Trade Simulation

TradeEngine()

Reference for the trade/strategy simulation tool. To import:

from marketquant.strategysimulator import TradeEngine

Trade Simulation Setup and Trade Engine Initialization

The core class of the simulation is TradingEngine. This is responsible for initializing the simulation parameters such as data provider, ticker symbol, date ranges, candle aggregation, balance, and shares.

TradingEngine Constructor Arguments:

Argument

Type

Description

Default

data_provider

str

The data provider to be used for fetching historical stock data (e.g., yahoo, schwab).

yahoo

ticker

str

The stock ticker to simulate trades on (e.g., AAPL, SPY).

AAPL

start_date

str

The starting date of the trade simulation in YYYY-MM-DD format.

"2023-01-01"

end_date

str

The end date of the simulation in YYYY-MM-DD format.

"2024-08-01"

candle_aggregation

str

The time interval for stock candles (1d, 1h, etc.).

"1d"

starting_balance

float

The initial capital (cash balance) available for the trading simulation.

100000

shares

int

The number of shares to be traded per buy/sell order.

10

print_tradehistory

bool

Whether to print the trade history at the end of the simulation.

False

print_pnl

bool

Whether to print the profit and loss (P&L) summary at the end.

True

print_balance

bool

Whether to print the account balance (buy, sell, short, cover).

True

print_buypower

bool

Whether to print the remaining buying power (cash available). This is useful to see your buying power at the end if you are still in a trade with an unrealized return.

True

print_unrealizedpnl

bool

Whether to print unrealized profit and loss during open positions after strategy has been ran.

True

print_timecomplexity

bool

Whether to print the time complexity of the input data during execution.

True

chart

bool

Whether to display a chart of stock prices and the trading strategy execution (e.g., buy/sell markers, profit/loss chart).

True

Example TradeEngine Setup:

from marketquant.strategy_simulator import TradingEngine

engine = TradingEngine(
    data_provider="yahoo",
    ticker="SPY",
    start_date="2023-01-01",
    end_date="2024-08-01",
    candle_aggregation="1d",
    starting_balance=100000,
    shares=100,
    print_tradehistory=False,
    print_pnl=True,
    print_balance=True,
    print_buypower=True,
    print_unrealizedpnl=True,
    print_timecomplexity=True,
    chart=True
)


Placing Trades and Managing Positions

In the trade simulation engine, managing positions is critical for executing your trading strategy. The TradingEngine uses an internal AccountManager to handle all trade-related actions. You can initiate or close positions by using predefined methods such as buy(), sell(), short(), and cover(). These methods allow you to manage both long and short positions dynamically during your strategy execution.

Below is a detailed guide on how to place trades and manage positions.


Managing Trades

The following methods are crucial for managing positions within a strategy. Each method can be called when certain market conditions or indicators (like MACD, RSI, etc.) meet specific criteria.

1. buy(date, price, shares)

  • Action: Initiates or adds to a long position by buying shares.

  • Usage: Use this when your strategy indicates a buy signal, such as a bullish crossover of a technical indicator.

  • Parameters:

    • date (str): The date of the trade.

    • price (float): The price at which the shares are being bought.

    • shares (int): The number of shares to purchase.

Example:

pythonCopy code# Buy signal detected in strategy
if macd > signal:
    price = data['Close'][i]
    self.trading_engine.simulator.buy(date, price, self.trading_engine.shares)


2. sell(date, price, shares)

  • Action: Closes a long position by selling previously purchased shares.

  • Usage: Use this when your strategy indicates a sell signal, such as a bearish crossover.

  • Parameters:

    • date (str): The date of the trade.

    • price (float): The price at which the shares are being sold.

    • shares (int): The number of shares to sell.

Example:

# Sell signal detected in strategy
if macd < signal:
    price = data['Close'][i]
    self.trading_engine.simulator.sell(date, price, self.trading_engine.shares)


3. short(date, price, shares)

  • Action: Initiates or adds to a short position by borrowing and selling shares.

  • Usage: Use this when your strategy indicates a short signal, such as when you anticipate the stock price will drop.

  • Parameters:

    • date (str): The date of the trade.

    • price (float): The price at which the shares are being shorted.

    • shares (int): The number of shares to short.

Example:

# Short signal detected in strategy
if macd < signal:
    price = data['Close'][i]
    self.trading_engine.simulator.short(date, price, self.trading_engine.shares)


4. cover(date, price, shares)

  • Action: Closes a short position by buying back previously shorted shares.

  • Usage: Use this when your strategy indicates the stock price is likely to increase, and you need to close the short position to lock in profits or avoid further losses.

  • Parameters:

    • date (str): The date of the trade.

    • price (float): The price at which the shares are being bought back to cover the short.

    • shares (int): The number of shares to cover.

Example:

# Cover signal detected in strategy
if macd > signal:
    price = data['Close'][i]
    self.trading_engine.simulator.cover(date, price, self.trading_engine.shares)

General Flow of a Strategy Using These Methods

In most strategies, these trade management methods are triggered based on conditions determined by technical indicators or price action. Here's a typical flow:

  1. Indicator Calculation: Indicators like MACD, RSI, or moving averages are calculated.

  2. Condition Evaluation: If the indicator meets the criteria (e.g., MACD crosses above the signal), the strategy calls the relevant trade method.

  3. Executing the Trade: Depending on the conditions, the buy(), sell(), short(), or cover() the method is executed, and the position is adjusted accordingly.

  4. Position Management: The AccountManager tracks the position, P&L, and buying power.


Additional Notes:

  • You can call these methods multiple times to scale positions or gradually close positions.

  • It's important to track the current position to avoid over-exposing your account to risk.

  • Position Tracking: Each method updates the positions attribute within the AccountManager, allowing you to track the status of each trade and the overall portfolio.

By understanding and utilizing these trade management methods, you can effectively simulate real-world trading strategies and optimize performance.


Use Case Notes

Users are not limited to the tools within the library. You may use any strategy where you can systematically define a buy/sell or short/cover strategy. The indicators and strategies demo_examples are demos and aren't meant for real use, nor should they be used in the real world. This tool gives you the ability to simulate and backtest strategies.

Last updated