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.
Issues
  • 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 msh855 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
  • 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 msh855 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
  • type object 'HCPortfolio' has no attribute 'HCPortfolio'

    type object 'HCPortfolio' has no attribute 'HCPortfolio'

    I am not I understand why I get this error:

    type object 'HCPortfolio' has no attribute 'HCPortfolio'

    The code is the same from the examples

    import riskfolio.HCPortfolio as hc
    
    hc.HCPortfolio
    
    # Building the portfolio object
    port = hc.HCPortfolio(returns=Y)
    
    # Estimate optimal portfolio:
    
    model='HRP' # Could be HRP or HERC
    correlation = 'pearson' # Correlation matrix used to group assets in clusters
    rm = 'MV' # Risk measure used, this time will be variance
    rf = 0 # Risk free rate
    linkage = 'single' # Linkage method used to build clusters
    max_k = 10 # Max number of clusters used in two difference gap statistic, only for HERC model
    leaf_order = True # Consider optimal order of leafs in dendrogram
    
    w = port.optimization(model=model,
                          codependence=correlation,
                          rm=rm,
                          rf=rf,
                          linkage=linkage,
                          max_k=max_k,
                          leaf_order=leaf_order)
    
    display(w.T)
    

    But I get:


    AttributeError Traceback (most recent call last) in 1 import riskfolio.HCPortfolio as hc 2 ----> 3 hc.HCPortfolio 4 5 # Building the portfolio object

    AttributeError: type object 'HCPortfolio' has no attribute 'HCPortfolio'

    opened by msh855 5
Owner
Riskfolio
Finance and Python lover, looking for job opportunities in quantitative finance, investments and risk management.
Riskfolio
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 76 Jun 11, 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 53 Jun 27, 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 17 Jun 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 2 Nov 13, 2021
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 4 May 5, 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 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 18 Jun 4, 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 7 Jan 25, 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 31 Jul 2, 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 4 May 13, 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.3k Jun 28, 2022
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.3k Jul 2, 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 395 Jun 29, 2022
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 28 Jun 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 5 Feb 21, 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 388 Jul 4, 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 11 Apr 12, 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 60 Jun 19, 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 401 Jun 19, 2022