kepler-metric | 金融风险指标计算库
概述
kepler-metric 是一个用于计算金融风险和绩效指标的 Python 库。基于 Quantopian Inc. 开发的 empyrical,经过现代化重构,为量化金融专业人士和研究人员提供了全面的工具集。
特性
- 现代化架构:模块化设计,清晰的代码结构
- 完整的指标:超过 50 个金融指标,包括收益、风险、风险调整收益和市场关系
- DataFrame 支持:当输入为 DataFrame 时,所有函数返回带列名的 pandas Series
- 灵活输入:支持 pandas Series/DataFrame 和 numpy 数组
- 类型注解:完整的 Python 3.10+ 类型提示
- Portfolio 类:高级接口,一次计算多个指标
安装
pip install kepler-metric
注意:虽然 PyPI 包名是 kepler-metric,但导入时仍然使用 kepler.metric:
import kepler.metric
快速开始
import pandas as pd
import numpy as np
from kepler.metric import (
max_drawdown, sharpe, total_return,
volatility, calmar, Portfolio, analyze
)
# 创建示例收益率数据
np.random.seed(42)
returns = pd.DataFrame(
np.random.normal(0.001, 0.02, (252, 3)),
columns=['Strategy_A', 'Strategy_B', 'Strategy_C']
)
# 计算各种指标
metrics = {
'Total Return': total_return(returns),
'Max Drawdown': max_drawdown(returns),
'Sharpe': sharpe(returns),
'Volatility': volatility(returns),
'Calmar': calmar(returns)
}
# 打印结果
for metric, values in metrics.items():
print(f"\n{metric}:")
print(values)
使用 Portfolio 类
Portfolio 类提供了一种更便捷的方式来计算多个指标:
from kepler.metric import Portfolio
# 创建 Portfolio 实例
# 注意:risk_free 是日度无风险利率,不是年度!
# 如果年化无风险利率是 2%,日度利率 = 0.02 / 252
pf = Portfolio(returns, risk_free=0.02/252)
# 计算单个指标
print(pf.sharpe())
print(pf.max_drawdown())
# 获取所有指标的摘要
summary = pf.summary()
print(summary)
# 转换为 DataFrame
df = pf.to_frame()
使用 analyze() 函数
from kepler.metric import analyze
# 一次性分析
result = analyze(
returns,
metrics=['sharpe', 'max_drawdown', 'total_return', 'volatility']
)
print(result)
⚠️ 重要说明
risk_free 参数
所有涉及 risk_free 的函数,该参数都是日度无风险利率,不是年度!
# ❌ 错误:传入年度 2%
sharpe(returns, risk_free=0.02) # 结果会是负数,完全错误!
# ✅ 正确:转换为日度利率
annual_rf = 0.02 # 年化 2%
daily_rf = annual_rf / 252 # 日度利率
sharpe(returns, risk_free=daily_rf) # 正确!
# ✅ 或者直接传 0(默认值)
sharpe(returns) # 假设无风险利率为 0
API 参考
收益指标
| 函数 | 描述 |
|---|---|
cum_returns(returns) |
累积收益 |
total_return(returns) |
总收益率 |
annual_return(returns, period) |
年化收益率 |
cagr(returns, period) |
复合年增长率 |
aggregate_returns(returns, convert_to) |
聚合收益 |
风险指标
| 函数 | 描述 |
|---|---|
max_drawdown(returns) |
最大回撤 |
volatility(returns, period) |
年化波动率 |
downside_risk(returns, required_return) |
下行风险 |
var(returns, cutoff) |
风险价值 (VaR) |
cvar(returns, cutoff) |
条件风险价值 (CVaR) |
tail_ratio(returns) |
尾部比率 |
风险调整收益
| 函数 | 描述 |
|---|---|
sharpe(returns, risk_free, period) |
夏普比率 |
sortino(returns, required_return, period) |
索提诺比率 |
calmar(returns, period) |
卡玛比率 |
omega(returns, risk_free, required_return) |
欧米茄比率 |
information_ratio(returns, period) |
信息比率 |
stability(returns) |
时间序列稳定性 (R²) |
excess_sharpe(returns, factor_returns) |
超额夏普比率 |
市场关系
| 函数 | 描述 |
|---|---|
alpha(returns, benchmark, risk_free, period) |
阿尔法 |
beta(returns, benchmark, risk_free) |
贝塔 |
alpha_beta(returns, benchmark, ...) |
阿尔法和贝塔 (元组) |
capture(returns, benchmark, period) |
捕获比率 |
up_capture(returns, benchmark, period) |
上涨捕获 |
down_capture(returns, benchmark, period) |
下跌捕获 |
up_down_capture(returns, benchmark, period) |
上涨下跌捕获比 |
高级接口
| 类/函数 | 描述 |
|---|---|
Portfolio(returns, benchmark, risk_free, period) |
投资组合分析类 |
analyze(returns, metrics, ...) |
一次性分析函数 |
从 0.x 迁移
如果你从旧版本 (0.x) 迁移,以下是主要的 API 变更:
| 旧名称 | 新名称 |
|---|---|
sharpe_ratio |
sharpe |
sortino_ratio |
sortino |
calmar_ratio |
calmar |
omega_ratio |
omega |
stability_of_timeseries |
stability |
value_at_risk |
var |
conditional_value_at_risk |
cvar |
annual_volatility |
volatility |
cum_returns_final |
total_return |
DataFrame 支持
所有函数都支持 DataFrame 输入,并保留列名:
# DataFrame 输入
returns = pd.DataFrame({
'Stock_A': [...],
'Stock_B': [...],
'Stock_C': [...]
})
# 返回带列名的 Series
result = sharpe(returns)
print(result)
# Stock_A 0.75
# Stock_B 0.82
# Stock_C 0.68
# dtype: float64
开发
从源码安装:
git clone https://github.com/cloudQuant/kepler.metric
cd kepler.metric
pip install -e .
运行测试:
pytest tests/
许可证
Apache License 2.0
致谢
基于 Quantopian Inc. 开发的 empyrical 库,经过现代化重构。
Metadata
Release files for kepler-metric 1.0.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| kepler_metric-1.0.5.tar.gz | 62.8 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| kepler_metric-1.0.5-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 124.8 kB
Release files / kepler_metric-1.0.5.tar.gz
| Download URL | kepler_metric-1.0.5.tar.gz |
|---|---|
| Size | 62.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
94b43bbb9c9f381d00e252aeed335822e4ad8fd5d73940a8fdb8c6f0fded2d5a
|
|
BLAKE2b-256 checksum How to use checksums |
af76022d1fe78f815548a3eac526e3ffcde0c47701582b58df552993cad28c80
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Release files / kepler_metric-1.0.5-py3-none-any.whl
| Download URL | kepler_metric-1.0.5-py3-none-any.whl |
|---|---|
| Size | 62.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
32129535a4cadcde7ea52d931401001a313818f1b25c06e3794274b4ad64b024
|
|
BLAKE2b-256 checksum How to use checksums |
3a375205068446ee7c552b72e25ff55953cbe3169575ddbe1b2635114e62ac1d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Security for kepler-metric 1.0.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.