Search code examples
pythonpandasforex

How to use min/max with shift function in pandas?


I have timeseries data (euro/usd). I want to create new column with conditions that

(It easier to read in my code to understand the conditions.) if minimum of 3 previous high prices less than or equal to the current price then it will be 'BUY_SIGNAL' and if maximum of 3 previous low prices higher than or equal to the current price then it will be 'SELL_SIGNAL'.

Here is my table looks like

DATE    OPEN    HIGH    LOW CLOSE
0   1990.09.28  1.25260 1.25430 1.24680 1.24890
1   1990.10.01  1.25170 1.26500 1.25170 1.25480
2   1990.10.02  1.25520 1.26390 1.25240 1.26330
3   1990.10.03  1.26350 1.27000 1.26030 1.26840
4   1990.10.04  1.26810 1.27750 1.26710 1.27590

and this is my code (I try to create 2 functions and it does not work)

def target_label(df):
   if df['HIGH']>=[df['HIGH'].shift(1),df['HIGH'].shift(2),df['HIGH'].shift(3)].min(axis=1):
      return 'BUY_SIGNAL'
   if df['LOW']>=[df['LOW'].shift(1),df['LOW'].shift(2),df['LOW'].shift(3)].min(axis=1):
        return 'SELL_SIGNAL'
   else:
        return 'NO_SIGNAL'

def target_label(df):
   if df['HIGH']>=df[['HIGH1','HIGH2','HIGH3'].min(axis=1):
      return 'BUY_SIGNAL'
   if df['LOW']<=df[['LOW1','LOW2','LOW3']].max(axis=1):
        return 'SELL_SIGNAL'
   else:
        return 'NO_SIGNAL'


d_df.apply (lambda df: target_label(df), axis=1)

Solution

  • You can use rolling(3).min() to get the minimum of previous 3 rows. The same would work for other functions like max, mean, etc. Something like the following:

    df['signal'] = np.where(
        df['HIGH'] >= df.shift(1).rolling(3)['HIGH'].min(), 'BUY_SIGNAL',
        np.where(
            df['LOW'] >= df.shift(1).rolling(3)['LOW'].min(), 'SELL_SIGNAL',
            'NO_SIGNAL'
        )
    )