kepler-metric is a Python library with performance and risk statistics commonly used in quantitative finance
Project description
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 库,经过现代化重构。
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kepler_metric-1.0.4.tar.gz.
File metadata
- Download URL: kepler_metric-1.0.4.tar.gz
- Upload date:
- Size: 62.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1f573ab1066fae44aef4204dac9e2e29e0df45d0101c1e6329fe48356c2a876c
|
|
| MD5 |
a69adf55d5d80edc7604f7717b7ad55b
|
|
| BLAKE2b-256 |
db8246979cdd91a4768757c486cb611c2895107fe46b4557a0ddb9a56df073e0
|
File details
Details for the file kepler_metric-1.0.4-py3-none-any.whl.
File metadata
- Download URL: kepler_metric-1.0.4-py3-none-any.whl
- Upload date:
- Size: 61.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
82ed3429d2236562c1bc0886ecd9ec9d2793ccf7501ae58bc6a849a169ab9c70
|
|
| MD5 |
49c0346bb6727d1c65785404a7611f37
|
|
| BLAKE2b-256 |
c3f4a901c5a812b08d687ea1243a2514b7a8d0af8eb6ca869220650410d1947e
|