【发布时间】:2021-07-09 18:33:00
【问题描述】:
假设我的初始财富为 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]
我想要的是以下内容:
100*(1 + r) - outflow,
现在流出的是[2. , 2.04 , 2.081, 2.122]。在以前的情况下,它是一个常数,2。在新的情况下,解决方案将是
[100, 100, 98.96, 97.9092, 98.3675]
我该如何合并它?
更新: 很多人问为什么我不能使用 for 循环。这里有一些上下文。而不是一组回报,我想模拟 100,000。请考虑以下事项。
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 花了很长时间。因此我希望避免 for 循环。
【问题讨论】:
-
不清楚您要计算的公式或输入的内容。
-
已编辑。看看这是否有意义。
-
为什么有不使用
for循环的限制? -
@mkrieger1 - 在我的例子中,r,返回矩阵是 n*m,其中 n = 100,000 和 m = 40。我必须为 10 个不同的实例执行此操作。 For 循环运行时间过长。