打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
empyrical、pyfolio工具介绍及在backtrader量化框架中使用
userphoto

2022.05.28 浙江

关注

简介

  • empyrical -- Quantopian开源的常见金融风险指标lib库,会调用pandas_datareader从yahoo或google获取股票数据
  • pyfolio -- Quantopian开源的用图形表示的金融投资组合性能和风险分析的Python库,基于empyrical获取数据和计算基础指标,由各种各样的独立图组成,这些图提供了交易策略表现的综合图像。图形示例可以参考full_tear_sheet_example.ipynb

empyrical安装&使用

  • 安装:pip install empyrical
  • 使用方法:以计算最大回撤和alpha、beta为例,代码如下。
import numpy as np
from empyrical import max_drawdown, alpha_beta
returns = np.array([.01.02.03-.4-.06-.02])
benchmark_returns = np.array([.02.02.03-.35-.05-.01])
max_drawdown(returns) # 计算最大回撤
alpha, beta = alpha_beta(returns, benchmark_returns) # 计算alpha和beta
returns = pd.Series([.01.02.03-.4-.06-.02]) #支持pd.Series()
max_drawdown(returns)

查看empyrical支持的api列表,如下。

import empyrical
print(dir(empyrical))

结果是:

['DAILY''MONTHLY''QUARTERLY''WEEKLY''YEARLY''__builtins__''__cached__''__doc__''__file__''__loader__''__name__''__package__''__path__''__spec__''__version__''_version''aggregate_returns''alpha''alpha_aligned''alpha_beta''alpha_beta_aligned''annual_return''annual_volatility''beta''beta_aligned''beta_fragility_heuristic''beta_fragility_heuristic_aligned''cagr''calmar_ratio''capture''compute_exposures''conditional_value_at_risk''cum_returns''cum_returns_final''deprecate''down_alpha_beta''down_capture''downside_risk''excess_sharpe''gpd_risk_estimates''gpd_risk_estimates_aligned''max_drawdown''omega_ratio''perf_attrib''periods''roll_alpha''roll_alpha_aligned''roll_alpha_beta''roll_alpha_beta_aligned''roll_annual_volatility''roll_beta''roll_beta_aligned''roll_down_capture''roll_max_drawdown''roll_sharpe_ratio''roll_sortino_ratio''roll_up_capture''roll_up_down_capture''sharpe_ratio''simple_returns''sortino_ratio''stability_of_timeseries''stats''tail_ratio''up_alpha_beta''up_capture''up_down_capture''utils''value_at_risk']

顺便说明下,empyrical官方api手册不全,看api文档使用help来看比较方便,如help(empyrical.excess_sharpe)

pyfolio安装&使用

pyfolio只能在jupyter notebook环境下完整绘图,在命令行环境或py文件下可以单独画图,但不能显示表格数据。

通常的误区是:pyfolio只能在jupyter下使用。正确的说法是pyfolio对jupyter环境下支持的最好。

  • 安装:
pip install git+https://github.com/quantopian/pyfolio

使用pip install pyfolio,在使用的时候会报错,下面会说明。

  • 使用方法:
  1. 构造数据 产出如下数据,格式为pd.series。
data.head()
Date
2017-04-25 00:00:00+00:00    0.018699
2017-04-26 00:00:00+00:00   -0.011536
2017-04-27 00:00:00+00:00   -0.004965
2017-04-28 00:00:00+00:00    0.017626
2017-05-01 00:00:00+00:00    0.027892
dtype: float64
  1. 使用pyfolio
import pyfolio as pf
pf.create_returns_tear_sheet(data)
pf.plot_drawdown_periods(data)

在jupyter中运行,结果如下:

在ipython运行,结果如下:

In [8]: pf.create_returns_tear_sheet(data)
<IPython.core.display.HTML object>
<IPython.core.display.HTML object>

In [9]: ret = pf.create_returns_tear_sheet(data)
<IPython.core.display.HTML object>
<IPython.core.display.HTML object>

pf.plot_drawdown_periods(data)

import matplotlib.pyplot as plt

plt.show()
  • 查看支持的函数:
print(dir(pf))

['APPROX_BDAYS_PER_MONTH', 'FACTOR_PARTITIONS', 'FigureCanvasAgg', 'FuncFormatter', 'MM_DISPLAY_UNIT', 'Markdown', 'OrderedDict', 'STAT_FUNCS_PCT', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_seaborn', '_version', 'axes_style', 'capacity', 'create_capacity_tear_sheet', 'create_full_tear_sheet', 'create_interesting_times_tear_sheet', 'create_perf_attrib_tear_sheet', 'create_position_tear_sheet', 'create_returns_tear_sheet', 'create_round_trip_tear_sheet', 'create_simple_tear_sheet', 'create_txn_tear_sheet', 'customize', 'datetime', 'deprecate', 'display', 'division', 'ep', 'figure', 'gridspec', 'interesting_periods', 'matplotlib', 'np', 'patches', 'pd', 'perf_attrib', 'plot_annual_returns', 'plot_capacity_sweep', 'plot_cones', 'plot_daily_turnover_hist', 'plot_daily_volume', 'plot_drawdown_periods', 'plot_drawdown_underwater', 'plot_exposures', 'plot_gross_leverage', 'plot_holdings', 'plot_long_short_holdings', 'plot_max_median_position_concentration', 'plot_monthly_returns_dist', 'plot_monthly_returns_heatmap', 'plot_monthly_returns_timeseries', 'plot_perf_stats', 'plot_prob_profit_trade', 'plot_return_quantiles', 'plot_returns', 'plot_rolling_beta', 'plot_rolling_returns', 'plot_rolling_sharpe', 'plot_rolling_volatility', 'plot_round_trip_lifetimes', 'plot_sector_allocations', 'plot_slippage_sensitivity', 'plot_slippage_sweep', 'plot_turnover', 'plot_txn_time_hist', 'plotting', 'plotting_context', 'plt', 'pos', 'pytz', 'round_trips', 'show_and_plot_top_positions', 'show_perf_stats', 'show_profit_attribution', 'show_worst_drawdown_periods', 'sns', 'sp', 'tears', 'time', 'timer', 'timeseries', 'txn', 'utils', 'warnings', 'wraps']

  • 常见错误
  1. 报错:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

解决办法:pf.create_returns_tear_sheet()的参数是pd.series,不能是pd.dataframe

  1. 报错:AttributeError: 'numpy.int64' object has no attribute 'to_pydatetime'

解决办法:

pip install git+https://github.com/quantopian/pyfolio

在backtrader中使用PyFolio

pyfolio改变过api接口,create_full_tear_sheet()函数后面没有了gross_lev参数,使用backtrade网站的示例代码会报错。参考pyfolio官方的使用文档即可。

backtrader使用pyfolio示例代码如下:

cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
strats = cerebro.run()
strat0 = strats[0]
pyfolio = strats.analyzers.getbyname('pyfolio')
returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
import pyfolio as pf
pf.create_full_tear_sheet(returns)

交流

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Backtrader版本“积木式”AI量化回测系统(全部源代码+数据下载)
细数7大算法交易工具
beta收益和alpha收益是什么意思?
文件同步更新之Rsync算法的探讨
太阳活动预报中心
七叶皂苷钠
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服