Convert Figma logo to code with AI

ranaroussi logoquantstats

Portfolio analytics for quants, written in Python

4,739
831
4,739
97

Top Related Projects

5,612

Portfolio and risk analytics in Python

15,147

Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.

MlFinLab helps portfolio managers and traders who want to leverage the power of machine learning by providing reproducible, interpretable, and easy to use tools.

1,897

ffn - a financial function library for Python

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

9,430

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

Quick Overview

QuantStats is a Python library that provides a set of performance and risk-analysis metrics for evaluating investment strategies and portfolios. It offers a comprehensive suite of tools for analyzing the risk-adjusted performance of trading systems, mutual funds, and other financial instruments.

Pros

  • Comprehensive Metrics: QuantStats provides a wide range of performance and risk-analysis metrics, including Sharpe ratio, Sortino ratio, maximum drawdown, and more, making it a valuable tool for in-depth portfolio analysis.
  • Easy to Use: The library has a user-friendly API and provides clear documentation, making it accessible for both novice and experienced data analysts.
  • Flexible and Customizable: QuantStats allows users to customize the analysis by providing options to adjust parameters and calculate metrics based on specific requirements.
  • Integration with Popular Libraries: The library seamlessly integrates with other popular Python data analysis libraries, such as Pandas and Matplotlib, enabling users to incorporate QuantStats into their existing workflows.

Cons

  • Limited Scope: While QuantStats is a powerful tool for performance and risk analysis, it may not cover all the needs of users who require more advanced financial modeling or trading strategies.
  • Dependency on External Libraries: The library relies on several external dependencies, which may introduce compatibility issues or require additional setup for some users.
  • Limited Community Support: Compared to some other popular Python libraries, QuantStats may have a smaller user community, which could make it more challenging to find support or troubleshoot issues.
  • Potential Learning Curve: Users who are new to financial analysis or Python may need to invest time in understanding the library's concepts and features to fully utilize its capabilities.

Code Examples

Here are a few examples of how to use QuantStats in your Python code:

  1. Calculating the Sharpe Ratio:
import quantstats as qs
import pandas as pd

# Load your portfolio returns data into a Pandas DataFrame
returns = pd.DataFrame(...)

# Calculate the Sharpe ratio
sharpe = qs.sharpe(returns)
print(f"Sharpe Ratio: {sharpe:.2f}")
  1. Generating a Performance Report:
import quantstats as qs

# Load your portfolio returns data into a Pandas DataFrame
returns = pd.DataFrame(...)

# Generate a comprehensive performance report
qs.reports.full(returns, benchmark='^GSPC', output='performance_report.html')
  1. Analyzing Maximum Drawdown:
import quantstats as qs
import pandas as pd

# Load your portfolio returns data into a Pandas DataFrame
returns = pd.DataFrame(...)

# Calculate the maximum drawdown
max_drawdown = qs.max_drawdown(returns)
print(f"Maximum Drawdown: {max_drawdown:.2%}")
  1. Visualizing Risk-Adjusted Returns:
import quantstats as qs
import pandas as pd

# Load your portfolio returns data into a Pandas DataFrame
returns = pd.DataFrame(...)

# Generate a risk-return scatter plot
qs.plots.snapshot(returns, benchmark='^GSPC')

Getting Started

To get started with QuantStats, follow these steps:

  1. Install the library using pip:
pip install quantstats
  1. Import the necessary modules and load your portfolio returns data into a Pandas DataFrame:
import quantstats as qs
import pandas as pd

returns = pd.DataFrame(...)
  1. Explore the available metrics and generate reports:
# Calculate the Sharpe ratio
sharpe = qs.sharpe(returns)
print(f"Sharpe Ratio: {sharpe:.2f}")

# Generate a full performance report
qs.reports.full(returns, benchmark='^GSPC', output='performance_report.html')
  1. Customize the analysis by adjusting parameters or using additional QuantStats functions:
# Calculate the maximum drawdown
max_drawdown = qs.max_drawdown(returns)
print(f"Maximum Drawdown: {max_drawdown:.2%}")

# Visualize the risk-return profile
qs.plots.snapshot(returns, benchmark='^GSPC')

For more detailed information and advanced usage

Competitor Comparisons

5,612

Portfolio and risk analytics in Python

Pros of pyfolio

  • More established and widely used in the quantitative finance community
  • Offers more advanced risk metrics and analysis tools
  • Better documentation and examples for complex use cases

Cons of pyfolio

  • Less actively maintained (last update was in 2021)
  • Heavier dependencies, which can make installation more challenging
  • Steeper learning curve for beginners

Code Comparison

pyfolio:

import pyfolio as pf

returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(backtest)
pf.create_full_tear_sheet(returns, positions=positions, transactions=transactions)

quantstats:

import quantstats as qs

qs.reports.html(returns, output='tearsheet.html')

Summary

