def bcolz_table_path(table_name, bundle='cninfo'): """bcolz文件路径""" root_dir = zipline_path(['bcolz', bundle]) if not os.path.exists(root_dir): os.makedirs(root_dir) path_ = os.path.join(root_dir, '{}.bcolz'.format(table_name)) return path_
def get_ff_factors(n): """读取3因子或5因子数据""" assert n in (3, 5), "仅支持3因子或5因子" file_name = f"ff{n}" root_dir = zipline_path(['factors']) result_path_ = os.path.join(root_dir, f'{file_name}.pkl') return pd.read_pickle(result_path_)
def get_backtest(dir_name=zipline_path(['backtest']), file_name=None): """获取最近的回测结果(数据框)""" if file_name is None: pref_file, _ = get_latest_backtest_info(dir_name) else: assert isinstance(file_name, str) assert file_name.endswith('.pkl'), '文件名必须带".pkl"扩展' pref_file = os.path.join(dir_name, file_name) return pd.read_pickle(pref_file)
def get_latest_backtest_info(dir_name=zipline_path(['backtest'])): """最新回测结果文件路径及更新时间""" assert os.path.isdir(dir_name) try: candidates = [os.path.join(dir_name, x) for x in os.listdir(dir_name)] most_recent = max(candidates, key=os.path.getmtime) return most_recent, pd.Timestamp(int(os.path.getmtime(most_recent)), unit='s', tz='Asia/Shanghai') except (ValueError, OSError) as e: if getattr(e, 'errno', errno.ENOENT) != errno.ENOENT: raise raise ValueError('在目录{}下,没有发现回测结果'.format(dir_name))
def backtest_result_path(): from zipline.utils import paths as pth ret = pth.zipline_path(['backtest']) pth.ensure_directory(ret) return ret
def show_draw_result(title, results_df, bundle): import matplotlib from matplotlib import gridspec import matplotlib.image as mpimg import matplotlib.pyplot as plt from zipline.utils import paths from datetime import datetime plt.style.use('ggplot') red = "#aa4643" blue = "#4572a7" black = "#000000" figsize = (18, 6) f = plt.figure(title, figsize=figsize) gs = gridspec.GridSpec(10, 8) # TODO draw logo # ax = plt.subplot(gs[:3, -1:]) # ax.axis("off") # filename = os.path.join(paths.zipline_root(), 'zipline.png') # img = mpimg.imread(filename) # imgplot = ax.imshow(img, interpolation="nearest") # ax.autoscale_view() # draw risk and portfolio series = results_df.iloc[-1] font_size = 12 value_font_size = 11 label_height, value_height = 0.8, 0.6 label_height2, value_height2 = 0.35, 0.15 fig_data = [ (0.00, label_height, value_height, "Total Returns", "{0:.3%}".format(series.algorithm_period_return), red, black), (0.15, label_height, value_height, "Annual Returns", "{0:.3%}".format(series.annualized_algorithm_return), red, black), (0.00, label_height2, value_height2, "Benchmark Total", "{0:.3%}".format(series.benchmark_period_return), blue, black), (0.15, label_height2, value_height2, "Benchmark Annual", "{0:.3%}".format(series.annualized_benchmark_return), blue, black), (0.30, label_height, value_height, "Alpha", "{0:.4}".format(series.alpha), black, black), (0.40, label_height, value_height, "Beta", "{0:.4}".format(series.beta), black, black), (0.55, label_height, value_height, "Sharpe", "{0:.4}".format(series.sharpe), black, black), (0.70, label_height, value_height, "Sortino", "{0:.4}".format(series.sortino), black, black), (0.85, label_height, value_height, "Information Ratio", "{0:.4}".format(series.information), black, black), (0.30, label_height2, value_height2, "Volatility", "{0:.4}".format(series.algo_volatility), black, black), (0.40, label_height2, value_height2, "MaxDrawdown", "{0:.3%}".format(series.max_drawdown), black, black), # (0.55, label_height2, value_height2, "Tracking Error", "{0:.4}".format(series.tracking_error), black, black), # (0.70, label_height2, value_height2, "Downside Risk", "{0:.4}".format(series.downside_risk), black, black), ] ax = plt.subplot(gs[:3, :-1]) ax.axis("off") for x, y1, y2, label, value, label_color, value_color in fig_data: ax.text(x, y1, label, color=label_color, fontsize=font_size) ax.text(x, y2, value, color=value_color, fontsize=value_font_size) # strategy vs benchmark ax = plt.subplot(gs[4:, :]) ax.get_xaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) ax.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) ax.grid(b=True, which='minor', linewidth=.2) ax.grid(b=True, which='major', linewidth=1) ax.plot(results_df["benchmark_period_return"], label="benchmark", alpha=1, linewidth=2, color=blue) ax.plot(results_df["algorithm_period_return"], label="algorithm", alpha=1, linewidth=2, color=red) # manipulate vals = ax.get_yticks() ax.set_yticklabels(['{:3.2f}%'.format(x * 100) for x in vals]) leg = plt.legend(loc="upper left") leg.get_frame().set_alpha(0.5) plt.show() now = datetime.now() paths.ensure_directory(paths.zipline_path(['perf'])) plt.savefig(filename=os.path.join( paths.zipline_path(['perf']), os.path.basename(title).split('.')[0] + '_' + bundle + '_' + now.strftime('%Y%m%dT%H%M%s') + '.png'))
df_rf = get_treasury_data(None, None)['3month'] df_rm = get_cn_benchmark_returns('000300') # 目标输出 rm_rf = df_rm - df_rf result = pd.DataFrame({ 'Mkt-RF': rm_rf.values, 'SMB': 0.0, 'HML': 0.0 }, index=rm_rf.index) result.loc[df_rf.index, 'RF'] = df_rf # 结果存放路径 file_name = "ff3" root_dir = zipline_path(['factors']) if not os.path.exists(root_dir): os.makedirs(root_dir) result_path_ = os.path.join(root_dir, f'{file_name}.pkl') class MarketEquity(CustomFactor): """ this factor outputs the market cap of every security on the day. """ window_length = 1 inputs = [USEquityPricing.market_cap] def compute(self, today, assets, out, mcap): out[:] = mcap[-1]