更新:不确定如果没有某种形式的aloop是否可行,但是在这里,np.where将不起作用。如果答案是“你不能”,那就顺其自然吧。如果可以,它可能会使用来自scipy.signal的内容。
我想在下面的代码中对循环进行向量化,但由于输出的递归性质,不确定如何进行。
浏览当前设置:
取起始金额(100万美元)和季度美元分配(5000美元):

dist = 5000.
v0 = float(1e6)

以每月频率生成一些随机安全/帐户返回(十进制形式):
r = pd.Series(np.random.rand(12) * .01,
              index=pd.date_range('2017', freq='M', periods=12))

创建一个空序列,该序列将保存每月帐户值:
value = pd.Series(np.empty_like(r), index=r.index)

将“开始月份”添加到value。此标签将包含v0
from pandas.tseries import offsets
value = (value.append(Series(v0, index=[value.index[0] - offsets.MonthEnd(1)]))
              .sort_index())

我想去掉的循环在这里:
for date in value.index[1:]:
    if date.is_quarter_end:
        value.loc[date] = value.loc[date - offsets.MonthEnd(1)] \
                        * (1 + r.loc[date]) - dist
    else:
        value.loc[date] = value.loc[date - offsets.MonthEnd(1)] \
                        * (1 + r.loc[date])

组合代码:
import pandas as pd
from pandas.tseries import offsets
from pandas import Series
import numpy as np

dist = 5000.
v0 = float(1e6)
r = pd.Series(np.random.rand(12) * .01, index=pd.date_range('2017', freq='M', periods=12))
value = pd.Series(np.empty_like(r), index=r.index)
value = (value.append(Series(v0, index=[value.index[0] - offsets.MonthEnd(1)])).sort_index())
for date in value.index[1:]:
    if date.is_quarter_end:
        value.loc[date] = value.loc[date - offsets.MonthEnd(1)] * (1 + r.loc[date]) - dist
    else:
        value.loc[date] = value.loc[date - offsets.MonthEnd(1)] * (1 + r.loc[date])

在psuedocode中,循环所做的只是:
for each date in index of value:
    if the date is not a quarter end:
        multiply previous value by (1 + r) for that month
    if the date is a quarter end:
        multiply previous value by (1 + r) for that month and subtract dist

问题是,我目前不知道矢量化是如何实现的,因为连续的值取决于前一个月是否进行了分布。我得到了期望的结果,但是对于更高频率的数据或更大的时间段,效率相当低。
python - 递归:具有分布的帐户值-LMLPHP

最佳答案

您可以使用以下代码:

cum_r = (1 + r).cumprod()
result = cum_r * v0
for date in r.index[r.index.is_quarter_end]:
     result[date:] -= cum_r[date:] * (dist / cum_r.loc[date])

你会做:
1所有月度收益的累计产品。
1个矢量与标量相乘v0
带标量的矢量乘法
n矢量减法
其中,dist / cum_r.loc[date]是季度结束数。
基于此代码,我们可以进一步优化:
cum_r = (1 + r).cumprod()
t = (r.index.is_quarter_end / cum_r).cumsum()
result = cum_r * (v0 - dist * t)

哪个是
1累积积n
1两个系列之间的划分n
1上述除法的累计和
1上述和与标量的乘积(1 + r).cumprod()
1标量减去r.index.is_quarter_end / cum_rwithdist
v0dist * t的逐点乘法

关于python - 递归:具有分布的帐户值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45820242/

10-14 17:36
查看更多