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 :
classMACDStrategy: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)defapply_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 inrange(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 shortif previous_macd <= previous_signal and macd > signal: price = data['Close'][i]# If in a short position, cover itif 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)
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:
macd_strategy.apply_strategy()
Full implementation example:
from marketquant.strategy_simulator import TradingEngine
from strategies.macd_strategy import MACDStrategy
def main():
# User Note: Initialize the trading core with your params for data_provider, ticker, start_date, end_date,
# candle_aggregation, starting_balance, and shares below.
engine = TradingEngine(
="yahoo",
="SPY",
="2023-01-01",
="2024-08-01",
="1d",
=100000,
=100,
=False,
=True,
=True,
=True,
=True,
=True,
=True
)
# User Note: Initializes the MACD strategy with the trading engine and MACD parameters
macd_strategy = MACDStrategy(engine, macd_params={
"short_period": 12,
"long_period": 26,
"signal_period": 9
})
macd_strategy.apply_strategy()
# Example: This prints the results of the enabled outputs
engine.print_results()
if __name__ == "__main__":
main()