def cal_factor_return(self, sf_ids): sfs = [] for sf_id in sf_ids: sfs.append( StockFactor.subclass(sf_id, StockFactor.stock_factors[sf_id])) close = StockAsset.all_stock_nav() ret = close.pct_change() ret = ret[StockAsset.all_stock_info().index] dates = ret.index dates = dates[dates > '2000-01-01'] df_ret = pd.DataFrame(columns=sf_ids) df_sret = pd.DataFrame(columns=StockAsset.all_stock_info().index) for date, next_date in zip(dates[:-1], dates[1:]): print 'cal_factor_return:', date tmp_exposure = {} tmp_ret = ret.loc[next_date].values for sf in sfs: tmp_exposure[sf.factor_id] = sf.exposure.loc[date] tmp_exposure_df = pd.DataFrame(tmp_exposure) tmp_exposure_df = tmp_exposure_df[sf_ids].fillna(0.0) tmp_exposure_df = tmp_exposure_df.loc[ StockAsset.all_stock_info().index] mod = sm.OLS(tmp_ret, tmp_exposure_df.values, missing='drop').fit() df_ret.loc[next_date] = mod.params df_sret.loc[next_date] = tmp_ret - np.dot(tmp_exposure_df.values, mod.params) return df_ret, df_sret
def cal_factor_return(self, sf_ids): period = 21 sfs = [] for sf_id in sf_ids: sfs.append( StockFactor.subclass(sf_id, StockFactor.stock_factors[sf_id])) close = StockAsset.all_stock_nav() ret = close.pct_change(period).iloc[period:] ret = ret[StockAsset.all_stock_info().index] dates = ret.index dates = dates[dates >= '2005-01-01'] df_ret = pd.DataFrame(columns=sf_ids) df_sret = pd.DataFrame(columns=StockAsset.all_stock_info().index) pool = Pool(len(sfs)) sfs = pool.map(multiprocess_load_factor_exposure, sfs) pool.close() pool.join() for date, next_date in zip(dates[:-period], dates[period:]): tmp_exposure = {} tmp_ret = ret.loc[next_date].values for sf in sfs: tmp_exposure[sf.factor_id] = sf.exposure.loc[date] #tmp_exposure[sf.factor_id] = fed[sf.factor_id].loc[date] tmp_exposure_df = pd.DataFrame(tmp_exposure) tmp_exposure_df = tmp_exposure_df[sf_ids].fillna(0.0) tmp_exposure_df = tmp_exposure_df.loc[ StockAsset.all_stock_info().index] mod = sm.OLS(tmp_ret, tmp_exposure_df.values, missing='drop').fit() # mod = sm.WLS(tmp_ret, tmp_exposure_df.values, weights = tmp_amount, missing = 'drop').fit() # print(mod.summary()) df_ret.loc[next_date] = mod.params df_sret.loc[next_date] = tmp_ret - np.dot(tmp_exposure_df.values, mod.params) return df_ret, df_sret