def show_fig(self, fig, file_name): """ Save fig object to self.output_folder/filename. Parameters ---------- fig : matplotlib.figure.Figure file_name : str """ self.fig_objs[file_name] = fig if self.output_format in ['pdf', 'png', 'jpg']: fp = os.path.join(self.output_folder, '.'.join([file_name, self.output_format])) jutil.create_dir(fp) fig.savefig(fp) print("Figure saved: {}".format(fp)) elif self.output_format == 'base64': fig_b64 = jutil.fig2base64(fig, 'png') self.fig_data[file_name] = fig_b64 print("Base64 data of figure {} will be stored in dictionary.". format(file_name)) elif self.output_format == 'plot': fig.show() else: raise NotImplementedError("output_format = {}".format( self.output_format))
def save_results(self, folder_path='.'): import os import pandas as pd folder_path = os.path.abspath(folder_path) trades = self.ctx.pm.trades type_map = {'task_id': str, 'entrust_no': str, 'entrust_action': str, 'symbol': str, 'fill_price': float, 'fill_size': float, 'fill_date': int, 'fill_time': int, 'fill_no': str, 'commission': float} # keys = trades[0].__dict__.keys() ser_list = dict() for key in type_map.keys(): v = [t.__getattribute__(key) for t in trades] ser = pd.Series(data=v, index=None, dtype=type_map[key], name=key) ser_list[key] = ser df_trades = pd.DataFrame(ser_list) df_trades.index.name = 'index' trades_fn = os.path.join(folder_path, 'trades.csv') configs_fn = os.path.join(folder_path, 'configs.json') jutil.create_dir(trades_fn) df_trades.to_csv(trades_fn) jutil.save_json(self.props, configs_fn) print ("Backtest results has been successfully saved to:\n" + folder_path)
def test_io(): folder_relative = 'output/test/test_file_io' folder = jutil.join_relative_path(folder_relative) fp = jutil.join_relative_path(folder_relative + '/file.postfix') jutil.create_dir(fp) jutil.create_dir(folder)
def show_fig(self, fig, file_name): """ Save fig object to self.output_folder/filename. Parameters ---------- fig : matplotlib.figure.Figure file_name : str """ self.fig_objs[file_name] = fig if self.output_format in ['pdf', 'png', 'jpg']: fp = os.path.join(self.output_folder, '.'.join([file_name, self.output_format])) jutil.create_dir(fp) fig.savefig(fp) print("Figure saved: {}".format(fp)) elif self.output_format == 'base64': fig_b64 = jutil.fig2base64(fig, 'png') self.fig_data[file_name] = fig_b64 print("Base64 data of figure {} will be stored in dictionary.".format(file_name)) elif self.output_format == 'plot': fig.show() else: raise NotImplementedError("output_format = {}".format(self.output_format))
def save_results(self, folder_path='.'): import os import pandas as pd folder_path = os.path.abspath(folder_path) trades = self.ctx.pm.trades type_map = {'task_id': str, 'entrust_no': str, 'entrust_action': str, 'symbol': str, 'fill_price': float, 'fill_size': float, 'fill_date': np.integer, 'fill_time': np.integer, 'fill_no': str, 'commission': float} # keys = trades[0].__dict__.keys() ser_list = dict() for key in type_map.keys(): v = [t.__getattribute__(key) for t in trades] ser = pd.Series(data=v, index=None, dtype=type_map[key], name=key) ser_list[key] = ser df_trades = pd.DataFrame(ser_list) df_trades.index.name = 'index' trades_fn = os.path.join(folder_path, 'trades.csv') configs_fn = os.path.join(folder_path, 'configs.json') jutil.create_dir(trades_fn) df_trades.to_csv(trades_fn) jutil.save_json(self.props, configs_fn) print ("Backtest results has been successfully saved to:\n" + folder_path)
def output_html(self, fn='test_out.html'): path = os.path.abspath(os.path.join(self.out_folder, fn)) jutil.create_dir(path) with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.html) print("HTML report: {:s}".format(path))
def do_analyze(self, result_dir, selected_sec=None): """ Convenient function to do a series of analysis. The reason why define these separate steps and put them in one function is this function is convenient for common users but advanced users can still customize. Parameters ---------- result_dir selected_sec Returns ------- """ jutil.create_dir( os.path.join(os.path.abspath(result_dir), 'dummy.dummy')) if selected_sec is None: selected_sec = [] print("process trades...") self.process_trades() print("get daily stats...") self.get_daily() print("calc strategy return...") self.get_returns(consider_commission=True) if len(selected_sec) > 0: print("Plot single securities PnL") for symbol in selected_sec: df_daily = self.daily.loc[pd.IndexSlice[symbol, :], :] df_daily.index = df_daily.index.droplevel(0) if df_daily is not None: plot_trades(df_daily, symbol=symbol, output_folder=result_dir) print("Plot strategy PnL...") self.plot_pnl(result_dir) print("generate report...") self.gen_report(source_dir=STATIC_FOLDER, template_fn='report_template.html', out_folder=result_dir, selected=selected_sec)
def _save_h5(fp, dic): """ Save data in dic to a hd5 file. Parameters ---------- fp : str File path. dic : dict """ import warnings warnings.filterwarnings('ignore', category=pd.io.pytables.PerformanceWarning) jutil.create_dir(fp) h5 = pd.HDFStore(fp, complevel=9, complib='blosc') for key, value in dic.items(): h5[key] = value h5.close()