I have created a python multi-time-frame analysis backtest program based on the following site. ( ref site )
The code I created is as follows
import os
import warnings
from datetime import datetime
!pip install pandas_ta > /dev/null 2>&1
import pandas as pd
import pandas_ta as ta
import numpy as np
import matplotlib.pyplot as plt
!pip install --upgrade backtesting > /dev/null 2>&1
from backtesting import Backtest, Strategy
from backtesting.lib import resample_apply, crossover
from backtesting.test import SMA
from google.colab import drive
drive.mount('/content/drive')
# -------------------------------------------------------
# Data pre-processing
# -------------------------------------------------------
# File path to retrieve
file_name = "/content/drive/.../EURUSD_M15_2023"
# If a pickle file exists, retrieve it
try:
data = pd.read_pickle(f"{file_name}.pkl")
# If a pickle file does not exist, retrieve the csv
except:
data = pd.read_table(f"{file_name}.csv", sep='\t')
# Change column names (Must include Open, High, Low, Close)
data = data.rename(columns={'<OPEN>': 'Open', '<HIGH>': 'High', '<LOW>': 'Low', '<CLOSE>': 'Close', '<VOL>': 'Volume'})
# Convert the date of the data to datetime type
data['datetime'] = pd.to_datetime(data['<DATE>']+ ' '+ data['<TIME>'])
# Specify datetime as the index
data = data.set_index('datetime')
# Save as a pkl file and store it in the drive
data.to_pickle(f"{file_name}.pkl")
# -------------------------------------------------------
# Logic Description
# -------------------------------------------------------
class Strategry(Strategy):
def init(self):
rsi_window = 14
upper_bound = 70
lower_bound = 30
close = pd.Series(self.data.Close)
self.daily_rsi = self.I(ta.rsi, close, self.rsi_window)
self.weekly_rsi = resample_apply('W-FRI', ta.rsi, pd.Series(self.data.Close), self.rsi_window)
def next(self):
if (crossover(self.daily_rsi, self.upper_bound) and
self.weekly_rsi[-1] > self.upper_bound):
self.position.close()
elif (crossover(self.lower_bound, self.daily_rsi) and
self.lower_bound > self.weekly_rsi[-1]):
self.buy()
It is divided into three parts: import, data preparation, and logic.
Executing the above code will result in the following error
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
Please let me know which part and how to correct it.