不带for循环的收益和流出的累积财富计算

jhiyze9q  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(203)

假设我的初始财富为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循环。这里有一些上下文。而不是一组返回,我想模拟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))

这个跑得很快。因为这个循环花了很长时间。因此,我希望避免循环。

oxosxuxt

oxosxuxt1#

循环是一个非常容易在这里使用的解决方案

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)]

相关问题