def get_stock_data(t1,t2,stock_name):lg = bs.login()print('login respond error_code:' + lg.error_code)print('login responderror_msg:' + lg.error_msg)#### 获取沪深A股历史K线数据 ##### 详细指标参数,参见“历史行情指标参数”章节rs = bs.query_history_k_data(stock_name,"date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",start_date=t1, end_date=t2,frequency="d", adjustflag="3")print('query_history_k_data respond error_code:' + rs.error_code)print('query_history_k_data responderror_msg:' + rs.error_msg)#### 打印结果集 ####data_list = []while (rs.error_code == '0') & rs.next():# 获取一条记录,将记录合并在一起data_list.append(rs.get_row_data())result = pd.DataFrame(data_list, columns=rs.fields)print(result)#### 结果集输出到csv文件 ####result.to_csv("D:\stockdata\history_A_stock_k_data.csv", index=False)print(result)#### 登出系统 ####bs.logout()result['date'] = pd.to_datetime(result['date'])result.set_index("date", inplace=True)return resultbyjc = get_stock_data('2014-1-1','2015-1-1','sh.600004')hxyh = get_stock_data('2014-1-1','2015-1-1','sh.600015')zndl = get_stock_data('2014-1-1','2015-1-1','sh.600023')fjgs = get_stock_data('2014-1-1','2015-1-1','sh.600033')sykj = get_stock_data('2014-1-1','2015-1-1','sh.600183')by = byjc['pctChg']by.name = 'byjc'by = pd.DataFrame(by,dtype=np.float)/100hx = hxyh['pctChg']hx.name = 'hxyh'hx = pd.DataFrame(hx,dtype=np.float)/100zn = zndl['pctChg']zn.name = 'zndl'zn = pd.DataFrame(zn,dtype=np.float)/100fj = fjgs['pctChg']fj.name = 'fjgs'fj = pd.DataFrame(fj,dtype=np.float)/100sy = sykj['pctChg']sy.name = 'sykj'sy = pd.DataFrame(sy,dtype=np.float)/100sh_return = pd.concat([by,fj,hx,sy,zn],axis=1)res = blacklitterman(sh_return,0.1,P,Q)p_mean = pd.DataFrame(res[0],index = sh_return.columns, columns = ['posterior_mean'])p_cov = res[1]print(p_mean)print(p_cov)
这时候,已经可以使用模型进行资产的配置. 定义新的函数以求解资产配置权重. 该函数的输入变量为函数的输出结果, 以及投资人的目标收益率.假设目标收益率为年化70%,则 = 0.7:
def blminVar(blres, goalRet):covs = np.array(blres[1],dtype=float)means = np.array(blres[0],dtype=float)L1 = np.append(np.append(covs.swapaxes(0,1),[means.flatten()],axis=0),[np.ones(len(means))],axis=0).swapaxes(0,1)L2 = list(np.ones(len(means)))L2.extend([0,0])L3 = list(means)L3.extend([0,0])L4 = np.array([L2,L3],dtype=float)L = np.append(L1,L4,axis=0)results = linalg.solve(L,np.append(np.zeros(len(means)),[1,goalRet]))return pd.DataFrame(results[:-2],columns = ['p_weight'])blresult = blminVar(res,0.70/252)print(blresult)
输出结果为:
0-5分别对应上面的五只股票.
参考文献
- 知乎python储存_知乎高赞回答:有什么相见恨晚的Python技巧
- 在Maix duino开发板上实现LED闪烁
- OpenCV.箱式滤波
- 2. fuse内核队列
- Python:如何用一行代码获取上个月是几月
- 长文!智能物流如何实现全面数字化
- 如何在 Python 中使用 plotly 创建人口金字塔?
- Chapter1 基于python的科研论文配图绘制与配色基础
- 如何使用python来画箱式图?
- 【微电网调度】基于粒子群实现对含并网蓄电池微电网的优化调度附matlab代码