ランキングに戻る

ranaroussi/quantstats

Python

Portfolio analytics for quants, written in Python

quantalgotradingalgorithmic-tradingquantitative-tradingquantitative-analysisalgo-tradingpythonvisualizationplottingquantitative-financefinance
スター成長
スター
7.5k
フォーク
1.2k
週間成長
Issue
9
2k4k6k
2019年5月2021年9月2024年2月2026年7月
成果物PyPIpip install quantstats
README

Python version PyPi version PyPi status PyPi downloads Ask DeepWiki Star this repo Follow me on twitter

QuantStats: Portfolio analytics for quants

QuantStats Python library that performs portfolio profiling, allowing quants and portfolio managers to understand their performance better by providing them with in-depth analytics and risk metrics.

Changelog »

QuantStats is comprised of 3 main modules:

  1. quantstats.stats - for calculating various performance metrics, like Sharpe ratio, Win rate, Volatility, etc.
  2. quantstats.plots - for visualizing performance, drawdowns, rolling statistics, monthly returns, etc.
  3. quantstats.reports - for generating metrics reports, batch plotting, and creating tear sheets that can be saved as an HTML file.

NEW! Monte Carlo Simulations

Monte Carlo Simulation

Run probabilistic risk analysis with built-in Monte Carlo simulations:

mc = qs.stats.montecarlo(returns, sims=1000, bust=-0.20, goal=0.50)
print(f"Bust probability: {mc.bust_probability:.1%}")
print(f"Goal probability: {mc.goal_probability:.1%}")
mc.plot()

Full Monte Carlo documentation »


Quick Start

%matplotlib inline
import quantstats as qs

# extend pandas functionality with metrics, etc.
qs.extend_pandas()

# fetch the daily returns for a stock
stock = qs.utils.download_returns('META')

# show sharpe ratio
qs.stats.sharpe(stock)

# or using extend_pandas() :)
stock.sharpe()

Output:

0.7604779884378278

Visualize stock performance

qs.plots.snapshot(stock, title='Facebook Performance', show=True)

# can also be called via:
# stock.plot_snapshot(title='Facebook Performance', show=True)

Output:

Snapshot plot

Creating a report

