import pandas as pd
import numpy as np
from scipy.optimize import minimize
# Read the data from data.csv
data = pd.read_csv('data.csv')
# Extract the expected returns and covariance matrix
returns = data['expected return']
covariance = np.diag(data['expected return'].values)
# Define the objective function to minimize
def objective(weights, covariance):
return np.dot(weights.T, np.dot(covariance, weights))
# Define the constraint - weights should be non-negative
def constraint(weights):
return np.sum(weights) - 1
# Define the bounds for the weights
bounds = [(0, None)] * len(returns)
# Define the initial guess for the weights
initial_guess = [1/len(returns)] * len(returns)
# Define the optimization problem
problem = {
'fun': objective,
'x0': initial_guess,
'args': (covariance,),
'constraints': {'type': 'eq', 'fun': constraint},
'bounds': bounds
}
# Solve the optimization problem
result = minimize(**problem)
# Extract the optimal weights
optimal_weights = result.x
# Print the optimal weights
for i, stock in enumerate(data['named']):
print(f"Weight for {stock}: {optimal_weights[i]}")