# The 2014 Oil Price Crash: Why Brent Fell 72%
# https://www.jeroenbouma.com/articles/oil-price-crash-2014
#
# The code behind every chart in the article, in the order of the charts.
# Run it from top to bottom. Replace FINANCIAL_MODELING_PREP_KEY with your own key.
#
# pip install financetoolkit
from financetoolkit import Economics
import pandas as pd


# --- Brent and WTI crude oil prices, 2010 to 2017 ---
economics = Economics(start_date="2010-01-01")

prices = economics.get_commodity_prices()
oil = prices.loc["2010-01":"2017-12", ["Crude oil Brent", "Crude oil WTI"]]


# --- Oil, copper and aluminium prices around the 2014 and 2008 oil price peaks ---
economics = Economics(start_date="2008-01-01")

prices = economics.get_commodity_prices()
prices = prices[["Crude oil Brent", "Copper", "Aluminum"]]

# as an index with the month of the oil price peak at 100
recent = prices.loc["2014-01":"2016-12"]
recent = recent / recent.loc["2014-06"] * 100
earlier = prices.loc["2008-01":"2010-12"]
earlier = earlier / earlier.loc["2008-07"] * 100

# the change from the oil price peak to the low, in %
fall_2014 = (prices.loc["2016-01"] / prices.loc["2014-06"] - 1) * 100
fall_2008 = (prices.loc["2008-12"] / prices.loc["2008-07"] - 1) * 100


# --- Brent minus WTI, 2005 to 2017 ---
economics = Economics(start_date="2005-01-01")

prices = economics.get_commodity_prices()
spread = (prices["Crude oil Brent"] - prices["Crude oil WTI"]).loc["2005-01":"2017-12"]

average_2011_2013 = spread.loc["2011":"2013"].mean()
average_2016_2017 = spread.loc["2016":"2017"].mean()


# --- Currencies of oil exporters against the US dollar, 2014 to 2016 ---
economics = Economics(start_date="2014-01-01")

fx = economics.get_exchange_rates(period="daily")
fx.index = fx.index.astype(str)
fx = fx.loc["2014-01-01":"2016-12-31", ["Russia", "Kazakhstan", "Norway", "Canada", "Mexico", "Saudi Arabia"]]
fx = fx.dropna(how="all").ffill()

# as an index with the average of June 2014 at 100
fx = fx / fx.loc["2014-06-01":"2014-06-30"].mean() * 100


# --- Brent after the peaks of 1985, 2008 and 2014 ---
economics = Economics(start_date="1960-01-01")

brent = economics.get_commodity_prices()["Crude oil Brent"]


def crash(peak, months=48):
    after = brent.loc[peak:].iloc[: months + 1]
    return pd.Series((after / after.iloc[0] * 100).values)


crashes = pd.DataFrame({"1985": crash("1985-11"), "2008": crash("2008-07"), "2014": crash("2014-06")})
months_at_half_or_less = (crashes <= 50).sum()


# --- Oil prices and oil currencies, 2019 to 2021 ---
economics = Economics(start_date="2019-01-01")

prices = economics.get_commodity_prices()
oil = prices.loc["2019-01":"2021-12", ["Crude oil Brent", "Crude oil WTI"]]

fx = economics.get_exchange_rates(period="daily")
fx.index = fx.index.astype(str)
fx = fx.loc["2019-01-01":"2021-12-31", ["Russia", "Norway"]].dropna(how="all").ffill()

# as an index with the average of January 2020 at 100
fx = fx / fx.loc["2020-01-01":"2020-01-31"].mean() * 100

