0

I have been getting the following error message:

IndexError                                Traceback (most recent call last)
Cell In [29], line 12
      8 for index, row in df.iterrows():
      9     # if the 50-day moving average is above the 200-day moving average
     10     if row['ma50'] > row['ma200']:
     11         # get the call options data for the current date
---> 12         call_options = options[5]['calls']
     13         # find the call option with the highest implied volatility
     14         max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]

IndexError: tuple index out of range

I have tried multiple things, but to no avail. What could I do to resolve the issue?

Why did my options trading strategy fail in this back-test? I had such high hopes for it, expecting it to bring in a profit based on the data and assumptions I inputted. But instead, it resulted in a loss. Is there a problem with the back-testing tool I'm using, or is there something else at play here? I implore anyone with experience in this field to offer their insights and suggestions on how to troubleshoot this frustrating issue. I have developed an options trading back-testing strategy as follows:

import yfinance as yf

start_date = "2020-01-01"
end_date = "2022-12-31"

stock = yf.Ticker("SPY")
df = stock.history(start=start_date, end=end_date)

def moving_average(df, window):
    return df['Close'].rolling(window=window).mean()

df['ma50'] = moving_average(df, 50)
df['ma200'] = moving_average(df, 200)

position = 0

long_trades = 0
short_trades = 0

options = stock.option_chain()

for index, row in df.iterrows():
    # if the 50-day moving average is above the 200-day moving average
    if row['ma50'] > row['ma200']:
        # get the call options data for the current date
        call_options = options[5]['calls']
        # find the call option with the highest implied volatility
        max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]
        # buy the call option with the highest implied volatility
        long_trades += 1
    # if the 50-day moving average is below the 200-day moving average
    elif row['ma50'] < row['ma200']:
        # get the put options data for the current date
        put_options = options[index.date()]['puts']
        # find the put option with the highest implied volatility
        max_iv_put = put_options[put_options['impliedVolatility'] == put_options['impliedVolatility'].max()]
        # buy the put option with the highest implied volatility
        short_trades += 1

print(f"Number of long trades: {long_trades}")
print(f"Number of short trades: {short_trades}")

0 Answers0