Skip to main content

Python version PyPi version PyPi status PyPi downloads CodeFactor Star this repo

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.

This is a fork of ranaroussi's quantstats project. Besides fixing bugs in the original project more promptly, we will proactively update the version to ensure compatibility with newer Python versions and commonly used Python libraries. We also achieve more rigorous dependency management via Poetry.

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.

Here's an example of a simple tear sheet analyzing a strategy:

Quick Start

%matplotlib inline
import quantstats as qs
import numpy as np
import datetime as dt

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

# Create random return data with a date index.
np.random.seed(42)
index = pd.date_range(end=dt.datetime.now(), periods=1000, freq='B')
stock = pd.Series(np.random.normal(0.001, 0.02, len(index)), index=index)

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

Output:

np.float64(1.1239729896454933)

Visualize stock performance

qs.plots.snapshot(stock, title='synthetic data', 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' create an html tearsheet

np.random.seed(42)
benchmark = pd.Series(np.random.normal(0.0, 0.02, len(index)), index=index)

qs.reports.full(stock, benchmark, output="/tmp/report.html")

Output will generate something like this:

first part

second part

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',
 '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',
 'utils',
 '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',
 'returns',
 'rolling_beta',
 'rolling_sharpe',
 'rolling_sortino',
 'rolling_volatility',
 'snapshot',
 'yearly_returns']

*** Full documenttion coming soon ***

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)
    calculats the conditional daily value-at-risk (aka expected shortfall)
    quantifies the amount of tail risk an investment

Installation

Install using pip:

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

Known Issues

  1. "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." - this is a known issue of Ranaroussi's Quantstats library.
  2. We dropped support for YFinance, since the author (live in Chinese mainland) has no env to test it.

Legal Stuff

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

P.S.

Ranaroussi's Quantstats is a highly favored strategy metric evaluation library among quants, boasting over 5k stars on GitHub. However, it has been more than eight months since its last release, and several critical bugs remain unresolved, rendering some fundamental functions inoperable (e.g., Issue 416 makes most calculations impossible under Python 3.12). Given that we've consistently recommended this library to students in our quantitative trading courses, we feel obliged to contribute to its maintenance and ensure timely releases of updated versions.

Metadata

Release files for quantstats-reloaded 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for quantstats-reloaded 0.1.0
File Size Uploaded
quantstats_reloaded-0.1.0.tar.gz 45.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for quantstats-reloaded 0.1.0
File Interpreter ABI Platform
quantstats_reloaded-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 97.4 kB

Release files / quantstats_reloaded-0.1.0.tar.gz

Download URL quantstats_reloaded-0.1.0.tar.gz
Size 45.1 kB
Tags Source
SHA-256 checksum
How to use checksums
a6998885b2205f57124026b5ef757833a72b1eeb3d12aae31da72b7e7f45de01
BLAKE2b-256 checksum
How to use checksums
b75755a95fe3f88a1f6ab66b9efd4bde49f8b9cf78ad87bccec1c6d48cb70894
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.1 CPython/3.9.7 Darwin/23.5.0

Release files / quantstats_reloaded-0.1.0-py3-none-any.whl

Download URL quantstats_reloaded-0.1.0-py3-none-any.whl
Size 52.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0feb46c02655277015f9246c8e6df3e01275c20e8fe2c08cb2550591f18d3c5b
BLAKE2b-256 checksum
How to use checksums
646f7f3abe4a129a0bc608d27f390180cd43a857b17660e4c210da0d3d3a88f4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.1 CPython/3.9.7 Darwin/23.5.0

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page