Sep-05-2022, 09:44 PM
Good afternoon, I am developing a code to optimize an investment portfolio, but I need to set some limits for the investment of certain assets. I wanted to ask if the above is possible?
For the above I need to create a list with weights.
For example, a portfolio of 3 assets A, B and C, with the following restrictions, asset A cannot represent more than 30% nor less than 10%, asset B cannot represent more than 80% nor less than 50% and asset C a maximum of 20%.
Is there a way to generate a list of weights that meets these restrictions? Thanks in advance.
The code I am using is the following, but it generates weights between 1% and 100%.
For the above I need to create a list with weights.
For example, a portfolio of 3 assets A, B and C, with the following restrictions, asset A cannot represent more than 30% nor less than 10%, asset B cannot represent more than 80% nor less than 50% and asset C a maximum of 20%.
Is there a way to generate a list of weights that meets these restrictions? Thanks in advance.
The code I am using is the following, but it generates weights between 1% and 100%.
import pandas as pd import numpy as np import matplotlib.pyplot as plt retornos = pd.read_excel(r"C:\Users\marce\Desktop\Magister en Finanzas\Mercado de Capitales\PythonSA.xlsx", sheet_name="Hoja1") symbols = ["IPSA", "MSCI world", "PIMCO CORP"] noa = len(symbols) rets= retornos #print(rets.corr()) weights = np.random.random(noa) weights /= np.sum(weights) def port_ret(weights): return np.sum(rets.mean() * weights) * 12 def port_vol(weights): return np.sqrt(np.dot(weights.T, np.dot(rets.cov() * 12, weights))) prets = [] pvols = [] for p in range (5000): weights = np.random.random(noa) weights /= np.sum(weights) prets.append(port_ret(weights)) pvols.append(port_vol(weights)) prets = np.array(prets) pvols = np.array(pvols) plt.figure(figsize=(10, 6)) plt.scatter(pvols, prets, c=prets / pvols,marker='o', cmap='coolwarm') plt.xlabel('expected volatility') plt.ylabel('expected return') plt.colorbar(label='Sharpe ratio')