import pandas as pd
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
from pylab import mpl
S = pd.read_excel(r'C:\Users\Dell\Desktop\中国东航.xlsx',sheet_name="中国东航",header=0,index_col=0)
S.describe()
S.tail()
R=np.log(S/S.shift(1))
R=R.dropna()
R.plot(figsize=(8, 6))
mu=R.mean()*252
sigma=R.std()*np.sqrt(252)
plt.show()
print('股票的预期年化收益率',round(mu,4))
print('股票收益的年化波动率',round(sigma,4))
help(pd.DatetimeIndex)
import numpy.random as npr
date=pd.date_range(start='2021-12-01',end='2023-12-12',freq='B')
N= len(date)
I= 200
dt= 1.0/252
mu= np.array(mu)
sigma= np.array(sigma)
S_GBM= np.zeros((N, I))
S_GBM[0]= 4.86
N=len(date)
for t in range(1, N):
epsilon = npr.standard_normal(I)
S_GBM[t] = S_GBM[t-1]np.exp((mu-0.5sigma*2)dt+sigmaepsilonnp.sqrt(dt))
S_GBM=pd.DataFrame(S_GBM, index=date)#将模拟的数值转化为带有时间索引的数据框
print(S_GBM.head())#查看前五行
print(S_GBM.tail())#查看后五行
print(S_GBM.describe())
plt.figure(figsize=(8, 6))
plt.plot(S_GBM)
plt.xlabel(u'日期', fontsize=13)
plt.ylabel(u'股价', fontsize=13, rotation=0)
plt.xticks(fontsize=13, rotation=30)
plt.yticks(fontsize=13)
plt.title(u'服从几何布朗运动的股价模拟全部路径(2019-2021年)',fontsize=13)
plt.grid('True')
plt.show()
plt.figure(figsize=(8, 6))
plt.plot(S_GBM.iloc[:, 0:10])
plt.xlabel(u'日期', fontsize=13)
plt.ylabel(u'股价', fontsize=13, rotation=0)
plt.xticks(fontsize=13, rotation=30)
plt.yticks(fontsize=13)
plt.title(u'服从几何布朗运动的股价模拟前10条路径(2019-2021年)',fontsize=13)
plt.grid('True')
plt.show()
读取excel时用到了openpyxl,你需要安装一下
pip install openpyxl
建议这边多看看报错,可以直接把报错百度一下,会很轻松的找到解决方案的