Python - 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(axis=0)if isinstance(benchmark, _pd.Series):benchmark = benchmark.resample(resample)benchmark = benchmark.last() if compound is True else benchmark.sum(axis=0)

第二个是把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_col=0)[['close']].pct_change().dropna().rename({'close':'return'},axis=1)['return'].rename("600900")#read benchmark data:  Seris格式,index为日期,列为return
benchmark  = pd.read_excel('000001.XSHG.xlsx',index_col=0)[['close']].pct_change().dropna().rename({'close':'return'},axis=1)['return'].rename("000001")qs.reports.html(stock,benchmark,output='report.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 Aroussi"from . import stats, utils, plots, reports__all__ = ["stats", "plots", "reports", "utils", "extend_pandas"]# try automatic matplotlib inline
utils._in_notebook(matplotlib_inline=True)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()

...正在更新

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/10357.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#,入门教程(13)——字符(char)及字符串(string)的基础知识

上一篇: C#,入门教程(12)——数组及数组使用的基础知识https://blog.csdn.net/beijinghorn/article/details/123918227 字符串的使用与操作是必需掌握得滚瓜烂熟的编程技能之一!!!!! C#语言实…

主流的AEB标准有哪些?

目录 1、AEB的技术构成与工作原理 2、典型应用场景举例 3、AEB的功能分类 4、AEB系统性能评估的关键因素 5、全球AEB技术标准概览 5.1、联合国欧洲经济委员会(UN ECE) 5.2、美国NHTSA法规 5.3、中国标准 5.4、印度AIS 185 5.5、澳大利亚ADR法规…

Linux网络 | 网络层IP报文解析、认识网段划分与IP地址

前言:本节内容为网络层。 主要讲解IP协议报文字段以及分离有效载荷。 另外, 本节也会带领友友认识一下IP地址的划分。 那么现在废话不多说, 开始我们的学习吧!! ps:本节正式进入网络层喽, 友友们…

基于Python的药物相互作用预测模型AI构建与优化(上.文字部分)

一、引言 1.1 研究背景与意义 在临床用药过程中,药物相互作用(Drug - Drug Interaction, DDI)是一个不可忽视的重要问题。当患者同时服用两种或两种以上药物时,药物之间可能会发生相互作用,从而改变药物的疗效、增加不良反应的发生风险,甚至危及患者的生命安全。例如,…

TCL C++开发面试题及参考答案

进程和线程的区别 进程和线程都是操作系统中重要的概念,它们在很多方面存在着明显的区别。 从概念上来说,进程是资源分配的基本单位,每个进程都有自己独立的地址空间、内存、文件描述符等资源。例如,当我们在计算机上同时运行多个应用程序,像浏览器、文本编辑器等,每个应…

如何获取当前的位置信息

文章目录 1 概念介绍2 使用方法3 示例代码3 体验分享 我们在上一章回中介绍了如何实现滑动菜单相关的内容,本章回中将介绍如何获取位置信息.闲话休提,让我们一起Talk Flutter吧。 1 概念介绍 我们在这里说的获取位置信息本质上是获取当前手机所在位置的…

python-leetcode-旋转链表

61. 旋转链表 - 力扣(LeetCode) # Definition for singly-linked list. # class ListNode: # def __init__(self, val0, nextNone): # self.val val # self.next next class Solution:def rotateRight(self, head: Optional[ListN…

基于排队理论的物联网发布/订阅通信系统建模与优化

论文标题 英文标题:Queuing Theory-Based Modeling and Optimization of a Publish/Subscribe IoT Communication System 中文标题:基于排队理论的物联网发布/订阅通信系统建模与优化 作者信息 Franc Pouhela Anthony Kiggundu Hans D. Schotten …

[EAI-026] DeepSeek-VL2 技术报告解读

Paper Card 论文标题:DeepSeek-VL2: Mixture-of-Experts Vision-Language Models for Advanced Multimodal Understanding 论文作者:Zhiyu Wu, Xiaokang Chen, Zizheng Pan, Xingchao Liu, Wen Liu, Damai Dai, Huazuo Gao, Yiyang Ma, Chengyue Wu, Bin…

基于Python的药物相互作用预测模型AI构建与优化(下.代码部分)

四、特征工程 4.1 分子描述符计算 分子描述符作为量化分子性质的关键数值,能够从多维度反映药物分子的结构和化学特征,在药物相互作用预测中起着举足轻重的作用。RDKit 库凭借其强大的功能,为我们提供了丰富的分子描述符计算方法,涵盖了多个重要方面的分子性质。 分子量…

【算法】动态规划专题① ——线性DP python

目录 引入简单实现稍加变形举一反三实战演练总结 引入 楼梯有个台阶,每次可以一步上1阶或2阶。一共有多少种不同的上楼方法? 怎么去思考? 假设就只有1个台阶,走法只有:1 只有2台阶: 11,2 只有3台…

0 基础学运维:解锁 K8s 云计算运维工程师成长密码

前言:作为一个过来人,我曾站在技术的门槛之外,连电脑运行内存和内存空间都傻傻分不清,完完全全的零基础。但如今,我已成长为一名资深的k8s云计算运维工程师。回顾这段历程,我深知踏上这条技术之路的艰辛与不…

事务03之MVCC机制

MVCC 多版本并发控制机制 文章目录 MVCC 多版本并发控制机制一:并发事务的场景1:读读场景2:写写场景3:读写 or 写读场景 二:MVCC机制综述1:MVCC日常生活的体现2:多版本并发控制 三:M…

数据结构-Stack和栈

1.栈 1.1什么是栈 栈是一种特殊的线性表,只允许在固定的一段进行插入和删除操作,进行插入和删除操作的一段称为栈顶,另一端称为栈底。 栈中的数据元素遵顼后进先出LIFO(Last In First Out)的原则,就像一…

langchain基础(二)

一、输出解析器(Output Parser) 作用:(1)让模型按照指定的格式输出; (2)解析模型输出,提取所需的信息 1、逗号分隔列表 CommaSeparatedListOutputParser:…

AI编程:如何编写提示词

这是小卷对AI编程工具学习的第2篇文章,今天讲讲如何编写AI编程的提示词,并结合实际功能需求案例来进行开发 1.编写提示词的技巧 好的提示词应该是:目标清晰明确,具有针对性,能引导模型理解问题 下面是两条提示词的对…

【B站保姆级视频教程:Jetson配置YOLOv11环境(五)Miniconda安装与配置】

B站同步视频教程:https://www.bilibili.com/video/BV1MwFDeyEYC/ 文章目录 0. Anaconda vs Miniconda in Jetson1. 下载Miniconda32. 安装Miniconda33. 换源3.1 conda 换源3.2 pip 换源 4. 创建环境5. 设置默认启动环境 0. Anaconda vs Miniconda in Jetson Jetson…

仿真设计|基于51单片机的无线投票系统仿真

目录 具体实现功能 设计介绍 51单片机简介 资料内容 仿真实现(protues8.7) 程序(Keil5) 全部内容 资料获取 具体实现功能 (1)投票系统分为发送端和接收端。 (2)发送端通过按…

玩转大语言模型——使用langchain和Ollama本地部署大语言模型

系列文章目录 玩转大语言模型——使用langchain和Ollama本地部署大语言模型 玩转大语言模型——ollama导入huggingface下载的模型 玩转大语言模型——langchain调用ollama视觉多模态语言模型 玩转大语言模型——使用GraphRAGOllama构建知识图谱 玩转大语言模型——完美解决Gra…

(动态规划基础 打家劫舍)leetcode 198

已知h2和h1&#xff0c;用已知推出未知 推是求答案&#xff0c;回溯是给答案 这里图片给出dfs暴力&#xff0c;再进行记录答案完成记忆化搜索&#xff0c;再转为dp数组 #include<iostream> #include<vector> #include<algorithm> //nums:2,1,1,2 //dp:2,2,…