You can create 7 different report tearsheets:

  1. qs.reports.metrics(mode='basic|full", ...) - shows basic/full metrics
  2. qs.reports.plots(mode='basic|full", ...) - shows basic/full plots
  3. qs.reports.basic(...) - shows basic metrics and plots
  4. qs.reports.full(...) - shows full metrics and plots
  5. qs.reports.html(...) - generates a complete report as html

Let's create an html tearsheet:

# benchmark can be a pandas Series or ticker
qs.reports.html(stock, "SPY")

Output will generate something like this:

HTML tearsheet

View original html file

Available methods

To view a complete list of available methods, run:

[f for f in dir(qs.stats) if f[0] != '_']
['avg_loss',
 'avg_return',
 'avg_win',
 'best',
 'cagr',
 'calmar',
 'common_sense_ratio',
 'comp',
 'compare',
 'compsum',
 'conditional_value_at_risk',
 'consecutive_losses',
 'consecutive_wins',
 'cpc_index',
 'cvar',
 'drawdown_details',
 'expected_return',
 'expected_shortfall',
 'exposure',
 'gain_to_pain_ratio',
 'geometric_mean',
 'ghpr',
 'greeks',
 'implied_volatility',
 'information_ratio',
 'kelly_criterion',
 'kurtosis',
 'max_drawdown',
 'monthly_returns',
 'montecarlo',
 'montecarlo_cagr',
 'montecarlo_drawdown',
 'montecarlo_sharpe',
 'outlier_loss_ratio',
 'outlier_win_ratio',
 'outliers',
 'payoff_ratio',
 'profit_factor',
 'profit_ratio',
 'r2',
 'r_squared',
 'rar',
 'recovery_factor',
 'remove_outliers',
 'risk_of_ruin',
 'risk_return_ratio',
 'rolling_greeks',
 'ror',
 'sharpe',
 'skew',
 'sortino',
 'adjusted_sortino',
 'tail_ratio',
 'to_drawdown_series',
 'ulcer_index',
 'ulcer_performance_index',
 'upi',
 'value_at_risk',
 'var',
 'volatility',
 'win_loss_ratio',
 'win_rate',
 'worst']
[f for f in dir(qs.plots) if f[0] != '_']
['daily_returns',
 'distribution',
 'drawdown',
 'drawdowns_periods',
 'earnings',
 'histogram',
 'log_returns',
 'monthly_heatmap',
 'montecarlo',
 'montecarlo_distribution',
 'returns',
 'rolling_beta',
 'rolling_sharpe',
 'rolling_sortino',
 'rolling_volatility',
 'snapshot',
 'yearly_returns']

*** Full documentation coming soon ***

Important: Period-Based vs Trade-Based Metrics

QuantStats analyzes return series (daily, weekly, monthly returns), not discrete trade data. This means:

  • Win Rate = percentage of periods with positive returns
  • Consecutive Wins/Losses = consecutive positive/negative return periods
  • Payoff Ratio = average winning period return / average losing period return
  • Profit Factor = sum of positive returns / sum of negative returns

These metrics are valid and useful for:

  • Systematic/algorithmic strategies with regular rebalancing
  • Analyzing return-series behavior over time
  • Comparing strategies on a period-by-period basis

For discretionary traders with multi-day trades, these period-based metrics may differ from trade-level statistics. A single 5-day trade might span 3 positive days and 2 negative days - QuantStats would count these as 3 "wins" and 2 "losses" at the daily level.

This is consistent with how all return-based analytics work (Sharpe ratio, Sortino ratio, drawdown analysis, etc.) - they operate on return periods, not discrete trade entries/exits.


In the meantime, you can get insights as to optional parameters for each method, by using Python's help method:

help(qs.stats.conditional_value_at_risk)
Help on function conditional_value_at_risk in module quantstats.stats:

conditional_value_at_risk(returns, sigma=1, confidence=0.99)
    calculates the conditional daily value-at-risk (aka expected shortfall)
    quantifies the amount of tail risk an investment

Installation

Install using pip:

$ pip install quantstats --upgrade --no-cache-dir

Install using conda:

$ conda install -c ranaroussi quantstats

Requirements

Questions?

This is a new library... If you find a bug, please open an issue.

If you'd like to contribute, a great place to look is the issues marked with help-wanted.

Known Issues

For some reason, I couldn't find a way to tell seaborn not to return the monthly returns heatmap when instructed to save - so even if you save the plot (by passing savefig={...}) it will still show the plot.

QuantStats is distributed under the Apache Software License. See the LICENSE.txt file in the release for details.

P.S.

Please drop me a note with any feedback you have.

Ran Aroussi

関連リポジトリ
ZhuLinsen/daily_stock_analysis

LLM 驱动的多市场股票智能分析系统:多源行情、实时新闻、决策看板与自动推送,支持零成本定时运行。 LLM-powered multi-market stock analysis system with multi-source market data, real-time news, decision dashboard, automated notifications, and cost-free scheduled runs.

PythonPyPIMIT Licenseaigcllm
dsa.zhulinsen.tech
58.2k50k
microsoft/qlib

Qlib is an AI-oriented Quant investment platform that aims to use AI tech to empower Quant Research, from exploring ideas to implementing productions. Qlib supports diverse ML modeling paradigms, including supervised learning, market dynamics modeling, and RL, and is now equipped with https://github.com/microsoft/RD-Agent to automate R&D process.

PythonPyPIMIT Licensequantitative-financemachine-learning
qlib.readthedocs.io/en/latest/
46.5k7.4k
vnpy/vnpy

基于Python的开源量化交易平台开发框架

PythonPyPIMIT Licensetradinginvestment
vnpy.com
43.4k12.2k
wilsonfreitas/awesome-quant

A curated list of insanely awesome libraries, packages and resources for Quants (Quantitative Finance)

HTMLfinancefinancial-data
wilsonfreitas.github.io/awesome-quant/
28.1k3.7k
akfamily/akshare

AKShare is an elegant and simple financial data interface library for Python, built for human beings! 开源财经数据接口库

PythonPyPIMIT Licensefuturesfinancial-data
akshare.akfamily.xyz
21.5k3.4k
quantopian/zipline

Zipline, a Pythonic Algorithmic Trading Library

PythonPyPIApache License 2.0quantpython
zipline.io
20k5k
bbfamily/abu

阿布量化交易系统(股票,期权,期货,比特币,机器学习) 基于python的开源量化交易,量化投资架构

PythonPyPIGNU General Public License v3.0quanttrade
abuquant.com
17.9k4.6k
RyanCodrai/turbovec

A vector index built on TurboQuant, written in Rust with Python bindings

PythonPyPIMIT Licenseannavx512
pypi.org/project/turbovec/
13.7k1.2k
yutiansut/QUANTAXIS

QUANTAXIS 支持任务调度 分布式部署的 股票/期货/期权 数据/回测/模拟/交易/可视化/多账户 纯本地量化解决方案

PythonPyPIMIT Licensequant
yutiansut.github.io/QUANTAXIS/
10.9k3.4k
je-suis-tm/quant-trading

Python quantitative trading strategies including VIX Calculator, Pattern Recognition, Commodity Trading Advisor, Monte Carlo, Options Straddle, Shooting Star, London Breakout, Heikin-Ashi, Pair Trading, RSI, Bollinger Bands, Parabolic SAR, Dual Thrust, Awesome, MACD

PythonPyPIApache License 2.0trading-strategiesquantitative-trading
je-suis-tm.github.io/quant-trading
10.4k1.8k
OpenByteInc/QuantDinger

AI quantitative trading platform for crypto, stocks, and forex with backtesting, live trading, market data, and multi-agent research.vibe-trading ,trading-agents,ai-trader,ai-trading

PythonPyPIApache License 2.0quantitative-financequant
ai.quantdinger.com
9.9k2.1k
brokermr810/QuantDinger

AI quantitative trading platform for crypto, stocks, and forex with backtesting, live trading, market data, and multi-agent research.vibe-trading ,trading-agents,ai-trader,ai-trading

PythonPyPIApache License 2.0quantitative-financequant
quantdinger.com
9.7k2k