当然,以下是一个使用 Python 进行投资组合优化的示例代码:

import numpy as np
import pandas as pd
from scipy.optimize import minimize

# 导入数据
data = pd.read_csv('data.csv')

# 定义目标函数
def objective(weights):
    weights = np.array(weights)
    port_return = np.sum(data.mean() * weights) * 252
    port_variance = np.sqrt(np.dot(weights.T, np.dot(data.cov() * 252, weights)))
    return port_variance / port_return

# 定义约束条件
def constraint(weights):
    return np.sum(weights) - 1

cons = {'type': 'eq', 'fun': constraint}

# 设置初始权重
init_weights = np.ones((data.shape[1],)) / data.shape[1]

# 进行优化
result = minimize(objective, init_weights, constraints=cons)

# 输出结果
print('Optimal weights:', result.x)
print('Portfolio return:', np.sum(data.mean() * result.x) * 252)
print('Portfolio variance:', np.sqrt(np.dot(result.x.T, np.dot(data.cov() * 252, result.x))))

在此示例中,我们从名为'data.csv'的数据文件中导入数据,并使用 Scipy 的 minimize 函数来优化目标函数。我们的目标是最小化投资组合的风险和收益之比。我们还定义了一个约束条件,即投资组合中所有股票的权重之和必须等于 1。最终,我们得到了投资组合的最优权重,以及其预期收益和风险。


原文地址: https://www.cveoy.top/t/topic/nwfK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录