哪些企业必须用网站,网页改进方案,信息中心完成网站建设,凡客集团使用Quantstats包做量化投资绩效统计的时候因为Pandas、Quantstats版本不匹配踩了一些坑#xff1b;另外#xff0c;Quantstats中的绩效统计指标非常全面#xff0c;因此详细记录一下BUG修复方法、使用说明以及部分指标的内涵示意。
一、Quantstats安装及版本匹配问题
可以…使用Quantstats包做量化投资绩效统计的时候因为Pandas、Quantstats版本不匹配踩了一些坑另外Quantstats中的绩效统计指标非常全面因此详细记录一下BUG修复方法、使用说明以及部分指标的内涵示意。
一、Quantstats安装及版本匹配问题
可以在cmd界面分别通过下面代码查询python/pandas/quantstats的版本。
python - version
pip show pandas
pip show quantstats
我使用的是截止到文章发布时点的最新版本
Python 3.12.8
Pandas 2.2.3
Quantstats 0.0.64上述版本组合在Quantstats生成绩效统计页面时因为Quantstats包没及时随着Pandas包的更新会报两个错需要修改Quantstats包。第一个是在Quantstats目录下_plotting文件夹下的core.py文件中294-297行要去掉sum函数的传参因为新的2.2.3版本Pandas这里没有参数。 if resample:returns returns.resample(resample)returns returns.last() if compound is True else returns.sum(axis0)if isinstance(benchmark, _pd.Series):benchmark benchmark.resample(resample)benchmark benchmark.last() if compound is True else benchmark.sum(axis0)
第二个是把1015-1025行的inplace方法重写成以下形式新版本Pandas不支持inplace。 port[Weekly] port[Daily].resample(W-MON).apply(apply_fnc)port[Weekly] port[Weekly].ffill()port[Monthly] port[Daily].resample(ME).apply(apply_fnc)port[Monthly] port[Monthly].ffill()port[Quarterly] port[Daily].resample(QE).apply(apply_fnc)port[Quarterly] port[Quarterly].ffill()port[Yearly] port[Daily].resample(YE).apply(apply_fnc)port[Yearly] port[Yearly].ffill()
上面修订提交了GITHUBGitHub - ranaroussi/quantstats: Portfolio analytics for quants, written in Python
二、Quantstats的使用
QuantStatus由3个主要模块组成
quantstats.stats-用于计算各种绩效指标如夏普比率、胜率、波动率等。
quantstats.plots-用于可视化绩效、滚动统计、月度回报等。
quantstats.reports-用于生成指标报告、批量绘图和创建可另存为HTML文件。
以持有长江电力600900为策略以上证综指000001为基准生成reports如下。EXCEL数据附后没会员下不了附件的可以私我发。
import pandas as pd
import quantstats as qs#read stock data Seris格式index为日期列为return
stock pd.read_excel(600900.XSHG.xlsx,index_col0)[[close]].pct_change().dropna().rename({close:return},axis1)[return].rename(600900)#read benchmark data: Seris格式index为日期列为return
benchmark pd.read_excel(000001.XSHG.xlsx,index_col0)[[close]].pct_change().dropna().rename({close:return},axis1)[return].rename(000001)qs.reports.html(stock,benchmark,outputreport.html) 三、指标详解
Quantstats有六个模块 其中extend_pandas的功能是可以实现通过Dataframe对象.方法()的方式调用QuantStatsd中的方法例如df.sharpe()实现方式如下
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# QuantStats: Portfolio analytics for quants
# https://github.com/ranaroussi/quantstats
#
# Copyright 2019-2024 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an AS IS BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.from . import version__version__ version.version
__author__ Ran Aroussifrom . import stats, utils, plots, reports__all__ [stats, plots, reports, utils, extend_pandas]# try automatic matplotlib inline
utils._in_notebook(matplotlib_inlineTrue)def extend_pandas():Extends pandas by exposing methods to be used like:df.sharpe(), df.best(day), ...from pandas.core.base import PandasObject as _po_po.compsum stats.compsum_po.comp stats.comp_po.expected_return stats.expected_return_po.geometric_mean stats.geometric_mean_po.ghpr stats.ghpr_po.outliers stats.outliers_po.remove_outliers stats.remove_outliers_po.best stats.best_po.worst stats.worst_po.consecutive_wins stats.consecutive_wins_po.consecutive_losses stats.consecutive_losses_po.exposure stats.exposure_po.win_rate stats.win_rate_po.avg_return stats.avg_return_po.avg_win stats.avg_win_po.avg_loss stats.avg_loss_po.volatility stats.volatility_po.rolling_volatility stats.rolling_volatility_po.implied_volatility stats.implied_volatility_po.sharpe stats.sharpe_po.smart_sharpe stats.smart_sharpe_po.rolling_sharpe stats.rolling_sharpe_po.sortino stats.sortino_po.smart_sortino stats.smart_sortino_po.adjusted_sortino stats.adjusted_sortino_po.rolling_sortino stats.rolling_sortino_po.omega stats.omega_po.cagr stats.cagr_po.rar stats.rar_po.skew stats.skew_po.kurtosis stats.kurtosis_po.calmar stats.calmar_po.ulcer_index stats.ulcer_index_po.ulcer_performance_index stats.ulcer_performance_index_po.upi stats.upi_po.serenity_index stats.serenity_index_po.risk_of_ruin stats.risk_of_ruin_po.ror stats.ror_po.value_at_risk stats.value_at_risk_po.var stats.var_po.conditional_value_at_risk stats.conditional_value_at_risk_po.cvar stats.cvar_po.expected_shortfall stats.expected_shortfall_po.tail_ratio stats.tail_ratio_po.payoff_ratio stats.payoff_ratio_po.win_loss_ratio stats.win_loss_ratio_po.profit_ratio stats.profit_ratio_po.profit_factor stats.profit_factor_po.gain_to_pain_ratio stats.gain_to_pain_ratio_po.cpc_index stats.cpc_index_po.common_sense_ratio stats.common_sense_ratio_po.outlier_win_ratio stats.outlier_win_ratio_po.outlier_loss_ratio stats.outlier_loss_ratio_po.recovery_factor stats.recovery_factor_po.risk_return_ratio stats.risk_return_ratio_po.max_drawdown stats.max_drawdown_po.to_drawdown_series stats.to_drawdown_series_po.kelly_criterion stats.kelly_criterion_po.monthly_returns stats.monthly_returns_po.pct_rank stats.pct_rank_po.treynor_ratio stats.treynor_ratio_po.probabilistic_sharpe_ratio stats.probabilistic_sharpe_ratio_po.probabilistic_sortino_ratio stats.probabilistic_sortino_ratio_po.probabilistic_adjusted_sortino_ratio (stats.probabilistic_adjusted_sortino_ratio)# methods from utils_po.to_returns utils.to_returns_po.to_prices utils.to_prices_po.to_log_returns utils.to_log_returns_po.log_returns utils.log_returns_po.exponential_stdev utils.exponential_stdev_po.rebase utils.rebase_po.aggregate_returns utils.aggregate_returns_po.to_excess_returns utils.to_excess_returns_po.multi_shift utils.multi_shift_po.curr_month utils._pandas_current_month_po.date utils._pandas_date_po.mtd utils._mtd_po.qtd utils._qtd_po.ytd utils._ytd# methods that requires benchmark stats_po.r_squared stats.r_squared_po.r2 stats.r2_po.information_ratio stats.information_ratio_po.greeks stats.greeks_po.rolling_greeks stats.rolling_greeks_po.compare stats.compare# plotting methods_po.plot_snapshot plots.snapshot_po.plot_earnings plots.earnings_po.plot_daily_returns plots.daily_returns_po.plot_distribution plots.distribution_po.plot_drawdown plots.drawdown_po.plot_drawdowns_periods plots.drawdowns_periods_po.plot_histogram plots.histogram_po.plot_log_returns plots.log_returns_po.plot_returns plots.returns_po.plot_rolling_beta plots.rolling_beta_po.plot_rolling_sharpe plots.rolling_sharpe_po.plot_rolling_sortino plots.rolling_sortino_po.plot_rolling_volatility plots.rolling_volatility_po.plot_yearly_returns plots.yearly_returns_po.plot_monthly_heatmap plots.monthly_heatmap_po.metrics reports.metrics# extend_pandas()...正在更新