بهینه سازی میانگین واریانس مارکویتز با پایتون
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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]}") |
در اینجا توضیحی در مورد کد آمده است: 1. کتابخانه های لازم را وارد می کند – پانداها برای خواندن CSV، numpy برای ماتریس ها و scipy.optimize برای به حداقل رساندن. 2. داده های CSV با استفاده از پانداها در یک دیتافریم خوانده می شوند. 3. بازده مورد انتظار از ستون ‘بازده مورد انتظار’ … ادامه