import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import quandl
from scipy import stats
from sklearn.linear_model import LinearRegression

with open('../quandl_key.txt', 'r') as f:
    quandl.ApiConfig.api_key = f.read()

tickers = ['AAPL', 'MSFT', 'AMZN', 'F', 'AMD', 'FB', 'MTCH', 'SQ', 'TWTR', 'DPZ']
data = quandl.get_table('WIKI/PRICES', 
                        qopts={'columns':['ticker', 'date', 'adj_close']},
                        date={'gte':'2014-1-1', 'lte':datetime.today()},

data = data.pivot(columns='ticker', values='adj_close').groupby(pd.Grouper(freq="M")).last()
df_ret = data.pct_change(1).dropna()
# change day to 1'st to line up with FF data
df_ret.index = [pd.datetime(dt_.year, dt_.month, 1) for dt_ in df_ret.index]

# pfl rets for equal-weighted pfl
df_ret['PFL'] = sum([1/len(df_ret.columns) * df_ret[col] for col in df_ret.columns])

# https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html
df_ff = pd.read_csv('./data/F-F_Research_Data_Factors.CSV', 
                    date_parser=lambda x: pd.datetime.strptime(x, '%Y%m'))

df = df_ret.join(df_ff, how='inner')
df = df[df_ret.index[-1] - relativedelta(months=36):] # 3-year beta, last date is 2018-03-01

print('Stock | MFT_RF | SMB | HML\n---------------')
X = df[['MKT_RF', 'SMB', 'HML']]
for col in df_ret:
    reg = LinearRegression().fit(X=X, y=df[col]) # could use 'SPY' instead
    print(col, [round(coef, 3) for coef in reg.coef_])

My concern is I am using the default intercept from sklearn.linear_model.LinearRegression instead of directly plugging in the RF value from the Fama-French data. Also, I'm not 100% confident I didn't make a mistake somewhere else.

Any feedback would be very appreciated.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.