首页 > 解决方案 > 在 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 分位数功能,但不幸的是并没有走多远。

提前谢谢了!

标签: pythonpandasdataframerisk-analysis

解决方案


熊猫分位数功能是要走的路。如果您想要 252 个值(即每天的 0.95 分位数),您可以使用轴参数:

simulation_df.quantile(.95, axis=1)

如果您只想快速浏览一下,请转置并使用 describe 函数:

simulation_df.T.describe(percentiles=[.95, .75, .5, .25, .05])

推荐阅读