📘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:

from strategies.macd_strategy import MACDStrategy

macd_strategy = MACDStrategy(
    engine=engine,
    macd_params={
        "short_period": 12,
        "long_period": 26,
        "signal_period": 9
    }
)

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()

Last updated