I've done a Python implementation of Markowitz portfolio optimization. The minimization function would ensure the risk is minimized while solving the optimizer to generate certain percentage return based on list of tickers. It also takes into account that sum of weights should be equal 1. Most of the time I generate the results are infeasible. What could be the reason?
import pandas as pd
import numpy as np
from helper_functions.get_data import download_data
from scipy.optimize import minimize
def optimizer(tickers, start_date, end_date, required_return=0.02):
df = download_data(tickers, start_date, end_date)
# Calculate daily returns
returns = df['Close'].pct_change()
# Calculate mean returns and covariance
mean_returns = returns.mean()
cov_matrix = returns.cov()
# Number of portfolio assets
num_assets = len(mean_returns)
# Initialize weights
weights_initial = num_assets * [1. / num_assets,]
# Constraints
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'eq', 'fun': lambda x: np.sum(x*mean_returns) - required_return})
# Bounds
bounds = tuple((0,1) for asset in range(num_assets))
# Objective function
def objective(weights):
return np.dot(weights.T, np.dot(cov_matrix, weights))
# Optimize
result = minimize(objective, weights_initial, method='SLSQP', bounds=bounds, constraints=constraints)
# Return optimization results
return result