Skip to content
All library documents

Backtesting a Moving Average Crossover with a Fixed Date Range and Stop Loss

Code Quant course library

Summary

This example demonstrates a historical equity backtest over a user-specified date interval. It processes daily bars incrementally, waits until enough history is available, and enters a long position when the 20-period moving average crosses above the 30-period average. A downward crossover closes the position. The example also exits if the bar’s low reaches a stop threshold set at 10% below the average entry price, using that threshold as the modeled sale price.

Position size is based on allocating the stated initial capital to the purchase, and realized trade profit is added back to capital after an exit. The script plots the resulting capital curve. These mechanics illustrate date filtering, bar-by-bar simulation, signal generation, and a simple protective exit, but the document reports no performance results. It does not account for commissions, slippage, partial fills, or broader portfolio constraints, and its use of closing prices for crossover trades and simplified stop execution may not reflect live fills.

Key ideas

  • The historical data request can be restricted to explicit start and end dates.
  • The strategy enters long when the shorter moving average crosses above the longer one and exits on the reverse crossover.
  • The example sizes an entry using the available stated capital and updates capital with realized profit or loss.
  • A stop exit is triggered when the bar low reaches a threshold 10% below the average entry price.
  • The code illustrates mechanics but supplies no performance evidence or transaction cost modeling.

Tags

From a private course collection; the original is not published.