0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like exactly what i'm looking for however i'm getting an error when i've implemented it... signal_cat() missing 1 required positional argument: 'current_RSI'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.