python - Pandas :分配具有多个条件和日期阈值的列

标签 python pandas dataframe finance portfolio

编辑:

我在 Pandas 数据框 df 中有一个金融投资组合,其中索引是日期,每个日期我有多个金融股票。

例如数据框:

Date    Stock   Weight  Percentile  Final weight
1/1/2000    Apple   0.010   0.75    0.010
1/1/2000    IBM    0.011    0.4     0
1/1/2000    Google  0.012   0.45    0
1/1/2000    Nokia   0.022   0.81    0.022
2/1/2000    Apple   0.014   0.56    0
2/1/2000    Google  0.015   0.45    0
2/1/2000    Nokia   0.016   0.55    0
3/1/2000    Apple   0.020   0.52    0
3/1/2000    Google  0.030   0.51    0
3/1/2000    Nokia   0.040   0.47    0

每当 Percentile 大于 0.7

时,我都会通过分配 Weight 的值来创建 Final_weight

现在我想让它更复杂一些,我仍然希望在 Percentile > 0.7 时将 Weight 分配给 Final_weight,但是在这个日期之后(在未来的任何时候),当股票 Percentile 不是 >0.7 时,我们仍然会得到一个权重,而不是变成 0,只要股票 Percentile 高于 0.5(即持仓时间超过一天)。

然后,如果股票低于 0.5(在不久的将来),则 Final_weight 将变为 0

例如从上面修改的数据框:

Date    Stock   Weight  Percentile  Final weight
1/1/2000    Apple   0.010   0.75    0.010
1/1/2000    IBM     0.011   0.4     0
1/1/2000    Google  0.012   0.45    0
1/1/2000    Nokia   0.022   0.81    0.022
2/1/2000    Apple   0.014   0.56    0.014
2/1/2000    Google  0.015   0.45    0
2/1/2000    Nokia   0.016   0.55    0.016
3/1/2000    Apple   0.020   0.52    0.020
3/1/2000    Google  0.030   0.51    0
3/1/2000    Nokia   0.040   0.47    0

每天的投资组合都不同,并不总是拥有与前一天相同的股票。

最佳答案

这个解决方案更明确,更少 pandas-esque,但它只涉及一次遍历所有行而不创建大量临时列,因此可能更快。它需要一个额外的状态变量,我将它包装到一个闭包中,这样就不必创建一个类了。

def closure():
    cur_weight = {}
    def func(x):
        if x["Percentile"] > 0.7:
            next_weight = x["Weight"]
        elif x["Percentile"] < 0.5 :
            next_weight = 0
        else:
            next_weight = x["Weight"] if cur_weight.get(x["Stock"], 0) > 0 else 0
        cur_weight[x["Stock"]] = next_weight
        return next_weight
    return func

df["FinalWeight"] = df.apply(closure(), axis=1)

关于python - Pandas :分配具有多个条件和日期阈值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791970/

相关文章:

python - Pandas :如何拆开系列

R,联合两个具有不同列名且不匹配的数据框

python - 编辑信息有限的嵌套字典

python - 使用 xpath 提取表列值(不包括 <sup>)

python - 指定 python 字典中可能的值

python - 在 Pandas 数据框中,使用 bool 输出,如何检测两个不同列(行)的交叉?

python - 打印时指定 Pandas DataFrame 列之间的空格数

python - 从 Matplotlib 图的工具栏禁用坐标

python - 使用 df.resample 时如何使 NaN 值总和为 NaN 而不是 0?

python - pandas - 绘制分箱 x 与 y 的更好方法