robertmartin8 / PyPortfolioOpt

Financial portfolio optimisation in python, including classical efficient frontier, Black-Litterman, Hierarchical Risk Parity
https://pyportfolioopt.readthedocs.io/
MIT License
4.25k stars 928 forks source link

EfficientCVaR efficient_risk is throwing error #530

Closed dcgithubaccount closed 7 months ago

dcgithubaccount commented 1 year ago

I am using Python3.10 and on mac OS but it seems the problem happens on DataCamp site as well which is using 3.7.

from pypfopt.efficient_frontier import EfficientCVaR ec = EfficientCVaR(None, df, beta=0.9) ec.efficient_risk(target_cvar=0.02) this piece of code is giving error as shown below. It matrix mult is having issues. I think expected_returns should be transposed.

File ~/anaconda3/envs/MortgageModelling/lib/python3.10/site-packages/pypfopt/objective_functions.py:88, in portfolio_return(w, expected_returns, negative) 75 """ 76 Calculate the (negative) mean return of a portfolio 77 (...) 85 :rtype: float 86 """ 87 sign = -1 if negative else 1 ---> 88 mu = w @ expected_returns 89 return _objective_value(w, sign * mu)

88d52bdba0366127fffca9dfa93895 commented 1 year ago

Hi @dcgithubaccount,

Could you provide more information to help us identify the source of the error? A minimal code example that reproduces the error and/or the data you are using would be helpful.

We have automatically tested our code with Python 3.10 on the latest macOS and Python 3.7 on the latest Ubuntu, and it is working well.

Regards,

dcgithubaccount commented 1 year ago

Hiya,

Please find the code. The data can be downloaded from https://pastebin.com/UuGKfBAv

udf = pd.read_csv('stock_returns_2018.csv')
from pypfopt.efficient_frontier import EfficientCVaR

ec = EfficientCVaR(None, udf, beta=0.9)
ec.efficient_risk(target_cvar=0.02)
88d52bdba0366127fffca9dfa93895 commented 1 year ago

Hi @dcgithubaccount, there is no problem with your data, however, your code needs the expected returns and you let it be None. You can try the following code:

import pandas as pd
from pypfopt import expected_returns
from pypfopt.efficient_frontier import EfficientCVaR

udf = pd.read_csv("~/Downloads/stock_returns_2018.csv.txt")
udf["date"] = pd.to_datetime(udf["date"])
udf.set_index("date", inplace=True)

mu = expected_returns.mean_historical_return(udf, returns_data=True)
ec = EfficientCVaR(mu, udf, beta=0.9)
ec.efficient_risk(target_cvar=0.02)