# 蒙特卡洛模拟股票价格（使用Python）

```＃虚报每日收盘价的申报单
history_prices = [180,192,193,195,191,199,198,200,199,203,205,207,205,208,201,203,204,201,205,206,207]
print(stockPrices)
```
```[180, 192, 193, 195, 206, 211, 191, 204, 215, 190, 205, 207, 205, 211, 222, 215, 245, 201, 205, 206, 214]
```

```＃导入统计信息以计算例如价格历史记录的标准差
import statistics as stat
＃导入pyplot进行绘图
import matplotlib.pyplot as plt
＃导入随机以生成随机数
import random as rnd```

```relative_prices = []
for i in range(0,len(history_prices)):
if i == 0:
pass
else:
relative_prices.append((history_prices[i]-history_prices[i-1])/(history_prices[i-1]))
std_prices = stat.stdev(relative_prices)
print(std_prices)```
`0.021375589655016836`

```＃模拟100天的随机价格上涨
＃-进行计算，定义功能
def randomWalk(stdev,pastPrices):
days = [i for i in range(1,101)]
prices = []
price = pastPrices[-1]
for i in range(1,101):
price = price + price*rnd.normalvariate(0,stdev)
prices.append(price)
return([days,prices])
＃-进行计算，使用功能
prices = randomWalk(std_prices,history_prices)
＃-可视化线图中的随机游走
plt.plot(prices[0],prices[1])
plt.title("random price walk")
plt.xlabel("day")
plt.ylabel("stock price")
```
`Text(0, 0.5, 'stock price')`

```plt.figure()
for i in range(0,30):
prices = randomWalk(std_prices,history_prices)
plt.plot(prices[0],prices[1])
plt.title("monte-carlo simulation of stock price development")
plt.xlabel("day")
plt.ylabel("stock price")
```
`Text(0, 0.5, 'stock price')`