Like that? Sorry, First time using Forums as well
#packages from IPython import get_ipython get_ipython().magic('reset -sf') import numpy as np import pandas as pd import datetime as dt import matplotlib as mpl import matplotlib.pyplot as plt get_ipython().magic('matplotlib inline') import pandas_datareader.data as web from pandas_datareader.famafrench import get_available_datasets import quandl import statsmodels.formula.api as smf import statsmodels.api as sm from scipy.optimize import minimize from datetime import datetime from zipline.api import order, symbol, record, order_target from zipline.utils.factory import load_bars_from_yahoo from zipline.algorithm import TradingAlgorithm from zipline.data.bundles import register, yahoo_equities from zipline.api import symbol, order, record, history import zipline import pytz from collections import OrderedDict #%% #Fetching and cleaning data, compute returns myassets = 'AAPL GOOG' #type(myassets) myassets = myassets.split() #define beginning date and time start_date = '2014-01-01' end_date = '2015-12-31' #extract data from yahoo data = web.DataReader(myassets, 'yahoo', start_date, end_date) data.items #data.items = [x.lower() for x in data.items] data.items=['open', 'high', 'low', 'close', 'volume', 'adjclose'] #changing to lower case and adjclose together prices=pd.DataFrame(data.adjclose, index=data.major_axis, columns=data.minor_axis) returns=(prices/prices.shift(1))-1 #%% #Download Fama French factors ff = web.DataReader("F-F_Research_Data_Factors_daily", "famafrench",start=start_date, end=end_date) ff = pd.DataFrame(ff[0]/100) #tranform the % values of factors to decimals ff.columns = (['mktrf', 'smb', 'hml', 'rf']) #change to lower case, and prettier look :) #join returns of assets and risk free return_rf = returns.join(ff.rf, how='inner') #inner=intersection, and outer=union #join returns of assets and all factors return_all = returns.join(ff, how='inner') #return_3 = returns.join([ff.rf, ff.smb], how='inner') #only two factors #%% #Regressions betas = [] for id in return_all.columns: formula = id + '~mktrf' res = smf.ols(formula = formula, data = return_all).fit() betas.append(res.params[1]) betas = (betas) betas = pd.DataFrame([betas], columns=return_all.columns) #%% #Minimizations #Minimize variance of portfolio and beta below 2,5 def PtfVar(w,b,vcv): temp = w.dot(vcv).dot(w.T) return temp w = pd.DataFrame([],index=data.major_axis, columns=data.minor_axis) for id in data.major_axis[::]: b = np.matrix(betas) #b = np.matrix(betas.iloc[-1,:]) vcv = np.array(return_all.loc[:,:].cov()) #vcv = np.array(return_all.loc[t-pd.DateOffset(days = 365):t,:].cov()) cons = ({'type': 'ineq', 'fun' : lambda x,b: 0.2-abs(x.dot(b.T)), 'args': (b,)}, {'type':'eq', 'fun': lambda x: x.sum()-1}) res = minimize(PtfVar, np.ones((1,6))/6 , args=(b,vcv,),constraints=cons,options={'disp': True,'ftol':1e-12}, method='SLSQP')#, jac=func_deriv, options={'disp': True}) w.loc[t,:]=res.x