# python金融蒙特卡洛模拟相关参数计算并生成图片

``````
import numpy as np
import numpy.random as npr
import pandas as pd
import matplotlib.pyplot as plt

# 导入外部数据
# print(stock_price)

# X为置信水平，I为蒙特卡洛模拟的次数，P0为固值（是后台设定还是老师设定待定）
# X = float(input("请输入置信水平："))
I = 10000
P0 = 1000

# 股票日收益
stock_return = np.log(stock_price/stock_price.shift(1))
# 删除缺失行
stock_return = stock_return.dropna()
# print(stock_return)

a = stock_return.loc[:,"收盘/最新价"]
# print(a)
# a_mean为平均收益率  b为保留小数点后四位的a_mean
a_mean =a.mean()*252
# 计算资产收益率的年化波动率
a_vol = a.std()*np.sqrt(252)
# 设定交易日的步长
dt = 1/252

# excel中投资组合中资产的个数
N_assets=len(stock_return.columns)

# 从标准正态分布中抽取随机数
epsilon = npr.standard_normal(size=I)

# 取excel表格中月末的股价并以数组格式
p=np.array(stock_price.iloc[-1])

# 生成放置下一个交易日资产价格初始数组
p_new = np.zeros(shape=(I,N_assets))
p_new[:,0] = p*np.exp((a_mean-0.5*a_vol**2)*dt + a_vol*epsilon*np.sqrt(dt))

S = P0*np.exp(np.cumsum((a_mean - 0.5*a_mean **2) *dt +a_mean *np.sqrt(dt) *np.random.standard_normal((50, I)),axis=0))

# 计算模拟下一个交易日投资组合盈亏额
s_delta=(np.dot(p_new/(p.T)-1,1))*P0

# 计算var的值
var = np.abs(np.percentile(a=s_delta,q=(1-0.95)*100))
print(var)

N = int(input("请输入持有天数:"))
var1 = np.sqrt(N)*float(var)
print(var1)

plt.hist(S,bins = 100)
plt.xlabel('price')
plt.ylabel('ferquency')
plt.show()

# 路径可视化 lw为所绘线的粗细
plt.plot(S,lw=1)
plt.xlabel('time step')
plt.ylabel('index level')
plt.show()

``````