Portfolio Optimization and Quantitative Strategic Asset Allocation in Python

Overview

Riskfolio-Lib

Quantitative Strategic Asset Allocation, Easy for Everyone.

Buy Me a Coffee at ko-fi.com

GitHub stars Downloads Documentation Status GitHub license Binder

Description

Riskfolio-Lib is a library for making quantitative strategic asset allocation or portfolio optimization in Python made in Peru 🇵🇪 . Its objective is to help students, academics and practitioners to build investment portfolios based on mathematically complex models with low effort. It is built on top of cvxpy and closely integrated with pandas data structures.

Some of key functionalities that Riskfolio-Lib offers:

  • Mean Risk and Logarithmic Mean Risk (Kelly Criterion) Portfolio Optimization with 4 objective functions:

    • Minimum Risk.
    • Maximum Return.
    • Maximum Utility Function.
    • Maximum Risk Adjusted Return Ratio.
  • Mean Risk and Logarithmic Mean Risk (Kelly Criterion) Portfolio Optimization with 13 convex risk measures:

    • Standard Deviation.
    • Semi Standard Deviation.
    • Mean Absolute Deviation (MAD).
    • First Lower Partial Moment (Omega Ratio).
    • Second Lower Partial Moment (Sortino Ratio).
    • Conditional Value at Risk (CVaR).
    • Entropic Value at Risk (EVaR).
    • Worst Case Realization (Minimax Model).
    • Maximum Drawdown (Calmar Ratio) for uncompounded cumulative returns.
    • Average Drawdown for uncompounded cumulative returns.
    • Conditional Drawdown at Risk (CDaR) for uncompounded cumulative returns.
    • Entropic Drawdown at Risk (EDaR) for uncompounded cumulative returns.
    • Ulcer Index for uncompounded cumulative returns.
  • Risk Parity Portfolio Optimization with 10 convex risk measures:

    • Standard Deviation.
    • Semi Standard Deviation.
    • Mean Absolute Deviation (MAD).
    • First Lower Partial Moment (Omega Ratio).
    • Second Lower Partial Moment (Sortino Ratio).
    • Conditional Value at Risk (CVaR).
    • Entropic Value at Risk (EVaR).
    • Conditional Drawdown at Risk (CDaR) for uncompounded cumulative returns.
    • Entropic Drawdown at Risk (EDaR) for uncompounded cumulative returns.
    • Ulcer Index for uncompounded cumulative returns.
  • Hierarchical Clustering Portfolio Optimization: Hierarchical Risk Parity (HRP) and Hierarchical Equal Risk Contribution (HERC) with 22 risk measures:

    • Standard Deviation.
    • Variance.
    • Semi Standard Deviation.
    • Mean Absolute Deviation (MAD).
    • First Lower Partial Moment (Omega Ratio).
    • Second Lower Partial Moment (Sortino Ratio).
    • Value at Risk (VaR).
    • Conditional Value at Risk (CVaR).
    • Entropic Value at Risk (EVaR).
    • Worst Case Realization (Minimax Model).
    • Maximum Drawdown (Calmar Ratio) for compounded and uncompounded cumulative returns.
    • Average Drawdown for compounded and uncompounded cumulative returns.
    • Drawdown at Risk (DaR) for compounded and uncompounded cumulative returns.
    • Conditional Drawdown at Risk (CDaR) for compounded and uncompounded cumulative returns.
    • Entropic Drawdown at Risk (EDaR) for compounded and uncompounded cumulative returns.
    • Ulcer Index for compounded and uncompounded cumulative returns.
  • Nested Clustered Optimization (NCO) with four objective functions and the available risk measures to each objective:

    • Minimum Risk.
    • Maximum Return.
    • Maximum Utility Function.
    • Equal Risk Contribution.
  • Worst Case Mean Variance Portfolio Optimization.

  • Relaxed Risk Parity Portfolio Optimization.

  • Portfolio optimization with Black Litterman model.

  • Portfolio optimization with Risk Factors model.

  • Portfolio optimization with Black Litterman Bayesian model.

  • Portfolio optimization with Augmented Black Litterman model.

  • Portfolio optimization with constraints on tracking error and turnover.

  • Portfolio optimization with short positions and leveraged portfolios.

  • Portfolio optimization with constraints on number of assets and number of effective assets.

  • Tools to build efficient frontier for 13 risk measures.

  • Tools to build linear constraints on assets, asset classes and risk factors.

  • Tools to build views on assets and asset classes.

  • Tools to build views on risk factors.

  • Tools to calculate risk measures.

  • Tools to calculate risk contributions per asset.

  • Tools to calculate uncertainty sets for mean vector and covariance matrix.

  • Tools to calculate assets clusters based on codependence metrics.

  • Tools to estimate loadings matrix (Stepwise Regression and Principal Components Regression).

  • Tools to visualizing portfolio properties and risk measures.

  • Tools to build reports on Jupyter Notebook and Excel.

  • Option to use commercial optimization solver like MOSEK or GUROBI for large scale problems.

