# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [Root]
#     language: python
#     name: Python [Root]
# ---

# # Fama French Momentum Factor
#
# ----------------
# #### FOR EDUCATIONAL USE ONLY. PLEASE SEE DISCLOSURE IN ROOT DIRECTORY OF REPOSITORY.
# ----------------
#
# http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/det_mom_factor.html

# +
import pandas as pd
from pandas_datareader import data, wb
from pandas_datareader.famafrench import get_available_datasets

import matplotlib.pyplot as plt
# %matplotlib inline

# -

get_available_datasets()

start_date = '1927-01-01'
end_date = '2016-12-31'

momo_df = data.DataReader( 'F-F_Momentum_Factor', 'famafrench',start=start_date, end=end_date)[0]
momo_df.columns = ['Momo']
momo_df.head()

momo_df.loc['2008-1-1':'2009-12-1',:]


# +
def compute_cumulative_returns(momo_df):
    momo_df = 1 + (momo_df / 100.)
    return momo_df.cumprod()['Momo']

momo_prices = compute_cumulative_returns(momo_df)
momo_prices.head()
# -

compute_cumulative_returns(momo_df).plot(logy=True)

momo_prices.iloc[0]


# +
def calculate_drawdown(prices):
    high_water_mark = prices.iloc[0]
    drawdown_amount = 0.
    drawdown_list = [0]
    for price in prices.iloc[1:]:
        if price > high_water_mark:
            drawdown_amount = 0.
            high_water_mark = price
        else:
            drawdown_amount = price / high_water_mark - 1
        drawdown_list.append(drawdown_amount) 
    
    return pd.Series(data=drawdown_list, index=prices.index)
    
momo_drawdown = calculate_drawdown(momo_prices)
                        
                
    

# +
fig, ax = plt.subplots(figsize=(10,6))

momo_drawdown.plot(ax=ax, color='red')
ax.set(title='Momo Factor Drawdown' , ylabel='Drawdown');
# -

spx_data = pd.read_csv('spx_monthly.csv', parse_dates=True, index_col='Date')
spx_data.head()

spx_drawdown = calculate_drawdown(spx_data.Close)
spx_drawdown.plot()
plt.title('S&P 500 Drawdown')
plt.ylabel('Drawdown');

momo_drawdown.index = momo_drawdown.index.to_timestamp()

drawdown_df = pd.concat([momo_drawdown, spx_drawdown],axis=1, join='inner')
drawdown_df.columns = ['momo', 'spx']
drawdown_df.head()


fig, ax = plt.subplots(figsize=(10,6))
drawdown_df.plot(ax=ax, color='rb')
plt.legend(loc='upper left', bbox_to_anchor=(1,1))
ax.set(title='Momo Factor Drawdowns vs. S&P 500 Drawdowns' , ylabel='Drawdown');

StarcoderdataJupyterScriptsDedupFiltered