大 pandas [英] Random walk pandas

查看:140
本文介绍了大 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在熊猫中快速创建一个模拟的随机游走系列.

I am trying to quickly create a simulated random walk series in pandas.

import pandas as pd
import numpy as np
dates = pd.date_range('2012-01-01', '2013-02-22')
y2 = np.random.randn(len(dates))/365
Y2 = pd.Series(y2, index=dates)
start_price = 100

想建立另一个起始于起始日期的start_price并以随机增长率增长的日期序列. 伪代码:

would like to build another date series starting at start_price at beginning date and growing by the random growth rates. pseudo code:

P0 = 100
P1 = 100 * exp(Y2)
P2 = P1 * exp(Y2)

在excel中很容易做到,但是我想不出不用熊猫来遍历一个数据框/系列的方法,而且我也为此感到震惊.

very easy to do in excel, but I cant think of way of doing it without iterating over a dataframe/series with pandas and I also bump my head doing that.

尝试过:

p = Y2.apply(np.exp)-1
y = p.cumsum(p)
y.plot()

这应该给出自开始以来的累计复合收益

this should give the cumulatively compound return since start

推荐答案

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def geometric_brownian_motion(T = 1, N = 100, mu = 0.1, sigma = 0.01, S0 = 20):        
    dt = float(T)/N
    t = np.linspace(0, T, N)
    W = np.random.standard_normal(size = N) 
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
    X = (mu-0.5*sigma**2)*t + sigma*W 
    S = S0*np.exp(X) ### geometric brownian motion ###
    return S

dates = pd.date_range('2012-01-01', '2013-02-22')
T = (dates.max()-dates.min()).days / 365
N = dates.size
start_price = 100
y = pd.Series(
    geometric_brownian_motion(T, N, sigma=0.1, S0=start_price), index=dates)
y.plot()
plt.show()

这篇关于大 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