Documentation

Online documentation is available at Documentation.

The docs include a tutorial with examples that shows the capacities of Riskfolio-Lib.

Dependencies

Riskfolio-Lib supports Python 3.7+.

Installation requires:

Installation

The latest stable release (and older versions) can be installed from PyPI:

pip install riskfolio-lib

Citing

If you use Riskfolio-Lib for published work, please use the following BibTeX entrie:

@misc{riskfolio,
      author = {Dany Cajas},
      title = {Riskfolio-Lib (2.0.0)},
      year  = {2021},
      url   = {https://github.com/dcajasn/Riskfolio-Lib},
      }

Development

Riskfolio-Lib development takes place on Github: https://github.com/dcajasn/Riskfolio-Lib

RoadMap

The plan for this module is to add more functions that will be very useful to asset managers.

  • Add more functions based on suggestion of users.
Comments
  • Custom risk measure function for HERC method

    Custom risk measure function for HERC method

    Hi Dany,

    Thank you for providing us such an amazing library, I really appreciate it.

    I would be grateful if you could provide support for custom risk measure for HERC method here.

    I would like to

    Best regards,

    opened by arthurire 10
  • User specified covariance matrix

    User specified covariance matrix

    Is possible to use a user-specified covariance matrix in the portfolio optimisation, especially with regards to the HRP or HERC?

    I don't see that this possible according to the documentation

    opened by ghost 10
  • use matplotlib from bash shell with plt.show()

    use matplotlib from bash shell with plt.show()

    Hello, I am following your very interesting and useful code. Everything is fine (e.g. I can see all the calculations outputs in the tables from tutorial 1, and 2), but I cannot see any of your plots. I check your Portfolio.py and you use matplotlib. Would you please tell me how to get the plots? I do not use ipynb. Thank you for your time, LM

    opened by limoon20 8
  • Errors with certain plot flags from Tutorials

    Errors with certain plot flags from Tutorials

    TL;DR for the current version with a forced matplotlib==3.2.2 patch in Google Colab (see also Here and https://github.com/facebook/prophet/issues/1691 for more info on plotting), and it does work due to matplotlib noting on unnecessary flags.

    Error for the Plot

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    [<ipython-input-21-460c462cbd5f>](https://localhost:8080/#) in <module>
         29 
         30 ax = rp.plot_pie(w=w, title='Sharpe Mean Variance', others=0.05, nrow=25, cmap = "tab20",
    ---> 31                  height=6, width=10, ax=None)
    
    1 frames
    [/usr/local/lib/python3.7/dist-packages/riskfolio/PlotFunctions.py](https://localhost:8080/#) in plot_pie(w, title, others, nrow, cmap, height, width, ax)
        601         wedgeprops=dict(width=size, edgecolor="black"),
        602         startangle=-15,
    --> 603         normalize=True,
        604     )
        605 
    
    [/usr/local/lib/python3.7/dist-packages/matplotlib/__init__.py](https://localhost:8080/#) in inner(ax, data, *args, **kwargs)
       1563     def inner(ax, *args, data=None, **kwargs):
       1564         if data is None:
    -> 1565             return func(ax, *map(sanitize_sequence, args), **kwargs)
       1566 
       1567         bound = new_sig.bind(ax, *args, **kwargs)
    
    TypeError: pie() got an unexpected keyword argument 'normalize'
    

    Code

    import riskfolio as rp
    
    # Building the portfolio object
    port = rp.Portfolio(returns=Y)
    
    # Calculating optimal portfolio
    
    # Select method and estimate input parameters:
    
    method_mu='hist' # Method to estimate expected returns based on historical data.
    method_cov='hist' # Method to estimate covariance matrix based on historical data.
    
    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=0.94)
    
    # Estimate optimal portfolio:
    
    model='Classic' # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = 'MV' # Risk measure used, this time will be variance
    obj = 'Sharpe' # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = True # Use historical scenarios for risk measures that depend on scenarios
    rf = 0 # Risk free rate
    l = 0 # Risk aversion factor, only useful when obj is 'Utility'
    
    w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
    
    display(w.T)
    
    # Plotting the composition of the portfolio
    
    ax = rp.plot_pie(w=w, title='Sharpe Mean Variance', others=0.05, nrow=25, cmap = "tab20",
                     height=6, width=10, ax=None)
    

    Extra code for replication purposes

    !pip install yfinance riskfolio-lib --quiet --upgrade
    !pip install matplotlib==3.2.2 --force-reinstall --quiet
    import numpy as np
    import pandas as pd
    import yfinance as yf
    import warnings
    
    warnings.filterwarnings("ignore")
    pd.options.display.float_format = '{:.4%}'.format
    
    # Date range
    start = '2010-01-01'
    end = '2020-12-30'
    
    # Tickers of long-term $BECKY assets
    assets = ["AAPL", "ADDYY", "AMZN", "BBBY", "BBWI", "BUD", "CHD", 
              "CMG", "CVS", "DECK", "DEO", "DIS", "EL", "F", "FIZZ", 
              "GPS", "JWN", "LRLCY", "LULU", "LVMUY", "M",  "MO", "MTCH", 
              "NFLX", "NKE", "PVH", "RL", "SBUX", "STZ", "TAP", "TGT", 
              "TJX", "TPR", "UAA", "ULTA", "VFC", "WSM", "WWW", "YUM"]
    
    # Contemporary $BECKY companies
    # "ABBV", "COTY", "CRON", "EOLS", "ETSY", "FTCH", "GOOS", "INMD", 
    # "LEVI", "LYFT", "MC", "META", "OR", "PINS", "PLNT", "PTON", 
    # "SFIX", "SKIN", "SNAP", "SPOT", "TLRY",  "YETI", 
    
    assets.sort()
    
    # Downloading data
    data = yf.download(assets, start = start, end = end)
    data = data.loc[:,('Adj Close', slice(None))]
    data.columns = assets
    
    # Calculating returns
    Y = data[assets].pct_change().dropna()
    display(Y.head())
    
    import missingno as msno
    msno.heatmap(data[assets].pct_change())
    
    opened by BrandonKMLee 7
  • Issue with assets_stats method in Tutorial 5.ipynb

    Issue with assets_stats method in Tutorial 5.ipynb

    In section 3.2 of the Tutorial 5, where:

    ############################################################
    # Building a loop that estimate optimal portfolios on
    # rebalancing dates
    ############################################################
    

    begins,

    I first get error: AttributeError: type object 'Portfolio' has no attribute 'Portfolio'

    This I fixed using:

    import riskfolio as rp
    port = rp.HCPortfolio(returns=Y)
    

    But then I get: AttributeError: 'HCPortfolio' object has no attribute 'assets_stats'

    Is it possible you could update the tutorial, or point to the fix to run the rest of the example?

    opened by ferhat00 7
  • constraints on HRP do not work

    constraints on HRP do not work

    Hi,

    I tried to use HRP with bounds on weights but does not seem to work.

    # Building the portfolio object
    port = rp.HCPortfolio(returns=ret_under_training, w_max=0.25, w_min=0.03)
    w = port.optimization(model='HRP')
    w
    
                                                        weights
    Aegon Global Equity Market Neut                    0.636207
    Artemis UK Select Fund I Acc                       0.025731
    BNY Mellon Investment Funds - N                    0.084947
    Baillie Gifford American Fund B                    0.013387
    Baillie Gifford European Fund B                    0.015596
    Baillie Gifford Global Income G                    0.024059
    Baillie Gifford Pacific B Acc                      0.031928
    Baillie Gifford Positive Change                    0.026448
    Fidelity Funds - Global Technology Fund W-acc-gbp  0.020010
    MI Chelverton UK Equity Growth                     0.098183
    Vanguard FTSE Developed World e                    0.023504
    
    opened by ghost 7
  • feature request: Relaxed Risk Parity

    feature request: Relaxed Risk Parity

    Hi, this is an amazing library! I have a small feature request: Risk Return Trade-Off Relaxed Risk Parity Portfolio Optimization, which might be an interesting addition to your library. Please let me know what you think, and if its possible to be implemented in your library. I have written some simple code for this although its not in your library's style, but I am happy to put it here to help in any way if you want to implement this paper :)

    opened by ghost 7
  • What the k variable and 1000 for ?

    What the k variable and 1000 for ?

    When the objective is "sharpe" i see some constraints multiply variable k and 1000, what are these options for ??? For example constraints += [mu @ w - rf0 * k == 1] objective = cv.Minimize(risk * 1000)

    Thank you

    opened by lemon234071 6
  • Example for using market caps

    Example for using market caps

    opened by cryptocoinserver 6
  • Run examples/Tutorial 1.ipynb and jupyter notebook is restarted

    Run examples/Tutorial 1.ipynb and jupyter notebook is restarted

    Hi Dany,

    Thanks for your great work. Riskfolio-Lib is really fascinating.

    I ran examples/Tutorial 1.ipynb and jupyter notebook was restarted As well as .py file in vs code. The notebook crashed at "port.efficient_frontier" in "2.3 Calculate efficient frontier", the error happened without any information. After tracing, I found it hang at line 2187 of Portfolio.py.

    Can you please help?

    Thank you very much in advance!

    Michael

    opened by mc6666 6
  • number of assets constraint

    number of assets constraint

    Hi, First of all, thank you for this wonderful library. I tried example 26 which is regarding the number of assets constraint and I am facing the following issue. image

    Appreciate any help. I also tried other MIP solvers based on the table below however faced the same issue. image

    opened by sabirjana 6
  • Install problem with 4.0.x versions

    Install problem with 4.0.x versions

    I was happy to see the new versions, but un fortunatley I was not able to install any of them. I have three confings: W8.1, W10, ubuntu. I am using PyCharm, but I have tried to install directly with pip. None of them worked. Here is a detailed error note from W8.1 PyCharm:

    Collecting Riskfolio-Lib==4.0.3 Using cached Riskfolio-Lib-4.0.3.tar.gz (12.9 MB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error'

    error: subprocess-exited-with-error

    python setup.py egg_info did not run successfully. exit code: 1

    [6 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 34, in File "C:\Users\Louis\AppData\Local\Temp\pip-install-u0z7wn8g\riskfolio-lib_717f395aa901483bbb9e438b122fa86e\setup.py", line 6, in from pybind11.setup_helpers import Pybind11Extension, build_ext ModuleNotFoundError: No module named 'pybind11' [end of output]

    note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed

    Encountered error while generating package metadata.

    See above for output.

    note: This is an issue with the package mentioned above, not pip. hint: See above for details.

    opened by plajos1 4
Owner
Riskfolio
Finance and Python lover, looking for job opportunities in quantitative finance, investments and risk management.
Riskfolio
A Python Package for Portfolio Optimization using the Critical Line Algorithm

PyCLA A Python Package for Portfolio Optimization using the Critical Line Algorithm Getting started To use PyCLA, clone the repo and install the requi

null 19 Oct 11, 2022
Use graph-based analysis to re-classify stocks and to improve Markowitz portfolio optimization

Dynamic Stock Industrial Classification Use graph-based analysis to re-classify stocks and experiment different re-classification methodologies to imp

Sheng Yang 10 Dec 5, 2022
Adaptive Prototype Learning and Allocation for Few-Shot Segmentation (CVPR 2021)

ASGNet The code is for the paper "Adaptive Prototype Learning and Allocation for Few-Shot Segmentation" (accepted to CVPR 2021) [arxiv] Overview data/

Gen Li 91 Dec 23, 2022
MRQy is a quality assurance and checking tool for quantitative assessment of magnetic resonance imaging (MRI) data.

Front-end View Backend View Table of Contents Description Prerequisites Running Basic Information Measurements User Interface Feedback and usage Descr

Center for Computational Imaging and Personalized Diagnostics 58 Dec 2, 2022
BisQue is a web-based platform designed to provide researchers with organizational and quantitative analysis tools for 5D image data. Users can extend BisQue by implementing containerized ML workflows.

Overview BisQue is a web-based platform specifically designed to provide researchers with organizational and quantitative analysis tools for up to 5D

Vision Research Lab @ UCSB 26 Nov 29, 2022
Optimal Adaptive Allocation using Deep Reinforcement Learning in a Dose-Response Study

Optimal Adaptive Allocation using Deep Reinforcement Learning in a Dose-Response Study Supplementary Materials for Kentaro Matsuura, Junya Honda, Imad

Kentaro Matsuura 4 Nov 1, 2022
This code uses generative adversarial networks to generate diverse task allocation plans for Multi-agent teams.

Mutli-agent task allocation This code uses generative adversarial networks to generate diverse task allocation plans for Multi-agent teams. To change

Biorobotics Lab 5 Oct 12, 2022
Tf alloc - Simplication of GPU allocation for Tensorflow2

tf_alloc Simpliying GPU allocation for Tensorflow Developer: korkite (Junseo Ko)

Junseo Ko 3 Feb 10, 2022
A Blender python script for getting asset browser custom preview images for objects and collections.

asset_snapshot A Blender python script for getting asset browser custom preview images for objects and collections. Installation: Click the code butto

Johnny Matthews 44 Nov 29, 2022
Racing line optimization algorithm in python that uses Particle Swarm Optimization.

Racing Line Optimization with PSO This repository contains a racing line optimization algorithm in python that uses Particle Swarm Optimization. Requi

Parsa Dahesh 6 Dec 14, 2022
Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Optimization Algorithm,Immune Algorithm, Artificial Fish Swarm Algorithm, Differential Evolution and TSP(Traveling salesman)

scikit-opt Swarm Intelligence in Python (Genetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Algorithm, Immune Algorithm,A

郭飞 3.7k Jan 3, 2023
library for nonlinear optimization, wrapping many algorithms for global and local, constrained or unconstrained, optimization

NLopt is a library for nonlinear local and global optimization, for functions with and without gradient information. It is designed as a simple, unifi

Steven G. Johnson 1.4k Dec 25, 2022
Reinforcement Learning for Portfolio Management

qtrader Reinforcement Learning for Portfolio Management Why Reinforcement Learning? Learns the optimal action, rather than models the market. Adaptive

Angelos Filos 406 Jan 1, 2023
Use AI to generate a optimized stock portfolio

Use AI, Modern Portfolio Theory, and Monte Carlo simulation's to generate a optimized stock portfolio that minimizes risk while maximizing returns. Ho

Greg James 30 Dec 22, 2022
A numpy-based implementation of RANSAC for fundamental matrix and homography estimation. The degeneracy updating and local optimization components are included and optional.

Description A numpy-based implementation of RANSAC for fundamental matrix and homography estimation. The degeneracy updating and local optimization co

AoxiangFan 9 Nov 10, 2022
A Free and Open Source Python Library for Multiobjective Optimization

Platypus What is Platypus? Platypus is a framework for evolutionary computing in Python with a focus on multiobjective evolutionary algorithms (MOEAs)

Project Platypus 424 Dec 18, 2022
A lightweight Python-based 3D network multi-agent simulator. Uses a cell-based congestion model. Calculates risk, loudness and battery capacities of the agents. Suitable for 3D network optimization tasks.

AMAZ3DSim AMAZ3DSim is a lightweight python-based 3D network multi-agent simulator. It uses a cell-based congestion model. It calculates risk, battery

Daniel Hirsch 13 Nov 4, 2022
Fast and scalable uncertainty quantification for neural molecular property prediction, accelerated optimization, and guided virtual screening.

Evidential Deep Learning for Guided Molecular Property Prediction and Discovery Ava Soleimany*, Alexander Amini*, Samuel Goldman*, Daniela Rus, Sangee

Alexander Amini 75 Dec 15, 2022
An optimization and data collection toolbox for convenient and fast prototyping of computationally expensive models.

An optimization and data collection toolbox for convenient and fast prototyping of computationally expensive models. Hyperactive: is very easy to lear

Simon Blanke 422 Jan 4, 2023