1

I want to add a new column named bullTrend to my (ohlcv) dataframe which is based on the previous values of 2 columns:

  • If current & previous 11 rows close price is higher than ema -> value of bullTrend changes to True
  • If current & previous 11 rows close price is lower than ema -> value of bullTrend changes to False
  • First values -> value of bullTrend changes to NaN
  • Don't include last row

Dataset:

             timestamp    open    high     low   close    volume          ema
    0    1591162860000  9490.0  9489.5  9489.5  9489.5       1.0  9489.500000
    1    1591162920000  9489.5  9490.0  9490.0  9490.0     406.0  9489.751250
    2    1591162980000  9490.0  9490.0  9490.0  9490.0     488.0  9489.834997
    3    1591163040000  9490.0  9497.0  9489.5  9489.5   12798.0  9489.749988
    4    1591163100000  9489.5  9497.0  9489.0  9497.0    1866.0  9491.229134
    ..             ...     ...     ...     ...     ...       ...          ...
    495  1591192560000  9524.5  9524.5  9524.0  9524.5    1727.0  9564.513010
    496  1591192620000  9524.5  9524.5  9523.0  9523.0  179978.0  9564.097058
    497  1591192680000  9523.0  9524.0  9523.0  9524.0     582.0  9563.695321
    498  1591192740000  9524.0  9523.0  9523.0  9523.0       2.0  9563.287617
    499  1591192800000  9523.0  9524.0  9523.0  9524.0    1324.0  9562.894044

Example of the column:

     bullTrend 
0    NaN
1    NaN
2    NaN
3    NaN
4    True
..             ...
495  True
496  True
497  False
498  False
499  False
Kobe Janssens
  • 310
  • 2
  • 13
  • it seems to be similar as https://stackoverflow.com/questions/22081878/get-previous-rows-value-and-calculate-new-column-pandas-python ? – linpingta Jun 03 '20 at 14:33

1 Answers1

2

This should work:

def isBull(row):
    idx = row.name
    if idx in idxs:
        return row['eta'] < min([df.at[idx-i, 'close'] for i in range(12)])
    else:
        return np.nan

idxs = df.index[12:-1]
df['bullTrend'] = df.apply(isBull, axis=1)
pzmn
  • 154
  • 5