假设我的起始财富为100美元,回报率为2%、1%、-1%、0.5%。此外,我在每个时间点都有2美元的支出。我想计算每个时间点的累积财富。我可以通过以下方式来做到这一点。
import numpy as np
import itertools
r = np.array([100, 0.02, 0.01, -0.01, 0.005])
def wealth(rs, out = 2):
# rs : (initial wealth, return) array, (n+1) x 1
# w : wealth is calculated iteratively
# annual outflow : 2
return list(itertools.accumulate(rs, lambda w,r: w*(1+r)-out))
wealth(r)
它返回
[100.0, 100.0, 99.0, 96.01, 94.49005]
到目前为止,它是有效的。现在假设流出/支出不是恒定的,而是每个时间步长都不同。例如,它可能是一系列预先确定的费用,或者每次膨胀2%,所以我的新费用是
np.array([2*((1 + 0.02)**n) for n in range(len(r)-1)]).round(3)
[2. , 2.04 , 2.081, 2.122]
我想要的是以下内容:CCD_ 1,其中流出现在是CCD_ 2。在以前的情况下,它是一个常数,2。在新的情况下,解决方案将是
[100, 100, 98.96, 97.9092, 98.3675]
我该如何融入其中?
更新:你们中的许多人问我为什么不能使用for循环。以下是一些上下文。我想模拟100000,而不是一组回报。考虑以下内容。
N = 100000
n = 40
r = np.array(np.random.normal(0.05, 0.14, N*n)).reshape((N, n))
rm0 = np.insert(rm, 0, 100, axis=1)
result = np.apply_along_axis(wealth, 1, rm0) # N wealth paths are created
import pandas as pd
allWealth = pd.DataFrame(result.T, columns=range(N), index=range(n+1))
这跑得很快。因为循环花了很长时间。因此,我希望避免循环。
for loop在这里使用是一个非常容易的解决方案
def wealth(rs, out):
result = [rs[0]]
for r, o in zip(rs[1:], out):
result.append(result[-1] * (1 + r) - o)
return result
结果似乎大不相同:[100.0, 100.0, 98.96, 95.8894, 94.24684]
accumulate
版本不是很好的
def wealth(rs, out):
fct = lambda prv, val: (prv[0] * (1 + val[0]) - out[prv[1]], prv[1] + 1)
return [x[0] for x in itertools.accumulate(zip(rs, range(len(rs))), fct)]