While pyfolio offers more advanced features and is well-established in the quant finance community, quantstats provides a more user-friendly and actively maintained alternative. quantstats has a simpler API and lighter dependencies, making it easier for beginners to get started. However, pyfolio still holds an edge for more complex analysis needs and risk metrics. The choice between the two depends on the user's specific requirements and level of expertise in quantitative finance.

15,147

Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.

Pros of qlib

  • More comprehensive AI-driven quantitative investment platform
  • Supports advanced machine learning models and strategies
  • Offers a modular and extensible architecture for customization

Cons of qlib

  • Steeper learning curve due to its complexity
  • Requires more computational resources for advanced features
  • Less focused on performance reporting and visualization

Code Comparison

qlib example:

from qlib.contrib.model.pytorch_lstm import LSTMModel
from qlib.contrib.data.handler import Alpha158
from qlib.workflow import R

model = LSTMModel()
dataset = Alpha158()
R.run(dataset=dataset, model=model)

quantstats example:

import quantstats as qs

qs.extend_pandas()
stock = qs.utils.download_returns('AAPL')
qs.reports.html(stock, output='AAPL_report.html')

Summary

qlib is a more advanced platform for AI-driven quantitative investing, offering sophisticated models and strategies. It's highly customizable but requires more expertise and resources. quantstats, on the other hand, focuses on performance analysis and reporting, providing an easier-to-use solution for portfolio analytics and visualization. The choice between the two depends on the specific needs of the project and the user's level of expertise in quantitative finance and machine learning.

MlFinLab helps portfolio managers and traders who want to leverage the power of machine learning by providing reproducible, interpretable, and easy to use tools.

Pros of mlfinlab

  • Focuses on machine learning applications in finance, offering advanced algorithms and techniques
  • Provides comprehensive documentation and educational resources
  • Includes implementations of academic research papers in financial machine learning

Cons of mlfinlab

  • Steeper learning curve due to more complex algorithms and concepts
  • May be overkill for basic portfolio analysis tasks
  • Requires more computational resources for some advanced features

Code comparison

mlfinlab:

from mlfinlab.portfolio_optimization import MeanVarianceOptimisation

mvo = MeanVarianceOptimisation()
weights = mvo.optimize(expected_returns, covariance_matrix)

quantstats:

import quantstats as qs

qs.reports.html(returns, benchmark="SPY", output="analysis_report.html")

Summary

mlfinlab is more focused on advanced machine learning techniques for finance, offering implementations of cutting-edge research. It's well-suited for users looking to apply sophisticated algorithms to financial data. However, it may be more complex and resource-intensive than necessary for basic analysis tasks.

quantstats, on the other hand, excels in generating performance reports and metrics for portfolios. It's more user-friendly and suitable for quick analysis and visualization of trading strategies. While it may not offer the same depth of machine learning capabilities, it's excellent for portfolio performance evaluation and comparison.

The choice between the two depends on the specific needs of the user, with mlfinlab being better for advanced ML applications and quantstats for straightforward portfolio analysis and reporting.

1,897

ffn - a financial function library for Python

Pros of ffn

  • More established and mature project with a longer history
  • Offers a wider range of financial metrics and analysis tools
  • Better suited for complex portfolio analysis and risk management

Cons of ffn

  • Less active development and fewer recent updates
  • Documentation is less comprehensive and user-friendly
  • Steeper learning curve for beginners

Code Comparison

ffn:

import ffn

returns = ffn.get('SPY,AAPL,MSFT', start='2010-01-01')
stats = ffn.calc_stats(returns)
print(stats.display())

QuantStats:

import quantstats as qs

qs.extend_pandas()
stock = qs.utils.download_returns('AAPL')
qs.reports.html(stock, output='AAPL_report.html')

ffn focuses on calculating various financial metrics and statistics, while QuantStats provides a more streamlined approach to generating performance reports. QuantStats offers easier-to-use functions for creating visual reports, while ffn provides more flexibility for custom analysis. Both libraries have their strengths, and the choice between them depends on the specific requirements of the financial analysis project.

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

Pros of backtesting.py

  • More focused on backtesting strategies with a simple, intuitive API
  • Includes built-in plotting and visualization tools
  • Supports custom indicators and strategies with less boilerplate code

Cons of backtesting.py

  • Less comprehensive performance metrics compared to QuantStats
  • Limited to backtesting; doesn't offer portfolio analysis or risk management tools
  • Smaller community and fewer contributors

Code Comparison

backtesting.py:

from backtesting import Backtest, Strategy
from backtesting.lib import crossover

class SmaCross(Strategy):
    def init(self):
        self.sma1 = self.I(SMA, self.data.Close, 10)
        self.sma2 = self.I(SMA, self.data.Close, 20)

    def next(self):
        if crossover(self.sma1, self.sma2):
            self.buy()
        elif crossover(self.sma2, self.sma1):
            self.sell()

bt = Backtest(data, SmaCross, cash=10000, commission=.002)
bt.run()
bt.plot()

