展开全部
0.导入需要的包import pandas as pd
import numpy as np
import statsmodels.api as sm #统计运算
import scipy.stats as scs #科学计算
import matplotlib.pyplot as plt #绘图
1.选取几只感兴趣的股票
000413 东旭光电,62616964757a686964616fe78988e69d8331333361313362000063 中兴通讯,002007 华兰生物,000001 平安银行,000002 万科A
并比较一下数据(2015-01-01至2015-12-31)
In[1]:
stock_set = ['000413.XSHE','000063.XSHE','002007.XSHE','000001.XSHE','000002.XSHE']
noa = len(stock_set)
df = get_price(stock_set, start_date = '2015-01-01', end_date ='2015-12-31', 'daily', ['close'])
data = df['close']
#规范化后时序数据
(data/data.ix[0]*100).plot(figsize = (8,5))
Out[1]:
2.计算不同证券的均值、协方差
每年252个交易日,用每日收益得到年化收益。计算投资资产的协方差是构建资产组合过程的核心部分。运用pandas内置方法生产协方差矩阵。
In [2]:
returns = np.log(data / data.shift(1))
returns.mean()*252
Out[2]:
000413.XSHE 0.184516
000063.XSHE 0.176790
002007.XSHE 0.309077
000001.XSHE -0.102059
000002.XSHE 0.547441
In [3]:
returns.cov()*252
Out[3]:
3.给不同资产随机分配初始权重
由于A股不允许建立空头头寸,所有的权重系数均在0-1之间
In [4]:
weights = np.random.random(noa)
weights /= np.sum(weights)
weights
Out[4]:
array([ 0.375