基于python的金融分析与风险管理-代码块-c8-股票投资组合

绘图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt  
##Matplotlib是一个用于绘制数据可视化的Python库。它提供了一种类似于Matlab的绘图接口,可以用于生成各种静态、动态、交互式的图形,包括线图、散点图、柱状图、饼图、等高线图等。
###Matplotlib具有强大的功能和灵活的可定制性,可以满足各种数据可视化的需求。

from pylab import mpl  
##pylab是一个Python库,用于科学计算,数据分析和绘图。它是Matplotlib库的一个模块,提供了类似于MATLAB的绘图接口。
##pylab库结合了NumPy库和Matplotlib库的功能,使得用户可以使用简单的命令来创建和定制各种类型的图形。

mpl.rcParams['font.sans-serif']= ['SimHei']  
##这段代码的意思是设置matplotlib图表的默认字体为"SimHei",即使用"SimHei"字体来显示中文。

mpl.rcParams['axes..unicode _minus']= False  
##  mpl.rcParams[‘axes.unicode_minus’] = False是Matplotlib库中的一个配置参数,用于设置轴标签是否显示减号的Unicode字符。应该是不显示负轴的意思


index_data = pd.read_excel('C:/desktop/a.xlsx', sheet_name = "sheet1", header = 0, index_col = 0)  
## 数据的第一行将被作为列名,第一列将被作为行索引。读取的数据将被存储在名为index_data的Pandas DataFrame中。

index_data.plot(subplots= True, layout = (2,2), figsize = (10, 10), fontsize = 13, grid = True)  
##这行代码是用来绘制一个包含4个子图的图表,并设置图表的布局为2行2列。
##其中,参数subplots=True表示创建子图,layout=(2,2)表示布局为2行2列,figsize=(10,10)表示图表的大小为10x10英寸,fontsize=13表示字体的大小为13,grid=True表示显示网格线。

随机数

##预期收益率
x = np.random.random(5) ##这些随机浮点数的范围在0到1之间。
weights = x/np.sum(x)  #broadcasting
print(weights)
round(sum(weights,2) #检验

方差

(data/data.iloc[0]).plot(figsize = (8,6))  ##根据第一行进行归一化

R = np.log(data/data.shift(1)) ###data.shift(1)将数据框中的每一列向下移动一行,并将第一行的值替换为缺失值。
####对数收益率
R = R.dropna()
R = R.describe()
R.hist(bins = 40, figsize = (10, 10))  #其中参数bins=40表示将数据分成40个区间,每个区间表示一个柱子
R_mean = R.mean()*252
R_cov = R.cov()*252
R_corr = R.corr()
R_vol = R.std()*mp.sqrt(252)

R_port = np.sum(weights * R_mean)  #投资组合预期收益率
vol_port = np.sqrt(np.dot(weights, np.dot(R_cov, weights.T)))  ###投资组合方差

模拟有效前沿

Rp_list = []  ##列表是Python中用来存储多个值的数据结构,可以存储不同类型的数据。
Vp_lisp = []
for i in np.range(1000):
  x = np.random.random(5)
  weights = x/sum(x)
  Rp_list.append(np.sum(weights*R_mean))
  Vp_list.append(np.sqrt(np.dot(weights, np.dot(R_cov, weights.T))) )

plt.figure()   ###用于创建一个新的图形窗口
plt.scatter(Vp_list, Rp_list)
plt.xlabel((u'波动率',fontsize = 13)
plt.ylabel((u'收益率',fontsize = 13, rotation = 0##rotation=0表示标签不旋转
plt.xticks(fontsize = 13) ###设置x轴刻度的字体大小
plt.yticks(fontsize = 13)
plt.xlim(0.1, 0.28) ###用于设置x轴的取值范围
plt.ylim(-0.1, 0.2)
plt.title(u'投资组合收益率与波动率的关系', fontsize= 13)
plt.grid('True')  #plt.grid(‘True’)用于显示图形的网格线
plt.show()  ###plt.show()用于显示图形

最优解 optimize包

import scipy.optimize as sco
def f(w):
  w = np.array(w)  #将变量w转换为NumPy数组
  Rp_opt = np.sum(w*R_mean)
  Vp_opt = np.sqrt(np.dot(w, np.dot(R_cov, w.T)))
  return np.array([Rp_opt, Vp_opt])

def Vmin_f(w):
  return f(w)[1]   ###读取第一个数字

cons = ({'type':'eq', 'fun':lambda x:np.sum(x)-1}, {'type':'eq', 'fun':lambda x:f(x)[0]-0.1})  
###该变量用于optimize,表示约束。eq表示等式,ineq表示不等式。

bnds =tuple( (0,1) fox x in range(len(R_mean))) ##以元组格式生成边界条件  ##不对 要检查

x0 = len(R_mean)*[1.0/len(R_mean), ]  
##生成初始权重
##列表的乘法操作符会将列表重复指定的次数;

results = scp.minimize(Vmin_f, x0, method = 'SLSQP', bounds = bnds, constraints = cons)

有效前沿可视化

Rp_target = np.linspace(Rp_vmin, 0.25, 100) ###包含Rp_vmin到0.25之间的100个等距元素
Vp_target = []

for r in Rp_target:
  cons = ({'type':'eq', 'fun':lambda x:np.sum(x)-1}, {'type':'eq', 'fun':lambda x:f(x)[0]-r})  
  results_new = scp.minimize(Vmin_f, len(R_mean)*[1.0/len(R_mean), ], method = 'SLSQP', bounds = bnds, constraints = cons_new)
  Vp_target.append(results_new['fun'])

plt.figure(figsize = (8, 6))   ###用于创建一个新的图形窗口
plt.scatter(Vp_list, Rp_list)
plt.plot(Vp_target, Rp_target, 'r-', lable=u'有效前沿', lw = 2.5)  ##r-红色实线   lw表示线宽2.5  u是Unicode的意思,python2.x中需要,3.x不需要
plt.plot(Vp_vmin, Rp_vmin, 'y*', lable=u'全局最小波动率', markersize = 14)  ##y*黄色星标   
plt.xlabel((u'波动率',fontsize = 13)
plt.ylabel((u'收益率',fontsize = 13, rotation = 0)  
plt.xticks(fontsize = 13) ###设置x轴刻度的字体大小
plt.yticks(fontsize = 13)
plt.xlim(0.15, 0.28) ###用于设置x轴的取值范围
plt.ylim(-0.1, 0.25)
plt.title(u'投资组合的有效前沿', fontsize= 13)
plt.legend(fontsize = 13)  ###图例的字体大小
plt.grid('True')  
plt.show()  

线性回归

##R_index 为hs300对数收益率的时间序列
import statsmodels.api as sm

R_index_addcons = sm.add_constant(R_index)

model_shjc = sm.OL(endog = R.iloc[:,0], exog = R_index_addcons)
#endog表示因变量
## exog代表自变量

result_shjc=model_shjc.fit()

result_shjc.summary()
posted @   \epsilon_t  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示