Understood! Let's proceed step by step to implement the simplified version of your trading strategy using Backtrader, focusing on handling your tick data and the core functionality of opening and closing positions at specific times.
Below is the modular structure:
config.py: Contains all the configurable parameters.
strategy.py: Defines the trading strategy based on your specifications.
main.py: Sets up the Backtrader environment, loads the data, and runs the backtest.
We'll start by handling your tick data from "Excess_USTECH_2023.csv" and ensure it is correctly integrated with Backtrader.
1. config.py
Let's define the configurable parameters.
# config.py
import datetime
# Trading parameters
START_TIME = datetime.time(1, 15) # Start trading at 01:15
STOP_TIME = datetime.time(21, 0) # Stop trading at 21:00
DIRECTION = 'BUY' # Initial order direction ('BUY' or 'SELL')
LOT_SIZE = 0.01 # Initial lot size
# Data parameters
DATA_FILE = 'Excess_USTECH_2023.csv' # Path to your tick data CSV file
# Backtrader parameters
CASH = 100000 # Starting cash
COMMISSION = 0.0 # Commission per trade
2. strategy.py
Here's the simplified strategy:
- At
START_TIME, open a market order in the specified DIRECTION with LOT_SIZE.
- At
STOP_TIME, close all positions and cancel all pending orders.
- Repeat this process each day.
# strategy.py
import backtrader as bt
import datetime
class SimpleIntradayStrategy(bt.Strategy):
params = (
('start_time', datetime.time(1, 15)),
('stop_time', datetime.time(21, 0)),
('direction', 'BUY'),
('lot_size', 0.01),
)
def __init__(self):
self.order = None
self.datadate = None
def next(self):
# Get the current datetime
dt = self.datas[0].datetime.time(0)
date = self.datas[0].datetime.date(0)
# If a new day starts
if self.datadate != date:
self.datadate = date
self.order_placed = False
self.order_closed = False
# Open position at START_TIME
if dt >= self.p.start_time and not self.order_placed:
if self.p.direction.upper() == 'BUY':
self.order = self.buy(size=self.p.lot_size)
elif self.p.direction.upper() == 'SELL':
self.order = self.sell(size=self.p.lot_size)
self.order_placed = True
self.log(f'Order placed at {dt}')
# Close positions at STOP_TIME
if dt >= self.p.stop_time and self.order_placed and not self.order_closed:
if self.position.size != 0:
self.close()
self.log(f'Position closed at {dt}')
self.order_closed = True
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.datetime(0)
print(f'{dt.isoformat()} - {txt}')
3. main.py
In the main script, we'll set up the Cerebro engine, load your tick data from the CSV file, and run the backtest.
# main.py
import backtrader as bt
from config import START_TIME, STOP_TIME, DIRECTION, LOT_SIZE, DATA_FILE, CASH, COMMISSION
from strategy import SimpleIntradayStrategy
import pytz
import datetime
def run_backtest():
cerebro = bt.Cerebro()
cerebro.broker.setcash(CASH)
cerebro.broker.setcommission(commission=COMMISSION)
# Add the strategy
cerebro.addstrategy(
SimpleIntradayStrategy,
start_time=START_TIME,
stop_time=STOP_TIME,
direction=DIRECTION,
lot_size=LOT_SIZE,
)
# Define a custom data feed to handle your tick data
data = bt.feeds.GenericCSVData(
dataname=DATA_FILE,
dtformat='%Y-%m-%d %H:%M:%S.%f',
tmformat='%H:%M:%S.%f',
datetime=2, # Position of 'Timestamp' in the CSV
time=-1,
high=-1,
low=-1,
open=-1,
close=3, # We'll use 'Bid' as the price
volume=-1,
openinterest=-1,
separator=',',
headers=True,
fromdate=datetime.datetime(2023, 1, 1),
todate=datetime.datetime(2023, 12, 31),
sessionstart=START_TIME,
sessionend=STOP_TIME,
)
cerebro.adddata(data)
# Run the backtest
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Ending Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Plot the result (optional)
# cerebro.plot()
if __name__ == '__main__':
run_backtest()
Handling the Tick Data CSV File
Your CSV file has the following format:
"Exness","Symbol","Timestamp","Bid","Ask"
"exness","USTEC","2023-01-02 23:30:20.051Z",10967.58,10970.14
"exness","USTEC","2023-01-02 23:30:22.096Z",10967.28,10969.9
To ensure that Backtrader can read this file, we need to adjust the CSV format slightly. Here's what we need to do:
- Remove the first two columns:
"Exness" and "Symbol" are not required.
- Adjust the header row: Modify the header to match Backtrader's expectations.
- Format the timestamp correctly: Ensure the timestamp is in a format that Backtrader can parse.
Preprocessing the CSV File
Since Backtrader expects certain headers and data formats, we'll need to preprocess the CSV file before using it. Here's how you can do it:
import pandas as pd
def preprocess_csv(input_file, output_file):
df = pd.read_csv(input_file)
# Remove unnecessary columns
df = df[['Timestamp', 'Bid', 'Ask']]
# Rename columns to match Backtrader's expected names
df.rename(columns={'Timestamp': 'datetime', 'Bid': 'close'}, inplace=True)
# Remove the 'Z' at the end of the timestamp and parse datetime
df['datetime'] = df['datetime'].str.replace('Z', '')
df['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%d %H:%M:%S.%f')
# Sort by datetime in case it's not sorted
df = df.sort_values('datetime')
# Save to a new CSV file without the index
df.to_csv(output_file, index=False)
# Preprocess the CSV file
preprocess_csv('Excess_USTECH_2023.csv', 'processed_tick_data.csv')
After preprocessing, your CSV file (processed_tick_data.csv) will look like:
datetime,close
2023-01-02 23:30:20.051,10967.58
2023-01-02 23:30:22.096,10967.28
...
Make sure to run this preprocessing step before running the backtest.
Updating main.py to Use the Processed CSV File
In the main.py, update DATA_FILE to point to processed_tick_data.csv:
# main.py
# ...
def run_backtest():
# ...
data = bt.feeds.GenericCSVData(
dataname='processed_tick_data.csv',
dtformat='%Y-%m-%d %H:%M:%S.%f',
datetime=0, # 'datetime' column index after preprocessing
time=-1,
open=-1,
high=-1,
low=-1,
close=1, # 'close' column index after preprocessing
volume=-1,
openinterest=-1,
separator=',',
headers=True,
fromdate=datetime.datetime(2023, 1, 1),
todate=datetime.datetime(2023, 12, 31),
sessionstart=START_TIME,
sessionend=STOP_TIME,
)
# ...
Putting It All Together
Now, you have:
config.py: Contains all your parameters.
strategy.py: Implements the simplified strategy.
main.py: Loads your tick data and runs the backtest.
Make sure to preprocess your CSV file before running the backtest.
Testing the Core Functionality
With the simplified strategy and properly formatted tick data, you can now run main.py to test the core functionality.
Next Steps
Once you have verified that:
- The initial order is placed at
START_TIME.
- All positions are closed at
STOP_TIME.
- The strategy repeats this process daily.
We can proceed to add the additional features step by step, such as:
- Tracking position loss.
- Opening reverse stop orders when the loss threshold is reached.
- Implementing the loop with increased lot sizes.
Feel free to let me know when you're ready to proceed with these enhancements!
Notes
- Timezones: Ensure that the timestamps in your tick data and the
START_TIME/STOP_TIME are in the same timezone. If your data is in UTC, you might need to adjust the times accordingly.
- Performance: Handling tick data can be resource-intensive. Ensure your system has enough memory to process the data.
- Backtrader's Limitations: Backtrader processes data in chronological order. If the timestamps in your tick data are not sequential, you may encounter issues.
Let me know if you have any questions or need further assistance!