当前位置: 首页 > 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 …...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

蓝牙 BLE 扫描面试题大全(2):进阶面试题与实战演练

前文覆盖了 BLE 扫描的基础概念与经典问题蓝牙 BLE 扫描面试题大全(1)&#xff1a;从基础到实战的深度解析-CSDN博客&#xff0c;但实际面试中&#xff0c;企业更关注候选人对复杂场景的应对能力&#xff08;如多设备并发扫描、低功耗与高发现率的平衡&#xff09;和前沿技术的…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

C++中string流知识详解和示例

一、概览与类体系 C 提供三种基于内存字符串的流&#xff0c;定义在 <sstream> 中&#xff1a; std::istringstream&#xff1a;输入流&#xff0c;从已有字符串中读取并解析。std::ostringstream&#xff1a;输出流&#xff0c;向内部缓冲区写入内容&#xff0c;最终取…...

汇编常见指令

汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX&#xff08;不访问内存&#xff09;XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...

AspectJ 在 Android 中的完整使用指南

一、环境配置&#xff08;Gradle 7.0 适配&#xff09; 1. 项目级 build.gradle // 注意&#xff1a;沪江插件已停更&#xff0c;推荐官方兼容方案 buildscript {dependencies {classpath org.aspectj:aspectjtools:1.9.9.1 // AspectJ 工具} } 2. 模块级 build.gradle plu…...

R 语言科研绘图第 55 期 --- 网络图-聚类

在发表科研论文的过程中&#xff0c;科研绘图是必不可少的&#xff0c;一张好看的图形会是文章很大的加分项。 为了便于使用&#xff0c;本系列文章介绍的所有绘图都已收录到了 sciRplot 项目中&#xff0c;获取方式&#xff1a; R 语言科研绘图模板 --- sciRplothttps://mp.…...

Python 实现 Web 静态服务器(HTTP 协议)

目录 一、在本地启动 HTTP 服务器1. Windows 下安装 node.js1&#xff09;下载安装包2&#xff09;配置环境变量3&#xff09;安装镜像4&#xff09;node.js 的常用命令 2. 安装 http-server 服务3. 使用 http-server 开启服务1&#xff09;使用 http-server2&#xff09;详解 …...

Chromium 136 编译指南 Windows篇:depot_tools 配置与源码获取(二)

引言 工欲善其事&#xff0c;必先利其器。在完成了 Visual Studio 2022 和 Windows SDK 的安装后&#xff0c;我们即将接触到 Chromium 开发生态中最核心的工具——depot_tools。这个由 Google 精心打造的工具集&#xff0c;就像是连接开发者与 Chromium 庞大代码库的智能桥梁…...

【阅读笔记】MemOS: 大语言模型内存增强生成操作系统

核心速览 研究背景 ​​研究问题​​&#xff1a;这篇文章要解决的问题是当前大型语言模型&#xff08;LLMs&#xff09;在处理内存方面的局限性。LLMs虽然在语言感知和生成方面表现出色&#xff0c;但缺乏统一的、结构化的内存架构。现有的方法如检索增强生成&#xff08;RA…...