Tim Pickup
Tim Pickup

Reputation: 143

If statement on Pandas Dataframe to add column

I'm trying to create a new column in a DataFrame that flags 'signals'. I cannot seem to figure out how to achieve this within pandas without setting variables and doing the following:

all_candles = pd.read_csv('ExportTest.csv', index_col=0)
all_candles.reset_index(level=0, inplace=True)
rows = len(all_candles.index)

for i in range(1,rows):
    current_RSI = all_candles.loc[i]['RSI']
    prev_RSI = all_candles.loc[i-1]['RSI']

    if prev_RSI < 30 and current_RSI >= 30:
        print('BULL SIGNAL')
    elif prev_RSI >= 70 and current_RSI < 70:
        print('BEAR SIGNAL')

Where it states BULL SIGNAL or BEAR SIGNAL, i want it to fill in a new column called all_candles['SIGNAL']. The ideal solution i want is to have it all contained in pandas so i don't have to do a for loop.

e.g. (forgive the crude way of noting this out, i know the syntax isn't valid at all.)

    if all_candles['RSI'].shift(-1) < 30 and all_candles['RSI'] >= 30:
        all_candles['SIGNAL'] = 'BULL'
    elif all_candles['RSI'].shift(-1) >= 70 and all_candles['RSI'] < 70:
        all_candles['SIGNAL'] = 'BEAR'
    else
        all_candles['SIGNAL'] = 'NON'

Any help would be much appreciated with regards to the art of the possible.

Upvotes: 0

Views: 104

Answers (1)

Renaud
Renaud

Reputation: 2819

You can do it with a function and .apply()

import pandas as pd

def signal_cat(RSI_col) :
    current_RSI=RSI_col['RSI']
    prev_RSI=RSI_col['prev_RSI']
    if prev_RSI < 30 and current_RSI >= 30:
        return 'BULL SIGNAL'
    elif prev_RSI >= 70 and current_RSI < 70:
        return 'BEAR SIGNAL'
    else:
        return 'NON'

#définition of your dataframe
all_candles=pd.DataFrame({'RSI':[10,40,75,79,10,20,30]})
all_candles['prev_RSI'] =all_candles['RSI'].shift(1)

all_candles['SIGNAL']=all_candles[['prev_RSI', 'RSI']].apply(signal_cat, axis=1)
print(all_candles)

Result:

   RSI  prev_RSI       SIGNAL
0   10       NaN          NON
1   40      10.0  BULL SIGNAL
2   75      40.0          NON
3   79      75.0          NON
4   10      79.0  BEAR SIGNAL
5   20      10.0          NON
6   30      20.0  BULL SIGNAL

Upvotes: 1

Related Questions