python投资分析
1. 资产组合的收益与风险
搜集三支股票不少于100个交易日的收盘价,据此计算其收益率与协方差,
并在此基础上计算等权重条件下的组合收益与风险。
未做,以下为例子
import numpy as np
def portstats(ExpReturn, ExpCovariance, PortWts):
PortRisk = 0
for i in range(len(PortWts)):
for j in range(len(PortWts)):
PortRisk += PortWts[i] * PortWts[j] * ExpCovariance[i * 3 + j]
PortReturn = np.sum(ExpReturn * np.array(PortWts))
return np.sqrt(PortRisk), PortReturn
# 组合中每种证券的预期收益率
ExpReturn = [0.000540, 0.000275, 0.000236]
# 组合中证券的协方差矩阵
ExpCovariance = 0.0001 * np.array([5.27, 2.80, 1.74,
2.80, 4.26, 1.67,
1.74, 1.67, 2.90])
ExpCovariance = ExpCovariance.tolist()
# 组合中每种证券的初始权重(初始投资金额)/初始总金额
PortWts = 1.0 / 3 * np.array([1, 1, 1])
PortWts = PortWts.tolist()
# 调用 portstats 函数
PortRisk, PortReturn = portstats(ExpReturn, ExpCovariance, PortWts)
print(PortRisk, PortReturn)
# 计算结果
# 风险(标准差)
# PortRisk = 0.016617
# 组合收益率
# PortReturn = 3.5033e-004
2. 有效前沿与随机模拟收益
利用之前下载的三支股票的收益率、协方差和相关系数等数据计算该三支股票的
有效前沿并给出其他可行集的收益——风险模拟。
未做,以下为例子
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as sco
def frontcon(ExpReturn, ExpCovariance, NumPorts):
noa = len(ExpReturn)
def statistics(weights):
weights = np.array(weights)
z = np.dot(ExpCovariance, weights)
x = np.dot(weights, z)
port_returns = (np.sum(ExpReturn * weights.T))
port_variance = np.sqrt(x)
num1 = port_returns / port_variance
return np.array([port_returns, port_variance, num1])
# 定义一个函数对方差进行最小化
def min_variance(weights):
return statistics(weights)[1]
bnds = tuple((0, 1) for x in range(noa))
# 在不同目标收益率水平(target_returns)循环时,最小化的一个约束条件会变化
target_returns = np.linspace(min(ExpReturn), max(ExpReturn), NumPorts)
target_variance = []
PortsWts = []
for tar in target_returns:
# 在最优化时采用两个约束:1.给定目标收益率;2.投资组合权重和为1
cons = ({'type': 'eq', 'fun': lambda x: statistics(x)[0] - tar},
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
res = sco.minimize(min_variance, noa * [1. / noa, ], method='SLSQP', bounds=bnds, constraints=cons)
target_variance.append(res['fun'])
PortsWts.append(res['x'])
target_variance = np.array(target_variance)
return [target_variance, target_returns, PortsWts]
ExpReturn = np.array([0.00540, 0.00275, 0.00236])
ExpCovariance = 0.0001 * np.array([[5.27, 2.80, 1.74],
[2.80, 4.26, 1.67],
[1.74, 1.67, 2.90]])
NumPorts = 10
[target_variance, target_returns, PortWts] = frontcon(ExpReturn, ExpCovariance, NumPorts)
plt.plot(target_variance, target_returns)
plt.title("Mean-Variance-Efficient Frontier")
plt.xlabel("Risk(Standard Deviation)")
plt.ylabel("Expected Retrun")
plt.show()
3. 单个资产的收益与风险
下载一只股票不少于100个交易日的收盘价,然后据此计算其收益率和风险。(分别用期望和方差表示)
未做,以下为例子
# NumAssets = 3 # 资产数量3个
# PVal = 1 # 配置比例,100%表示满仓配置,若80%,则设PVal=0.8;AssetMin=0各资产最低配置
# # 将各类约束合并到ConSet中
# ConSet = portcons(PVal, NumAssets)
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as sco
noa = 3
ExpReturn = np.array([0.000540, 0.000275, 0.000236])
ExpCovariance = 0.0001 * np.array([[5.27, 2.80, 1.74],
[2.80, 4.26, 1.67],
[1.74, 1.67, 2.90]])
def statistics(weights):
weights = np.array(weights)
z = np.dot(ExpCovariance, weights)
x = np.dot(weights, z)
port_returns = (np.sum(ExpReturn * weights.T))
port_variance = np.sqrt(x)
# port_variance = np.array(port_variance)
num1 = port_returns / port_variance
# arr2 = np.ravel(arr1)
return np.array([port_returns, port_variance, num1])
# 定义一个函数对方差进行最小化
def min_variance(weights):
return statistics(weights)[1]
# 在最优化时采用两个约束:1.给定目标收益率;2.投资组合权重和为1
bnds = tuple((0, 1) for x in range(noa))
# 在不同目标收益率水平(target_returns)循环时,最小化的一个约束条件会变化
target_returns = np.linspace(min(ExpReturn), max(ExpReturn), 10)
target_variance = []
print(target_returns)
for tar in target_returns:
cons = ({'type': 'eq', 'fun': lambda x: statistics(x)[0] - tar},
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
res = sco.minimize(min_variance, noa * [1. / noa, ], method='SLSQP', bounds=bnds, constraints=cons)
target_variance.append(res['fun'])
print(res['x'])
target_variance = np.array(target_variance)
print(target_variance)