当前位置: 首页 > news >正文

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()

...正在更新

相关文章:

Python - Quantstats量化投资策略绩效统计包 - 详解

使用Quantstats包做量化投资绩效统计的时候因为Pandas、Quantstats版本不匹配踩了一些坑;另外,Quantstats中的绩效统计指标非常全面,因此详细记录一下BUG修复方法、使用说明以及部分指标的内涵示意。 一、Quantstats安装及版本匹配问题 可以…...

智慧园区管理系统推动企业智能运维与资源优化的全新路径分析

内容概要 在当今快速发展的商业环境中,园区管理的数字化转型显得尤为重要。在这个背景下,快鲸智慧园区管理系统应运而生,成为企业实现高效管理的最佳选择。它通过整合互联网、物联网等先进技术,以智能化的方式解决了传统管理模式…...

【数据结构-字典树】力扣14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 “”。 示例 1: 输入:strs [“flower”,“flow”,“flight”] 输出:“fl” 示例 2: 输入:strs [“dog”,“racecar…...

《深入浅出HTTPS​​​​​​​​​​​​​​​​​》读书笔记(31):HTTPS和TLS/SSL

《深入浅出HTTPS​​​​​​​​​​》读书笔记(31):HTTPS和TLS/SSL TLS/SSL协议和应用层协议无关,它只是加密应用层协议(比如HTTP)并传递给下层的TCP。 HTTP和TLS/SSL协议组合在一起就是HTTPS, HTTPS等…...

Go学习:Go语言中if、switch、for语句与其他编程语言中相应语句的格式区别

Go语言中的流程控制语句逻辑结构与其他编程语言类似,格式有些不同。Go语言的流程控制中,包括if、switch、for、range、goto等语句,没有while循环。 目录 1. if 语句 2. switch语句 3. for语句 4. range语句 5. goto语句(不常用…...

L30.【LeetCode笔记】设计链表

1.题目 707. 设计链表 - 力扣(LeetCode) 你可以选择使用单链表或者双链表,设计并实现自己的链表。 单链表中的节点应该具备两个属性:val 和 next 。val 是当前节点的值,next 是指向下一个节点的指针/引用。 如果是双向…...

java日志框架详解-Log4j2

一、概述 Apache Log4j 2 (Log4j – Apache Log4j 2)是对Log4j的升级,它比其前身Log4j 1.x提供了重大改进,并参考了Logback中优秀的设计,同时修复了Logback架构中的一些问题。被誉为是目前最优秀的Java日志框架&#x…...

C++中vector追加vector

在C中,如果你想将一个vector追加到另一个vector的后面,可以使用std::vector的成员函数insert或者std::copy,或者简单地使用std::vector的push_back方法逐个元素添加。这里我将展示几种常用的方法: 方法1:使用insert方…...

加一(66)

66. 加一 - 力扣&#xff08;LeetCode&#xff09; 解法&#xff1a; class Solution { public:vector<int> plusOne(vector<int>& digits) {bool plus_one true;for (int i digits.size() - 1; i > 0; --i) {if (plus_one) {int tmp digits[i] 1;if …...

远程连接-简化登录

vscode通过ssh连接远程服务器免密登录&#xff08;图文&#xff09;_vscode ssh-CSDN博客...

canvas的基本用法

canvas canvas元素简介 1.是个container元素<canvas width100 height100></canvas>&#xff0c;有开闭标签 2.有且只有width和height两个attribute&#xff0c;不需要写单位 canvas的基本使用 const canvasEl document.getElementById(canvas01) const ctx …...

Tailwind CSS - Tailwind CSS 引入(安装、初始化、配置、引入、构建、使用 Tailwind CSS)

一、Tailwind CSS 概述 Tailwind CSS 是一个功能优先的 CSS 框架&#xff0c;它提供了大量的实用类&#xff08;utility classes&#xff09;&#xff0c;允许开发者通过组合这些类来快速构建用户界面 Tailwind CSS 与传统的 CSS 框架不同&#xff08;例如&#xff0c;Bootstr…...

鸿蒙开发黑科技“stack叠层”替代customdialog

前一篇提到的问题,本篇博文提出了一个解决方案: arkui-x LongPressGesture触发customdialog踩坑记录-CSDN博客 前一段时间遇到的这个问题,通过排除法观察,锁定为customdialog组件有bug,极为容易挂死。不论如何调整使用方法,都还是会触发挂死。 反馈给arkui团队,说是在…...

FreeRTOS从入门到精通 第十五章(事件标志组)

参考教程&#xff1a;【正点原子】手把手教你学FreeRTOS实时系统_哔哩哔哩_bilibili 一、事件标志组简介 1、概述 &#xff08;1&#xff09;事件标志位是一个“位”&#xff0c;用来表示事件是否发生。 &#xff08;2&#xff09;事件标志组是一组事件标志位的集合&#x…...

智慧园区管理平台实现智能整合提升企业运营模式与管理效率

内容概要 在当今数字化的背景下&#xff0c;智慧园区管理平台正逐渐成为企业提升运营效率和管理模式的重要工具。这个平台汇聚了多种先进技术&#xff0c;旨在通过智能整合各类资源与信息&#xff0c;帮助企业实现全面的管理创新。 智慧园区管理平台不仅仅是一个数据处理工具…...

markdown公式特殊字符

个人学习笔记 根号 在 Markdown 中&#xff0c;要表示根号 3&#xff0c;可以使用 LaTeX 语法来实现。常见的有以下两种方式&#xff1a; 行内公式形式&#xff1a;使用一对美元符号 $ 将内容包裹起来&#xff0c;即 $\sqrt{3}$ &#xff0c;在支持 LaTeX 语法渲染的 Markdow…...

【深度分析】微软全球裁员计划不影响印度地区,将继续增加当地就业机会

当微软的裁员刀锋掠过全球办公室时&#xff0c;班加罗尔的键盘声却愈发密集——这场资本迁徙背后&#xff0c;藏着数字殖民时代最锋利的生存法则。 表面是跨国公司的区域战略调整&#xff0c;实则是全球人才市场的地壳运动。微软一边在硅谷裁撤年薪20万美金的高级工程师&#x…...

学习数据结构(5)单向链表的实现

&#xff08;1&#xff09;头部插入 &#xff08;2&#xff09;尾部删除 &#xff08;3&#xff09;头部删除 &#xff08;4&#xff09;查找 &#xff08;5&#xff09;在指定位置之前插入节点 &#xff08;6&#xff09;在指定位置之后插入节点 &#xff08;7&#xff09;删除…...

刷题记录 HOT100回溯算法-5:22. 括号生成

题目&#xff1a;22. 括号生成 数字 n 代表生成括号的对数&#xff0c;请你设计一个函数&#xff0c;用于能够生成所有可能的并且 有效的 括号组合。 示例 1&#xff1a; 输入&#xff1a;n 3 输出&#xff1a;["((()))","(()())","(())()",…...

Keepalived高可用集群企业应用实例二

一、实现ipvs的高可用性 ipvs相关配置 虚拟服务器配置结构&#xff1a; virtual_server ip port { …… real_server { …… } real_server { …… } } virtual server (虚拟服务器)的定义格式 virtual_server ip port 定义虚拟主机ip地址及其端口 virtual_server …...

C++计算特定随机操作后序列元素乘积的期望

有一个长度为 n n n的序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1​,a2​,...,an​。初始序列的所有元素均为 0 0 0。再给定正整数 m m m、 c c c和 ( n − m 1 ) (n-m1) (n−m1)个正整数 b 1 , b 2 , . . . , b n − m 1 b_1,b_2,...,b_{n-m1} b1​,b2​,...,bn−m1​…...

c++字母大小写转换

可以通过标准库中的 <algorithm> 和 <cctype> 头文件来实现大小写转换。以下是常用的方法&#xff1a; 1. 使用 std::transform 和 std::toupper/std::tolower 1.1 转换为大写 #include <iostream> #include <string> #include <algorithm> //…...

MySQL知识点总结(十六)

请说明在复制拓扑中&#xff0c;中继日志集和从属服务器状态日志的作用。 中继日志用来保存从主服务器接受的二进制日志&#xff0c;与二进制日志相同的格式存储&#xff0c;由服务器自动管理&#xff0c;在其全部内容重放后会自动删除。 从属服务器状态日志存储关于如何连接…...

Windows程序设计10:文件指针及目录的创建与删除

文章目录 前言一、文件指针是什么&#xff1f;二、设置文件指针的位置&#xff1a;随机读写&#xff0c;SetFilePointer函数1.函数说明2.函数实例 三、 目录的创建CreateDirectory四、目录的删除RemoveDirectory总结 前言 Windows程序设计10&#xff1a;文件指针及目录的创建与…...

geolocator包的功能和用法

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

Node.js——body-parser、防盗链、路由模块化、express-generator应用生成器

个人简介 &#x1f440;个人主页&#xff1a; 前端杂货铺 &#x1f64b;‍♂️学习方向&#xff1a; 主攻前端方向&#xff0c;正逐渐往全干发展 &#x1f4c3;个人状态&#xff1a; 研发工程师&#xff0c;现效力于中国工业软件事业 &#x1f680;人生格言&#xff1a; 积跬步…...

22.Word:小张-经费联审核结算单❗【16】

目录 NO1.2 NO3.4​ NO5.6.7 NO8邮件合并 MS搜狗输入法 NO1.2 用ms打开文件&#xff0c;而不是wps❗不然后面都没分布局→页面设置→页面大小→页面方向→上下左右&#xff1a;页边距→页码范围&#xff1a;多页&#xff1a;拼页光标处于→布局→分隔符&#xff1a;分节符…...

Agent 高频知识汇总:查漏补缺参考大全

Agent 高频问题汇总 一、基础概念类 &#xff08;一&#xff09;请解释 Agent 的概念及其主要特点 Agent 是一种能够感知所处环境&#xff0c;并基于感知信息做出决策、采取行动以实现特定目标的实体。它既可以是简单的规则基系统&#xff0c;也能是复杂的智能体&#xff0c…...

本地化部署DeepSeek-R1

本文环境搭建均基于免费工具&#xff0c;感谢开源。 一、下载工具并安装 1. Ollama&#xff1a;最新版本 0.5.7 官网在这里 https://ollama.com/download 但是下载太慢&#xff0c;得换个思路 https://sourceforge.net/projects/ollama.mirror/ 2.Chatbox https://cha…...

验证二叉搜索数(98)

98. 验证二叉搜索树 - 力扣&#xff08;LeetCode&#xff09; 解法&#xff1a; /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* …...