πTrade Simulation Example
Below you will find how to set up a strategy using an example foun in the demo_examples folder.
Strategy Setup w/ Example Strategy
Once the TradingEngine is initialized, you can apply a trading strategy to it. In this example, we use a MACDStrategy to simulate trades based on the Moving Average Convergence Divergence (MACD) indicator.
Code for the MACDstrategy, located in demo_examples/strategies :
class MACDStrategy:
def __init__(self, trading_engine, macd_params=None):
self.trading_engine = trading_engine
self.macd_params = macd_params if macd_params else {}
self.macd_indicator = MACDIndicator(**self.macd_params)
def apply_strategy(self):
# Fetches data from the engine
data = self.trading_engine.data_engine.fetch_data()
# Calculates the MACD and signal using the indicator class
data = self.macd_indicator.calculate(data)
for i in range(1, len(data)):
date = data['Date'][i]
macd = data['MACD'][i]
signal = data['Signal'][i]
previous_macd = data['MACD'][i - 1]
previous_signal = data['Signal'][i - 1]
# Checks for cover signal (MACD crosses above signal line) to close the short
if previous_macd <= previous_signal and macd > signal:
price = data['Close'][i]
# If in a short position, cover it
if self.trading_engine.simulator.account_manager.positions.get('long', {}).get('quantity', 0) > 0:
self.trading_engine.simulator.sell(date, price, self.trading_engine.shares)
# Checks for short signal (MACD crosses below signal line)
elif previous_macd >= previous_signal and macd < signal:
price = data['Close'][i]
# Short the stock
self.trading_engine.simulator.buy(date, price, self.trading_engine.shares)MACD Strategy Constructor Arguments:
Argument
Type
Description
engine
TradingEngine
The initialized trading engine instance.
macd_params
dict
Dictionary containing the MACD parameters:
- short_period
int
The short-period EMA (typically 12 periods).
- long_period
int
The long-period EMA (typically 26 periods).
- signal_period
int
The signal line period (typically 9 periods).
Example Usage:
This sets up the MACD strategy using the specified MACD parameters and links it to the previously initialized TradingEngine.
Applying the Strategy:
To apply the strategy, you need to add the following command to your script:
Full implementation example:
Last updated