def __init__(self, trading_rec, param_cols): self.trarec_grp = trading_rec.groupby(param_cols) self.trading_rec = trading_rec self.bt_res = self.trarec_grp.apply( lambda x: gbt.BT_wCost(x)[0]).unstack(level=-1).fillna(np.nan) self.trec = self.trarec_grp.apply(lambda x: gbt.BT_wCost(x)[1]) self.trec_unstack = self.trec.unstack(param_cols) self.underly = self.trec['Underlying'].unique() self.indiv_tr = { ud: self.trec[self.trec['Underlying'] == ud] for ud in self.underly }
def print_basic(self, coerext='145500'): idx_coer = self.trec['dt_Exit'].dt.strftime('%H:%M:%S') == coerext coerext_pct = gfc.true_pct(idx_coer) print '%Coerce Exit: ', coerext_pct, '\n\n' if coerext_pct > 0: emat_coerce, trec_coerce = gbt.BT_wCost(self.trec[idx_coer]) emat_complete, trec_complete = gbt.BT_wCost(self.trec[~idx_coer]) coer_vs_compl = pd.concat([emat_coerce, emat_complete], 1, keys=['coerce', 'complete']).T print coer_vs_compl[['TotalReturn', 'WinLoss']] print coer_vs_compl.filter(like='count') print coer_vs_compl.filter(like='Long') print coer_vs_compl.filter(like='Short') else: print 'No coerce exit.'
def seperated_heatmap_parts(self, underly=None): if underly is None: underly = self.underly for ud in underly: tr = self.indiv_tr[ud] btr = tr.groupby(tr.index.names[:-1]).apply( lambda x: gbt.BT_wCost(x)[0]).unstack(-1).fillna(np.nan) self.heatmap_parts(bt_res=btr)
def cummulative_returns(self): # Cummulative Return cret0 = self.trec_unstack.loc[:, 'CumRet(RReturn)'].ffill() # Integration by refine_tradingRecord self.trarec_refined = gbt.refine_tradingRecord( self.trading_rec.sort_values('dt_Enter')) emat_int, trec_int = gbt.BT_wCost(self.trarec_refined) cret1 = pd.Series(trec_int['CumRet(RReturn)'], name='integrated') fig, ax = plt.subplots(figsize=(9, 10)) cret0.plot.line(grid=True, title=', '.join(self.underly), cmap=cm.rainbow, ax=ax) cret1.plot.line(ls='-.', color='k', grid=True, ax=ax, legend=True) fig.tight_layout(rect=(0, 0, 1, 1)) return fig, ax
tradingsignals = pd.DataFrame( [openlong, openshort, selllong, buycover], index=['openlong', 'openshort', 'selllong', 'buycover'], columns=df.index[win:]).T abprice = df[['ap1', 'bp1']] bt_data = pd.concat([abprice, tradingsignals], 1).ffill().dropna() bt_data[tradingsignals.columns] = bt_data[tradingsignals.columns].shift(2) bt_data.dropna(inplace=True) bt_data = bt_data.rename(columns={'ap1': 'ask', 'bp1': 'bid'}) daily_container.append([myc, bt_data]) colns, dfs = zip(*daily_container) tradingsignals_df = pd.concat(dfs, 1, keys=colns, names=['underly', 'signals']) tradingsignals_df = tradingsignals_df.ffill().dropna().stack('signals') # Backtest results trarec = gbt.generate_trading_records(tradingsignals_df) trarec['Underlying'] = 'stock' trarec.drop(['underly_Enter', 'underly_Exit'], axis=1, inplace=True) cn_ord_parts = [ 'dt_Enter', 'Price_Enter', 'Type_Enter', 'dt_Exit', 'Price_Exit', 'Type_Exit' ] trarec = trarec[cn_ord_parts + [cn for cn in trarec.columns if cn not in cn_ord_parts]] trarec_res = gbt.BT_wCost(trarec)
tradingsignals_df = pd.concat(dfs, 1, keys=colns, names=['underly', 'signals']) tradingsignals_df = tradingsignals_df.ffill().dropna().stack('signals') # In[] # Backtest results trarec = gbt.generate_trading_records(tradingsignals_df) trarec['Underlying'] = 'stock' trarec.drop(['underly_Enter', 'underly_Exit'], axis=1, inplace=True) cn_ord_parts = [ 'dt_Enter', 'Price_Enter', 'Type_Enter', 'dt_Exit', 'Price_Exit', 'Type_Exit' ] trarec = trarec[cn_ord_parts + [cn for cn in trarec.columns if cn not in cn_ord_parts]] emat, trec = gbt.BT_wCost(trarec) print '\nOverview Performance: \n', emat, print '\nTrading Logs: \n', trec # In[] # # Performance # import RiskAdjustedReturnMetrics as rarm # rr = trec['RReturn'].values # mr = np.random.uniform(-1, 1, trec.shape[0]) # # Expected return # e = np.mean(rr) # # Risk free rate # f = 0.06 # # Alpha