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
  • 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 blenderben2 7
  • 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
  • Back test tutorials - Transactions costs.

    Back test tutorials - Transactions costs.

    Hi @dcajasn !!

    I hope your well.!! Amazing library, well done, its so excellent!

    I was wondering if you could add more back test tutorials, which include slippage and transaction costs.

    Also would it be possible to add tear sheet functionality.

    Thanks again :).

    Kind regards and sincere thanks, Andrew

    opened by andrewcztrack 5
  • 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
  • Issues in JupyterReport and RiskFunctions

    Issues in JupyterReport and RiskFunctions

    Hi Dany, I actually having some issue with the risk functions, in all of them there is: value.item(), by running my code, I met AttributeError: 'float' object has no attribute 'item'. How could I fix this issue? And why is it present?

    opened by ands996 5
  • Tracking error

    Tracking error

    Hi Dany, I am looking for solution for incorporate tracking error as a constraint. In your examples in Tutorial 7 I failed to find out how you incorporate an index. The results are not likely to be correct because you have zero weights on several stocks APA, BMY, HPQ, etc, which is not really possible if you want to track certain index. Furthermore, how do you calculate tracking error in your codes? is it ex-post: so the standard deviation of historical returns x relative weight , where relative weight = portfolio weights - benchmark weights, or is it ex-ante: so transpose(relative weights)@[email protected] weights?

    opened by TomLiu518 3
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 16 Nov 12, 2021
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 53 Nov 29, 2021
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 1 Nov 12, 2021
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 44 Nov 11, 2021
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 13 Nov 20, 2021
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 3 Nov 23, 2021
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

郭飞 2.7k Dec 3, 2021
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.1k Nov 30, 2021
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 385 Nov 20, 2021
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 26 Sep 29, 2021
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 2 Oct 23, 2021
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 365 Nov 25, 2021
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 8 Nov 12, 2021
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 42 Nov 17, 2021
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 316 Nov 21, 2021
🐦 Opytimizer is a Python library consisting of meta-heuristic optimization techniques.

Opytimizer: A Nature-Inspired Python Optimizer Welcome to Opytimizer. Did you ever reach a bottleneck in your computational experiments? Are you tired

Gustavo Rosa 469 Nov 30, 2021
Distributed Asynchronous Hyperparameter Optimization in Python

Hyperopt: Distributed Hyperparameter Optimization Hyperopt is a Python library for serial and parallel optimization over awkward search spaces, which

null 6k Nov 25, 2021
A Python implementation of global optimization with gaussian processes.

Bayesian Optimization Pure Python implementation of bayesian global optimization with gaussian processes. PyPI (pip): $ pip install bayesian-optimizat

fernando 5.6k Dec 4, 2021