Not filtering RSI and ROC properly in Python library BT

48 Views Asked by At

I am having problem with my strategy that is supposed to take trades when RSI is above 70, and ROC is above 5, as an example. But when I print out the values in the trades afterwards, it shows RSI below 70. I also tried with only the RSI signals and then use the "SelectMomentum" in the strategy with no luck, same result.

So, it doesn't seem to filter both RSI and ROC at the same time. But when running it one on one, then both works individually.

This is the code I have been trying, but can't seem to find the problem here. Not even ChatGPT could help me, but that may depends on how I asked. ;-)

Can someone please shed the light for me here?


import bt
import pandas as pd
import talib as ta

# List of stock symbols to test
stock_symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META']

data = bt.get(stock_symbols, start='2023-06-01', end='2023-12-31')

# Fill NaN values with zero
data_filled = data.fillna(0)

# Calculate RSI for each stock
rsi = data_filled.apply(lambda x: ta.RSI(x, timeperiod=14))

# Calculate ROC for each stock
roc = data_filled.apply(lambda x: ta.ROC(x, timeperiod=25))
#roc = data_filled.pct_change(25) * 100  # 25-day ROC, multiplied by 100 for percentage

# Create signals based on RSI and momentum
rsi_signal = rsi > 70

# Create a signal based on ROC
roc_signal = roc > 5

# Create the combined signal
combined_signal = rsi_signal & roc_signal

# Create the strategy
my_strategy = bt.Strategy('s1', [
    bt.algos.RunAfterDate('2023-07-01'),  # Run after the specified date
    bt.algos.RunWeekly(),
    bt.algos.SelectWhere(combined_signal),
    #bt.algos.SelectMomentum(n=1, lookback=pd.DateOffset(days=25)),
    bt.algos.WeighEqually(),
    bt.algos.Rebalance()
])

# Create the backtest and run it
test = bt.Backtest(my_strategy, data)
result = bt.run(test)

# Access RSI values
rsi_values_list = []
roc_values_list = []

# Get the latest transactions
latest_transactions = result.get_transactions().tail(10)  # You can adjust the number as needed

# Print RSI values for the stocks in the latest transactions
#for stock, date in latest_transactions.index:
for date, stock in latest_transactions.index:
    rsi_value = rsi.loc[date, stock]
    roc_value = roc.loc[date, stock]
    print(f"Stock: {stock}, Date: {date}, RSI: {rsi_value}, ROC: {roc_value}")

print("***end***")

0

There are 0 best solutions below