
Qbot 中的 QuantStats 插件量化策略绩效分析与 HTML Tearsheet 报告实战指南【免费下载链接】Qbot[updating ...] AI 自动量化交易机器人(完全本地部署) AI-powered Quantitative Investment Research Platform. online docs: https://ufund-me.github.io/Qbot ✨ :news: qbot-mini: https://github.com/Charmve/iQuant项目地址: https://gitcode.com/GitHub_Trending/qbot/Qbot本文以 Qbot 仓库内置的 QuantStats 插件文档为主体系统讲解这个面向量化者的投资组合分析库的三大核心模块stats 指标计算、plots 可视化、reports 报告生成的使用方法并结合仓库内嵌的 0.0.59 版源码深入剖析extend_pandas()的 monkey-patch 机制、qs.reports.html()的完整参数默认值与模板渲染流程帮助读者在 Qbot 量化策略回测完成后快速产出包含绩效指标、回撤明细与滚动统计的专业级 HTML 分析报表。QuantStats 是什么三大模块与版本定位QuantStats 是一个用 Python 编写的组合分析Portfolio Analytics库其官方定位是Portfolio analytics for quants——通过提供深入的绩效分析与风险指标帮助量化研究员和组合管理者更好地理解策略表现。在 Qbot 仓库中它以插件形式完整内嵌在 qbot/plugins/quantstats 目录下与 Qbot 的量化回测/实盘体系配套使用策略回测产出收益序列之后QuantStats 负责把一串收益率转化为一份可汇报的绩效分析。从官方说明文档 qbot/plugins/quantstats/README.rst 看QuantStats 由 3 个主模块构成quantstats.stats—— 计算各类绩效指标如夏普比率Sharpe ratio、胜率Win rate、波动率Volatility等quantstats.plots—— 可视化绩效、回撤drawdowns、滚动统计、月度收益等quantstats.reports—— 生成指标报告、批量绘图并创建可保存为 HTML 文件的 tearsheet撕裂式全页分析报告。对应到仓库源码包入口 qbot/plugins/quantstats/quantstats/init.py 正是把这三个模块外加utils工具模块组装导出from . import plots, reports, stats, utils __all__ [stats, plots, reports, utils, extend_pandas]version.py 显示该插件版本为0.0.59CHANGELOG.rst 记录了该库的历史变更。安装方式与依赖环境文档给出的两种标准安装命令# 使用 pip 安装 $ pip install quantstats --upgrade --no-cache-dir # 使用 conda 安装 $ conda install -c ranaroussi quantstats文档中列出的依赖要求如下以当前仓库版本为准依赖版本要求Python 3.5pandas 0.24.0已测试可用numpy 1.15.0scipy 1.2.0matplotlib 3.0.0seaborn 0.9.0tabulate 0.8.0yfinance 0.1.38plotly 3.4.1可选用于plots.to_plotly()从源码结构看setup.py 的classifiers中声明的受支持解释器为Python 3.6 ~ 3.9许可协议为 Apache Software License2.0。依赖清单由 requirements.txt 提供并在打包时通过install_requiresrequirements注入。需要留意的是qs.utils.download_returns()这类联网取数函数依赖 yfinance在无外网环境Qbot 主打完全本地部署的场景下建议改用本地回测产出的收益 Series 直接喂给 QuantStats。快速上手extend_pandas() 与 Sharpe 计算文档给出的最小可运行示例%matplotlib inline import quantstats as qs # 用指标等函数扩展 pandas 的功能 qs.extend_pandas() # 获取一只股票的日收益率 stock qs.utils.download_returns(FB) # 显示 Sharpe ratio qs.stats.sharpe(stock) # 或者借助 extend_pandas() 直接调用 stock.sharpe() # 输出示例0.8135304438803402这个示例的核心是qs.extend_pandas()。阅读 qbot/plugins/quantstats/quantstats/init.py 中的extend_pandas()实现可以看到它对pandas.core.base.PandasObject即所有 pandas 对象的基类进行属性注入一次性绑定了几十个方法分四个层次收益/风险指标sharpe、smart_sharpe、sortino、omega、cagr、volatility、implied_volatility、skew、kurtosis、calmar、ulcer_index、serenity_index等尾部风险与交易统计value_at_risk/var、conditional_value_at_risk/cvar/expected_shortfall、tail_ratio、payoff_ratio、win_loss_ratio、profit_factor、kelly_criterion、risk_of_ruin等数据变换工具来自utilsto_returns、to_prices、to_log_returns、rebase、aggregate_returns、ytd/qtd/mtd等绘图与报告方法plot_snapshot、plot_drawdown、plot_monthly_heatmap等 15 个绘图方法以及metrics报告方法需要基准的方法r_squared、information_ratio、greeks、rolling_greeks、compare。这正是文档中or using extend_pandas() :)能成立的原因——注入后stock.sharpe()与qs.stats.sharpe(stock)等价。另外值得注意的细节是__init__.py第 31 行# try automatic matplotlib inline utils._in_notebook(matplotlib_inlineTrue)导入 quantstats 时会自动尝试在 Notebook 环境中执行%matplotlib inline这解释了为什么文档快速示例中还需要手动写一行%matplotlib inline——在非 notebook 的脚本环境中这行是无效的画图需显式plt.show()或依赖 plots 模块的savefig参数。指标函数本体位于 qbot/plugins/quantstats/quantstats/stats.py全文件 1000 余行。以文档示例中的conditional_value_at_risk为例其签名与说明help(qs.stats.conditional_value_at_risk) # Help on function conditional_value_at_risk in module quantstats.stats: # # conditional_value_at_risk(returns, sigma1, confidence0.99) # calculates the conditional daily value-at-risk (aka expected shortfall) # quantifies the amount of tail risk an investment文档特别提示由于完整在线文档尚标注为coming soon使用 Python 内置help()查看各方法的可选参数如sigma、confidence默认值是官方推荐的探索方式。可视化qs.plots.snapshot 与完整绘图函数清单文档给出的可视化示例qs.plots.snapshot(stock, titleFacebook Performance) # 也可以这样调用 # stock.plot_snapshot(titleFacebook Performance)snapshot会一次性输出包含累计收益曲线、回撤曲线、月度收益热图、滚动夏普/滚动波动率等子图的快照面板仓库内保留了官方生成的示例输出图 docs/snapshot.jpg见文首配图可作为解读snapshot各子图含义的参照。要查看全部可用的绘图方法运行[f for f in dir(qs.plots) if f[0] ! _]文档收录的完整清单如下[daily_returns, distribution, drawdown, drawdowns_periods, earnings, histogram, log_returns, monthly_heatmap, returns, rolling_beta, rolling_sharpe, rolling_sortino, rolling_volatility, snapshot, yearly_returns]从 qbot/plugins/quantstats/quantstats/plots.py 的源码结构看这些绘图函数统一经由_plotting子包含core.py底层绘制与wrappers.py包装层实现其中wrappers.py还提供了to_plotly()路径——将 matplotlib 图转换为 Plotly 交互图这依赖 requirements 中可选的 plotly并允许通过plotly.iplot输出交互页面。plots.py顶部还会注册 pandas 的 matplotlib 日期转换器register_matplotlib_converters保证时间轴刻度正确渲染。报告生成qs.reports 与 HTML Tearsheet文档列出了 QuantStats 提供的报告 tearsheet 类型qs.reports.metrics(modebasic|full, ...)—— 展示基础/完整指标表qs.reports.plots(modebasic|full, ...)—— 展示基础/完整图组qs.reports.basic(...)—— 展示基础指标与图表qs.reports.full(...)—— 展示完整指标与图表qs.reports.html(...)—— 生成完整 HTML 报告。其中html()是产出可存档 tearsheet 的入口。文档示例benchmark 可以是 pandas Series 或行情代码qs.reports.html(stock, SPY)生成的 HTML 报告中嵌入了完整指标矩阵、EOY 年度收益对比表、回撤明细表Top 10 回撤期以及 returns/drawdown/monthly heatmap 等图表。仓库内保留了官方 tearsheet 成品文件 qbot/plugins/quantstats/docs/tearsheet.html 与 qbot/plugins/quantstats/docs/quantstats-tearsheet.html可直接用浏览器打开核对报告的最终形态。结合 qbot/plugins/quantstats/quantstats/reports.py 中html()的实际签名各参数的默认值与约束如下def html( returns, benchmarkNone, # 基准Series / DataFrame / 行情代码或 None rf0.0, # 无风险利率默认 0 grayscaleFalse, # 是否灰度输出打印友好 titleStrategy Tearsheet, # 报告标题 outputNone, # 输出文件名非 notebook 环境必填 compoundedTrue, # 是否按复利口径计算 periods_per_year252, # 年化周期数股票常用 252 download_filenamequantstats-tearsheet.html, figfmtsvg, # 内嵌图表格式 template_pathNone, # 自定义 HTML 模板路径 match_datesFalse, # 是否对齐 returns 与 benchmark 的日期 **kwargs, ):几个从源码可确认的关键行为非 notebook 环境下output必填若output is None且当前不在 notebook 中html()会抛出ValueError(filemust be specified)reports.py 第 72-73 行。也就是说在 Qbot 的脚本化回测流水线里调用时务必传入如outputstats.html模板即代码默认模板是同目录下的report.htmltemplate_path or __file__[:-4] .html报告渲染本质是对模板占位符{{metrics}}、{{dd_info}}、{{eoy_table}}等做字符串替换因此可以用template_path提供自定义模板改写报告版式图表内嵌方式figfmtsvg表示图表以 SVG 编码内嵌进 HTML源码中通过base64.b64encode处理生成的单文件报告不依赖外部资源便于归档与邮件分发基准处理当传入benchmark时报告会增加EOY Returns vs Benchmark逐年对比表含 Multiplier / Won 列match_datesTrue会先通过_match_dates()将 returns 与 benchmark 裁剪到共同的起止日期区间。qs.stats 全量指标函数清单文档完整收录了qs.stats模块可用函数清单通过[f for f in dir(qs.stats) if f[0] ! _]得到这是使用 QuantStats 做绩效归因时的指标字典[avg_loss, avg_return, avg_win, best, cagr, calmar, common_sense_ratio, comp, compare, compsum, conditional_value_at_risk, consecutive_losses, consecutive_wins, cpc_index, cvar, drawdown_details, expected_return, expected_shortfall, exposure, gain_to_pain_ratio, geometric_mean, ghpr, greeks, implied_volatility, information_ratio, kelly_criterion, kurtosis, max_drawdown, monthly_returns, outlier_loss_ratio, outlier_win_ratio, outliers, payoff_ratio, profit_factor, profit_ratio, r2, r_squared, rar, recovery_factor, remove_outliers, risk_of_ruin, risk_return_ratio, rolling_greeks, ror, sharpe, skew, sortino, adjusted_sortino, tail_ratio, to_drawdown_series, ulcer_index, ulcer_performance_index, upi, utils, value_at_risk, var, volatility, win_loss_ratio, win_rate, worst]对照 stats.py 源码可以看到这些函数的统一设计模式多数指标函数都接受aggregate聚合粒度day/week/month/quarter/year、compounded是否复利、prepare_returns是否预处理收益序列三个可选项。例如expected_return(returns, aggregateNone, compoundedTrue, prepare_returnsTrue)通过几何持有期收益计算期望收益geometric_mean与ghpr都是它的别名best()/worst()分别取聚合周期内最高/最低单期收益consecutive_wins()/consecutive_losses()统计最大连盈/连亏期数实现上先aggregate_returns聚合再对布尔序列计数stats.py 第 135-150 行distribution(returns, compoundedTrue, prepare_returnsTrue)按 IQR 1.5 倍准则识别日/周/月/季/年各粒度的离群值输入为 DataFrame 时函数会自动降级若存在close列则取close否则取第一列并给出警告stats.py 第 63-73 行。这份指标体系覆盖了收益类cagr、rar、comp、风险类volatility、max_drawdown、value_at_risk、conditional_value_at_risk、风险收益比类sharpe、sortino、calmar、ulcer_index、交易行为类win_rate、payoff_ratio、profit_factor、kelly_criterion与基准相对类r_squared、information_ratio、greeks恰好对应 tearsheet 报告metrics(modefull)中输出的完整指标表。已知问题Known Issues文档明确记录了当前的一个已知问题由于无法让 seaborn 在指定保存时不显示月度收益热图即使通过savefig{...}保存monthly_heatmap图表仍会被渲染显示。在 Qbot 本地脚本环境中批量生成报表时若不希望终端弹出该图可以留意此行为必要时单独调用该图或使用grayscale/自定义模板绕过。QuantStats 与 Qbot 回测体系的衔接点在 Qbot 仓库中QuantStats 并不是孤立插件而是回测分析链路的一环。以 Qbot 的策略脚本为例qbot/strategies/boll_strategy_bt.py 中就保留了直接衔接回测收益与 tearsheet 的调用# quantstats.reports.html(returns, outputstats.html, titleBTC Sentiment)这一行注释代码展示了典型的接入姿势回测得到returns序列后直接交给qs.reports.html()并指定output与title即可产出一份以策略命名的绩效 HTML 报告。此外Qbot 的示例资料库中还有基于 QuantStats 的滚动分析 notebook docs/notebook/quantstats-rolling.ipynb 与成品报告页 docs/notebook/my_quant_stats.html可作为 tearsheet 在实际 A 股数据上的参照样例。小结围绕 qbot/plugins/quantstats/README.rst 这份插件文档本文完整覆盖了 QuantStats 在 Qbot 中的使用方法三大模块stats/plots/reports的职责划分、pip/conda 安装与 Python 3.6 依赖要求、extend_pandas()将指标方法注入 pandas 对象的机制源码位于 quantstats/init.py、qs.plots.snapshot快照图与 15 个绘图函数、qs.reports.html()的完整参数默认值与非 notebook 环境必须传output的硬约束、全量 59 个指标函数清单、help()探索方法以及 seaborn 月度热图的已知问题。对于在 Qbot 上完成策略回测的研究者将回测returns直接传入qs.reports.html(returns, benchmark, output..., title...)即可获得一份可直接归档汇报的单文件绩效报告。【免费下载链接】Qbot[updating ...] AI 自动量化交易机器人(完全本地部署) AI-powered Quantitative Investment Research Platform. online docs: https://ufund-me.github.io/Qbot ✨ :news: qbot-mini: https://github.com/Charmve/iQuant项目地址: https://gitcode.com/GitHub_Trending/qbot/Qbot创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考