QuantStats:

import quantstats as qs

# Assuming 'returns' is a pandas Series of strategy returns
qs.reports.html(returns, output='strategy_report.html')
qs.plots.snapshot(returns, title='Strategy Performance')

Both libraries offer valuable tools for quantitative finance, with backtesting.py focusing on strategy backtesting and QuantStats excelling in performance analysis and reporting.

9,430

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

Pros of Lean

  • Comprehensive algorithmic trading platform with backtesting, live trading, and data management capabilities
  • Supports multiple asset classes and markets
  • Extensive documentation and active community support

Cons of Lean

  • Steeper learning curve due to its complexity and extensive features
  • Requires more setup and configuration compared to QuantStats
  • May be overkill for simple portfolio analysis tasks

Code Comparison

QuantStats (Python):

import quantstats as qs

# Fetch stock data and calculate returns
stock = qs.utils.download_returns('AAPL')

# Generate tearsheet
qs.reports.html(stock, output='AAPL_tearsheet.html')

Lean (C#):

public class SimpleMovingAverageAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2015, 1, 1);
        SetEndDate(2018, 1, 1);
        SetCash(100000);
        AddEquity("SPY", Resolution.Daily);
    }

    public override void OnData(Slice data)
    {
        if (!Portfolio.Invested)
        {
            SetHoldings("SPY", 1);
        }
    }
}

QuantStats focuses on quick portfolio analysis and reporting, while Lean provides a full-fledged algorithmic trading environment with more advanced features and flexibility.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://img.shields.io/badge/python-3.6+-blue.svg?style=flat :target: https://pypi.python.org/pypi/quantstats :alt: Python version

.. image:: https://img.shields.io/pypi/v/quantstats.svg?maxAge=60 :target: https://pypi.python.org/pypi/quantstats :alt: PyPi version

.. image:: https://img.shields.io/pypi/status/quantstats.svg?maxAge=60 :target: https://pypi.python.org/pypi/quantstats :alt: PyPi status

.. image:: https://img.shields.io/pypi/dm/quantstats.svg?maxAge=2592000&label=installs&color=%2327B1FF :target: https://pypi.python.org/pypi/quantstats :alt: PyPi downloads

.. image:: https://www.codefactor.io/repository/github/ranaroussi/quantstats/badge :target: https://www.codefactor.io/repository/github/ranaroussi/quantstats :alt: CodeFactor

.. image:: https://img.shields.io/github/stars/ranaroussi/quantstats.svg?style=social&label=Star&maxAge=60 :target: https://github.com/ranaroussi/quantstats :alt: Star this repo

.. image:: https://img.shields.io/twitter/follow/aroussi.svg?style=social&label=Follow&maxAge=60 :target: https://twitter.com/aroussi :alt: 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 » <./CHANGELOG.rst>__

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
===========

.. code:: python

    %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:

.. code:: text

    0.8135304438803402


Visualize stock performance
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

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

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

Output:

.. image:: https://github.com/ranaroussi/quantstats/blob/main/docs/snapshot.jpg?raw=true
    :alt: 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

.. code:: python

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

Output will generate something like this:

.. image:: https://github.com/ranaroussi/quantstats/blob/main/docs/report.jpg?raw=true
    :alt: HTML tearsheet

(`view original html file <https://rawcdn.githack.com/ranaroussi/quantstats/main/docs/tearsheet.html>`_)


To view a complete list of available methods, run

.. code:: python

[f for f in dir(qs.stats) if f[0] != '_']

.. code:: text

['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']

.. code:: python

[f for f in dir(qs.plots) if f[0] != '_']

.. code:: text

['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:

.. code:: python

help(qs.stats.conditional_value_at_risk)

.. code:: text

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:

.. code:: bash

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

Install using conda:

.. code:: bash

$ conda install -c ranaroussi quantstats

Requirements

  • Python <https://www.python.org>_ >= 3.5+
  • pandas <https://github.com/pydata/pandas>_ (tested to work with >=0.24.0)
  • numpy <http://www.numpy.org>_ >= 1.15.0
  • scipy <https://www.scipy.org>_ >= 1.2.0
  • matplotlib <https://matplotlib.org>_ >= 3.0.0
  • seaborn <https://seaborn.pydata.org>_ >= 0.9.0
  • tabulate <https://bitbucket.org/astanin/python-tabulate>_ >= 0.8.0
  • yfinance <https://github.com/ranaroussi/yfinance>_ >= 0.1.38
  • plotly <https://plot.ly/>_ >= 3.4.1 (optional, for using plots.to_plotly())

Questions?

This is a new library... If you find a bug, please open an issue <https://github.com/ranaroussi/quantstats/issues>_ in this repository.

If you'd like to contribute, a great place to look is the issues marked with help-wanted <https://github.com/ranaroussi/quantstats/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22>_.

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.

Legal Stuff

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

P.S.

Please drop me a note with any feedback you have.

Ran Aroussi