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

React 第五十五节 Router 中 useAsyncError的使用详解

前言 useAsyncError 是 React Router v6.4 引入的一个钩子&#xff0c;用于处理异步操作&#xff08;如数据加载&#xff09;中的错误。下面我将详细解释其用途并提供代码示例。 一、useAsyncError 用途 处理异步错误&#xff1a;捕获在 loader 或 action 中发生的异步错误替…...

ubuntu搭建nfs服务centos挂载访问

在Ubuntu上设置NFS服务器 在Ubuntu上&#xff0c;你可以使用apt包管理器来安装NFS服务器。打开终端并运行&#xff1a; sudo apt update sudo apt install nfs-kernel-server创建共享目录 创建一个目录用于共享&#xff0c;例如/shared&#xff1a; sudo mkdir /shared sud…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

蓝桥杯 2024 15届国赛 A组 儿童节快乐

P10576 [蓝桥杯 2024 国 A] 儿童节快乐 题目描述 五彩斑斓的气球在蓝天下悠然飘荡&#xff0c;轻快的音乐在耳边持续回荡&#xff0c;小朋友们手牵着手一同畅快欢笑。在这样一片安乐祥和的氛围下&#xff0c;六一来了。 今天是六一儿童节&#xff0c;小蓝老师为了让大家在节…...

Nuxt.js 中的路由配置详解

Nuxt.js 通过其内置的路由系统简化了应用的路由配置&#xff0c;使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...

Nginx server_name 配置说明

Nginx 是一个高性能的反向代理和负载均衡服务器&#xff0c;其核心配置之一是 server 块中的 server_name 指令。server_name 决定了 Nginx 如何根据客户端请求的 Host 头匹配对应的虚拟主机&#xff08;Virtual Host&#xff09;。 1. 简介 Nginx 使用 server_name 指令来确定…...

爬虫基础学习day2

# 爬虫设计领域 工商&#xff1a;企查查、天眼查短视频&#xff1a;抖音、快手、西瓜 ---> 飞瓜电商&#xff1a;京东、淘宝、聚美优品、亚马逊 ---> 分析店铺经营决策标题、排名航空&#xff1a;抓取所有航空公司价格 ---> 去哪儿自媒体&#xff1a;采集自媒体数据进…...

动态 Web 开发技术入门篇

一、HTTP 协议核心 1.1 HTTP 基础 协议全称 &#xff1a;HyperText Transfer Protocol&#xff08;超文本传输协议&#xff09; 默认端口 &#xff1a;HTTP 使用 80 端口&#xff0c;HTTPS 使用 443 端口。 请求方法 &#xff1a; GET &#xff1a;用于获取资源&#xff0c;…...

免费数学几何作图web平台

光锐软件免费数学工具&#xff0c;maths,数学制图&#xff0c;数学作图&#xff0c;几何作图&#xff0c;几何&#xff0c;AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...

Python+ZeroMQ实战:智能车辆状态监控与模拟模式自动切换

目录 关键点 技术实现1 技术实现2 摘要&#xff1a; 本文将介绍如何利用Python和ZeroMQ消息队列构建一个智能车辆状态监控系统。系统能够根据时间策略自动切换驾驶模式&#xff08;自动驾驶、人工驾驶、远程驾驶、主动安全&#xff09;&#xff0c;并通过实时消息推送更新车…...