Custom Data Backtesting with Moving Average Crossovers and a Stop Loss
Summary
The document presents a bar-by-bar backtest using historical price data loaded from a CSV file. As each bar is added, the strategy calculates 20-period and 30-period moving averages after sufficient history is available. It enters a long position when the shorter average crosses above the longer one, and exits when it crosses below, using the current bar's closing price for the simulated trades.
The example also applies a stop loss at 90% of the average entry price, checking whether the current bar's low reaches that level. Position size is based on the stated starting capital divided by the entry price, and realized profit updates the asset value. The document provides implementation mechanics, not performance evidence: it reports no returns, costs, slippage, or comparison benchmark. Its same-bar close execution assumptions and simple capital accounting limit how well the example represents live trading.
Key ideas
- Historical bars are fed incrementally into the backtest before the strategy evaluates each bar.
- A long position opens when the 20-period moving average crosses above the 30-period average.
- The strategy exits on a downward crossover or when the bar low reaches the stop threshold.
- Position size uses available capital divided by the closing price, with profits added to asset value.
- The example does not account for transaction costs, slippage, or reported strategy performance.
Tags
From a private course collection; the original is not published.