python - 在 Python 中为蒙特卡罗模拟结果添加分位数
问题描述
我为单个股票投资组合创建了蒙特卡洛模拟,并希望计算并理想地显示某些分位数。例如,在我的示例中,我有 1000 次运行,并且想要计算结果的 95% 分位数(t252)。
import pandas_datareader.data as web
import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import quandl
style.use('ggplot')
quandl.ApiConfig.api_key = 'dnyYEnFxwxxxxxxxxxxx'
prices = quandl.get(dataset='WIKI/AAPL',start_date='2000-01-01',end_date='2010-12-31')['Close']
returns = prices.pct_change()
last_price = prices[-1]
num_simulations = 1000
num_days = 252
simulation_df = pd.DataFrame()
for x in range(num_simulations):
count = 0
daily_vol = returns.std()
price_series = []
price = last_price * (1 + np.random.normal(0, daily_vol))
price_series.append(price)
for y in range(num_days):
if count == 251:
break
price = price_series[count] * (1 + np.random.normal(0, daily_vol))
price_series.append(price)
count += 1
simulation_df[x] = price_series
fig = plt.figure()
plt.plot(simulation_df)
plt.axhline(y = last_price, color = 'r', linestyle = '-')
plt.show()
有人能告诉我最好的方法是什么吗?我尝试了 Pandas 分位数功能,但不幸的是并没有走多远。
提前谢谢了!
解决方案
熊猫分位数功能是要走的路。如果您想要 252 个值(即每天的 0.95 分位数),您可以使用轴参数:
simulation_df.quantile(.95, axis=1)
如果您只想快速浏览一下,请转置并使用 describe 函数:
simulation_df.T.describe(percentiles=[.95, .75, .5, .25, .05])
推荐阅读
- html - Internet Explorer 多范围输入滑块
- jquery - 寻找包含特定文本的元素并相乘
- java - 扫描仪比打印快?
- c# - 如何在重命名 Visual Studio 项目 (VSIX) 时收到通知?
- excel - 如何使用 VBA 在用户窗体的不同“顶部”位置添加多个标签?
- javascript - Laravel + x-editable:完整性约束违反1048:没有数据通过
- python - ValueError: <__main__.Enemy object at 0x07BFE2F8> 不在列表中
- kubernetes - 在部署配置、openshift 集群的情况下,我们如何确定哪个复制控制器实际上正在管理 Pod
- php - Laravel - 无法打开流:权限被拒绝
- python - 使用python的有限差分法的向量化版本