Certainly! Let's develop your trading strategy in a modular fashion as you outlined. We'll break it down into three main components:
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 with the core functionality: opening an initial order at a specified start time and closing it at a specified stop time using tick data. Once this core is functional, we can incrementally add more features.
1. config.py
This file will hold all the configurable parameters, making it easy to adjust the strategy without modifying the core code.
# config.py
# Trading Parameters
START_TIME = "01:15:00" # Strategy start time each day
STOP_TIME = "21:00:00" # Strategy stop time each day
DIRECTION = "BUY" # Initial order direction: 'BUY' or 'SELL'
INITIAL_LOTSIZE = 0.01 # Initial lot size
THRESHOLD_POINTS = -5000 # Loss threshold in points
MULTIPLIER = 5.0 # Lot size multiplier for reverse orders
MAX_LOOP_COUNT = 5 # Maximum number of reverse loops
# Data Parameters
DATA_FILE_PATH = "Excess_USTECH_2023.csv" # Path to your tick data CSV
TIMEZONE = "UTC" # Timezone of the data
# Backtrader Parameters
CEREBRO_RUN_STDSTAT = False # Disable standard statistics for simplicity
Explanation:
- Trading Parameters: These control the behavior of your trading strategy, such as when to start and stop trading each day, the initial order direction and size, loss thresholds, multipliers for increasing lot sizes, and the maximum number of loops.
- Data Parameters: Specify the path to your tick data and its timezone.
- Backtrader Parameters: Configure Backtrader's behavior; for now, we disable standard statistics for simplicity.
2. strategy.py
This file defines the trading strategy. For the initial version, we'll focus on opening an initial order at the start time and closing it at the stop time.
# strategy.py
import backtrader as bt
from datetime import datetime, time
import config
class CoreStrategy(bt.Strategy):
params = (
('start_time', config.START_TIME),
('stop_time', config.STOP_TIME),
('direction', config.DIRECTION),
('lotsize', config.INITIAL_LOTSIZE),
)
def __init__(self):
self.order = None
self.order_executed = False
self.start_time = datetime.strptime(self.p.start_time, "%H:%M:%S").time()
self.stop_time = datetime.strptime(self.p.stop_time, "%H:%M:%S").time()
def next(self):
current_time = self.datas[0].datetime.time(0)
# Check if current time is within trading window
if self.start_time <= current_time < self.stop_time:
if not self.order and not self.order_executed:
self.log(f"Opening initial {self.p.direction} order at {current_time}")
if self.p.direction == "BUY":
self.order = self.buy(size=self.p.lotsize)
elif self.p.direction == "SELL":
self.order = self.sell(size=self.p.lotsize)
else:
if self.order:
self.log(f"Closing order at {current_time}")
self.close() # Close the position
self.order = None
self.order_executed = False
def notify_order(self, order):
if order.status in [order.Completed]:
if order.isbuy():
self.log(f"BUY EXECUTED, Price: {order.executed.price}, Size: {order.executed.size}")
elif order.issell():
self.log(f"SELL EXECUTED, Price: {order.executed.price}, Size: {order.executed.size}")
self.order_executed = True
self.order = None
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log("Order Canceled/Margin/Rejected")
self.order = None
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.datetime(0)
print(f"{dt.isoformat()} - {txt}")
Explanation:
- Parameters: The strategy uses parameters from
config.py for flexibility.
- Initialization: Sets up variables to track orders and parse start/stop times.
next() Method: Called for each incoming data point (tick). It checks whether the current time is within the trading window:
- Opening Order: If within the trading window and no order is active, it opens an initial BUY or SELL order.
- Closing Order: If outside the trading window and there's an active order, it closes the position.
notify_order(): Handles order notifications, confirming executions or handling cancellations/rejections.
log(): A helper method for logging events with timestamps.
3. main.py
This script sets up the Backtrader environment, loads the tick data, and runs the backtest.
# main.py
import backtrader as bt
import config
from strategy import CoreStrategy
import pandas as pd
from datetime import datetime
import pytz
def load_tick_data(filepath):
# Load the tick data CSV
df = pd.read_csv(filepath)
# Convert 'Timestamp' to datetime and set as index
df['Timestamp'] = pd.to_datetime(df['Timestamp'], utc=True)
df = df.set_index('Timestamp')
# Rename columns to Backtrader's expected format
df.rename(columns={
'Bid': 'open',
'Bid': 'high',
'Bid': 'low',
'Bid': 'close',
'Bid': 'volume', # Assuming Bid represents the price; volume handling may require adjustment
}, inplace=True)
# Since tick data doesn't have OHLC, we'll treat each tick as a separate bar
# Create a minimal OHLCV dataframe
df['open'] = df['Bid']
df['high'] = df['Bid']
df['low'] = df['Bid']
df['close'] = df['Bid']
df['volume'] = 1 # Each tick is treated as a single volume unit
return df
if __name__ == '__main__':
cerebro = bt.Cerebro()
# Load data
tick_data = load_tick_data(config.DATA_FILE_PATH)
data = bt.feeds.PandasData(
dataname=tick_data,
timeframe=bt.TimeFrame.Ticks,
tz=pytz.timezone(config.TIMEZONE),
datetime='index',
open='open',
high='high',
low='low',
close='close',
volume='volume',
openinterest=-1
)
cerebro.adddata(data)
# Add strategy
cerebro.addstrategy(CoreStrategy)
# Set initial cash
cerebro.broker.setcash(100000.0)
# Set commission - assuming 0 for simplicity
cerebro.broker.setcommission(commission=0.0)
# Run backtest
print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
cerebro.run()
print("Ending Portfolio Value: %.2f" % cerebro.broker.getvalue())
# Plot results
cerebro.plot()
Explanation:
- Loading Tick Data:
load_tick_data(): Reads the tick data CSV, converts timestamps to datetime objects with timezone awareness, and prepares the data for Backtrader. Since Backtrader expects OHLCV (Open, High, Low, Close, Volume) data, and tick data only provides Bid and Ask prices, we treat each tick as a separate bar with identical Open, High, Low, and Close prices. Volume is set to 1 for each tick.
- Note: Depending on your specific needs, you might want to refine how you handle Bid and Ask prices or map them to OHLCV differently.
- Setting Up Backtrader:
bt.Cerebro(): Initializes the Backtrader engine.
- Data Feed: Adds the tick data to Cerebro using the
PandasData feed, specifying TimeFrame.Ticks to handle tick-level data.
- Strategy: Adds the
CoreStrategy defined in strategy.py.
- Broker Settings: Sets the initial portfolio value and commission. Adjust these as needed.
- Running the Backtest: Executes the strategy and prints the starting and ending portfolio values.
- Plotting: Generates a plot of the backtest results for visual inspection.
4. Handling Tick Data in Backtrader
Backtrader doesn't natively support tick-wise backtesting as it's primarily designed for time-based data (e.g., minutes, hours, days). However, you can simulate tick-level backtesting by treating each tick as a separate bar with TimeFrame.Ticks. Here are some considerations:
- Granularity: Be mindful that treating each tick as a bar can lead to high computational demands, especially with large datasets.
- Custom Data Feeds: For more complex tick data handling (like separate Bid and Ask), consider implementing a custom data feed. This allows for more accurate simulation of tick dynamics.
For now, the provided load_tick_data() function simplifies tick data into OHLCV format suitable for Backtrader. You can refine this as you add more features to your strategy.
5. Running the Strategy
- Directory Structure: Ensure your files are organized as follows:
your_project/
│
├── config.py
├── strategy.py
├── main.py
└── Excess_USTECH_2023.csv
- Install Dependencies:
Make sure you have the necessary Python packages installed. You can install them using pip:
pip install backtrader pandas pytz
- Execute the Backtest:
Run the main.py script:
python main.py
You should see output indicating when orders are opened and closed, along with the starting and ending portfolio values.
6. Next Steps
Once the core functionality is verified—opening an initial order at START_TIME and closing it at STOP_TIME—we can proceed to implement the more advanced features of your strategy, such as:
- Tracking Position Loss: Monitor the loss in points and trigger reverse stop orders when thresholds are breached.
- Reverse Stop Orders with Increased Lot Sizes: Implement logic to manage order sizing based on multipliers when loss thresholds are hit.
- Loop Control: Manage the maximum number of loops (
MAX_LOOP_COUNT) and reset the strategy appropriately.
Each of these features will be added incrementally, ensuring the strategy remains robust and maintainable.
Final Note: Backtrader is a powerful framework, but handling tick data can be resource-intensive. For larger datasets or more intricate tick-based strategies, consider optimizing data handling or exploring other frameworks better suited for high-frequency data.
Feel free to reach out with questions or for further assistance as you develop your strategy!