【问题标题】:Perform calculations based on signals in array根据数组中的信号执行计算
【发布时间】:2019-12-22 15:11:45
【问题描述】:

我有两列 - 一个数组中的“关闭”列和一个“信号”列。我想根据“信号”列中的分类数据对“关闭”列中的数据进行计算。如果相同的信号连续出现(忽略 NAN),则什么也不做,仅当索引 n+t 处的“信号”数据与索引 n 处的前面“信号”数据相反时执行计算。

这是一个基本的回测代码,以证明我逻辑上提出的算法的能力。我知道可能需要一个 for 循环才能正确应用,但在尝试应用到数据的特定索引点时不确定如何正确应用。

伪代码

for n in signals:
    if signals == 1: 
        if 'signals' n+t == 1 maintain 'close' at n index point:
        when 'signals' n+t == 2
            return ['close'(n+t) - 'close'(n)] in 'calculations' at index n+t

这是我希望通过程序化方法获得的输出。

   close  signals  calculations
0  100    NAN      NAN
1  105    1        NAN
2  110    NAN      NAN
3  107    1        NAN
4  115    NAN      NAN
5  120    2        15

感谢您的帮助,如果需要任何说明,请告诉我!

【问题讨论】:

  • 为什么15calculations(最后一行)?
  • 120 - 105 = 15 关闭(n+t) - 关闭(n)
  • nt 是什么?
  • 只是任意的索引点。 n 是 'signals' = 1 的索引点,t 是 'signals' = 2 的索引点,跳过 NAN 和可能出现的任何其他 1。

标签: python pandas loops numpy signals


【解决方案1】:

一种方法可能是:

  1. 使用dropna提取“信号”不为空的行
  2. 使用shift删除连续重复
  3. 设置输出列:如果信号 = 2,则设置close 差异,否则:设置NaN。我用np.where()
  4. 使用join将此列更新为输入数据框

代码如下:

# Import modules
import pandas as pd
import numpy as np

# Build dataset
data = [[10,  np.NaN,  ],
        [105, 1,       ],
        [110, np.NaN,  ],
        [107, 1,       ],
        [115, np.NaN,  ],
        [120, 2,       ]]
df = pd.DataFrame(data, columns=["close", "signals"])


# Select rows where "signals" not null and remove duplicates
sub_df = df.dropna(subset=['signals'])

# Remove consecutive duplicates
sub_df = sub_df.loc[sub_df.signals.shift() != sub_df.signals]

# If signal == 2, set diff between close and previous close
# Else: set NaN
sub_df['output'] = np.where(sub_df.signals == 2, sub_df.close - sub_df.close.shift(), np.NaN)
print(sub_df)
#    close  signals  output
# 1    105      1.0     NaN
# 5    120      2.0    15.0

# Update dataframe with the new column
print(df.join(sub_df['output']))
#    close  signals  output
# 0     10      NaN     NaN
# 1    105      1.0     NaN
# 2    110      NaN     NaN
# 3    107      1.0     NaN
# 4    115      NaN     NaN
# 5    120      2.0    15.0

【讨论】:

  • 效果很好,我会做相应的调整。感谢您的帮助和时间!
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
相关资源
最近更新 更多