PyPortfolioOpt icon indicating copy to clipboard operation
PyPortfolioOpt copied to clipboard

Easy way to save the stock weights for all portfolios on the efficient frontier

Open avrenli2 opened this issue 2 years ago • 1 comments

What are you trying to do? I created the efficient frontier based on a group of stocks and plotted the efficient frontier from 200 points. Is there an easy way to create a data frame that saves the stock weights for all portfolios on the plot?

What have you tried? I have plotted the efficient frontier from 200 points as follows:

import yfinance as yf
import numpy as np
import pandas as pd
DATA = yf.download(["TSLA","SBUX","CAKE"], start="2018-1-1", end="2023-1-1", interval="1mo")
ADJUSTED = DATA["Adj Close"]
from pypfopt import EfficientFrontier, risk_models, expected_returns, plotting
EXP_RETS = expected_returns.mean_historical_return(ADJUSTED, frequency=1, compounding=False)
COV_MATRIX = risk_models.sample_cov(ADJUSTED , frequency=1)
EF1 = EfficientFrontier(EXP_RETS, COV_MATRIX, weight_bounds=(0,1))
FIG = plotting.plot_efficient_frontier(EF1, ef_param="return", points=200 , 
                                show_assets=False, showfig=True)
#Std. Deviation
LINE = FIG.lines[0]
LINE.get_xdata()
#Expected Return
LINE.get_ydata()
#Create a loop to save the stock weights as WEIGHTS
WEIGHTS =pd.DataFrame(columns=EF1.tickers)
for i in Y:
  EF1.efficient_return(target_return=i)
  ROW = pd.DataFrame.from_dict(data=[EF1.clean_weights()])
  WEIGHTS = pd.concat(objs=[WEIGHTS,ROW])

What data are you using? I am downloading the data using yfinance.

avrenli2 avatar May 01 '23 02:05 avrenli2

This question is useful.

Yes, your approach seems correct, but maybe it’s not an “easy way”. We still don’t support this function, but we plan to have it in the next major version. If you have any more questions or suggestions for the next version, please let me know.