VALYNOXSTRATEGY RESEARCH TECHNOLOGY
AlphaPrimeAlphaPrime
ACADEMY / Strategy generation

Stock trading algorithms: how they work and how to test one

A stock algorithm is a fixed set of rules for buying, selling and holding. Most are trend, mean reversion or rebalancing rules. No single best one exists, so each must be tested with clean data and real costs, and on data it has never seen.

By · Published · updated · Editorial policy

Contents
  1. How does a stock trading algorithm work?
  2. What are the main types of stock algos?
  3. Which data problems are specific to stock backtests?
  4. What is survivorship bias in a stock backtest?
  5. How should a backtest handle splits and dividends?
  6. How much do costs and liquidity change a stock algorithm?
  7. Is there a best stock algorithm?
  8. How do you test a stock algorithm before trading it?
  9. Frequently asked questions
  10. References

A stock trading algorithm is a fixed set of rules that tells a computer when to buy, sell or hold a stock. Most belong to three families: trend following, mean reversion and rebalancing. No single best one exists: results depend on the market, the costs and the period, so every algorithm must be tested on data it has never seen.

How does a stock trading algorithm work?

Every stock algorithm turns price data into orders through the same short chain of steps. Think of it as a recipe. The same ingredients and the same steps give the same result every time, and the cook never gets tired or nervous.

  1. Data in. The algorithm reads bars. A bar is one period of trading summarized as open, high, low, close and volume, for example one day or five minutes.
  2. Signal. It calculates something from the bars, for example whether the 50-day moving average is above the 200-day moving average.
  3. Rule. It turns the signal into a decision: "If the signal is true at the close, buy at the next bar's open."
  4. Size and exit. It decides how many shares to buy, where the stop is, and what ends the trade.
  5. Order. It sends the order to the broker, or in a test, records a simulated fill.

A backtest is a run of these rules over historical data that reports the trades and the equity curve the rules would have produced. The order of steps matters. A rule that decides on the close and also fills at that same close uses a price you could not have traded. Filling on the next bar is the realistic default for rules that decide at the bar close.

What are the main types of stock algos?

Most stock algos are built on one of three ideas: follow the move, bet on a return to normal, or reset a portfolio on a schedule. Each one wins in different conditions and loses in a typical way.

Trend following is buying what is already rising (or selling what is falling) and holding while the move lasts. Mean reversion is the tendency of a price that moved far from its recent average to move back toward it. Rebalancing is resetting a portfolio to target weights, or to a new ranked list of stocks, at fixed dates.

ApproachExample ruleTypical holding timeUsual trade patternWhat hurts it
Trend followingBuy when the close makes a new 100-day high; exit on a new 50-day lowWeeks to monthsMany small losses, a few large winsSideways, choppy markets
Mean reversionBuy after a sharp short drop, for example when the RSI is very low in a stock above its long average; sell after a bounceDaysMany small wins, an occasional large lossSell-offs that keep going
RebalancingEach month, rank a stock list by six-month return and hold the top 20One rebalance period or longerResults come from the whole basket, not single tradesTurnover costs and a biased stock list
Three families of stock algorithms: trend following buys a breakout and sells much later, mean reversion buys a drop below the average and sells on the return to it, and rebalancing swaps stocks on fixed monthly dates Three families of stock algos Buy Sell Trend Ride the move Reversion Back to average Rebalance Reset each month
Three families of stock algorithms: ride the move, bet on the return to average, or reset the basket on fixed dates.

The trade pattern decides how the algorithm feels to trade. A trend system can lose ten times in a row and still be working as designed. A mean reversion system can win for months and then give back a large part in one trade. Know which pattern you are testing before you judge the result.

Which data problems are specific to stock backtests?

Stock data has three traps of its own: companies that disappeared, share splits and dividends. Each one can make a backtest look better or worse than the history you could actually have traded.

What is survivorship bias in a stock backtest?

Survivorship bias is the error of testing only on stocks that still exist today, so the companies that went bankrupt, were delisted or were bought out are missing from the test. A list of today's index members tested back over many years quietly contains only winners, because the losers were removed from the index along the way.

Hypothetical example

You test a "buy the biggest fallers" rule on the 100 stocks in an index today, going back ten years. Ten years ago the index had 100 different members, and 15 of them later collapsed and were removed. Your test never buys those 15, because they are not in today's list. The rule looks like it always buys the dip before a recovery, but only because the dips that never recovered are missing.

Survivorship bias: of ten index members at the start of the test, two failed and were replaced by newer stocks, so a test on today's list never trades the failed companies Today's list hides the failures Same index, ten years apart Start Today Survived Failed Added later The test never buys the losers. So: use the list as of each date.
A test built on today's stock list never trades the companies that failed, which makes the history look kinder than it was.

How should a backtest handle splits and dividends?

A 2-for-1 split doubles the number of shares and halves the price, without any change in the value of the company. Unadjusted data shows that as a 50% overnight drop, and a stop or a breakout rule will react to a move that never happened. Split-adjusted data divides the older prices by the split ratio, so the series is continuous.

On the ex-dividend date, the price usually drops by about the dividend amount. Dividend-adjusted data lowers all earlier prices so that this drop disappears and the series shows total return. A short seller also pays the dividend to the share lender, so a short trade held across that date costs more than the price chart shows.

ProblemWhat goes wrongWhat to check
Survivorship biasFailed companies are missing, so results look too goodThe stock list on each date in the test, including delisted stocks
SplitsFake price gaps trigger stops and signalsPrices adjusted for every split, and volume adjusted the same way
DividendsFake drops on ex-dates, or missing income on long tradesWhether your series is price-only or total return, and whether short trades pay dividends
Fixed price levelsA rule like "only stocks above $10" picks different stocks on adjusted and unadjusted dataApply price filters to the price that was actually quoted on that date

How much do costs and liquidity change a stock algorithm?

Costs often decide whether a stock algorithm keeps any edge, and liquidity decides how large those costs are. The spread is the gap between the best bid and the best ask price. Slippage is the difference between the price the backtest assumed and the price you would actually get. Liquidity is how much you can buy or sell without moving the price, and in stocks it is usually judged by the average traded value per day and by the width of the spread.

The simplest check fits in one line:

Net average trade = gross average trade − round-trip cost

The gross average trade is the average result per trade before any costs. The round-trip cost is everything you pay to enter and exit once: commission, half the spread on each side, and slippage on each side.

Hypothetical example

An algorithm trades 500 shares and its gross average trade is $0.06 per share, or $30 per trade. On a liquid large-cap stock with a 2-cent spread, half the spread costs $0.01 per share on each side, and slippage adds another $0.01 per side. That is $0.04 per share, or $20, plus $2 in commission: a $22 round trip. The net average trade is $8. The same rule on a small-cap stock with a 10-cent spread pays $0.05 per side for the spread alone, or $50 per trade, and the net average trade turns negative before slippage and commission are even counted.

Three liquidity habits make a stock test more realistic. Filter the stock list by average daily traded value, not by price. Keep your order size a small fraction of a stock's normal daily volume. Model wider slippage for trades at the open and in thin stocks. Rebalancing algorithms need one more number: turnover, the share of the portfolio replaced at each rebalance, because every replaced position pays a full round trip. For a full walk-through of commission and slippage settings, see trading costs in backtests.

Is there a best stock algorithm?

There is no best stock algorithm. Performance depends on conditions that change, and the "best" result from any search is inflated by the search itself.

The first reason is fit. A trend rule that suits large, slow-moving stocks can fail on volatile small caps. A mean reversion rule that works with low commissions can fail with higher ones. A rule that suits one account size can be too costly or too illiquid for another.

The second reason is selection. Imagine a hundred people each flipping a coin ten times. Someone will get eight or nine heads. That person is not a skilled flipper; the high score came from the number of people trying. Testing many algorithm variants and keeping the top one works the same way. The top backtest is partly skill and partly the luck of being the best among many tries.

Sullivan, Timmermann and White (1999) tested a large universe of technical trading rules and showed that the best rule must be judged against the whole search, not on its own. White (2000) described a "reality check" test for this kind of data snooping. Bailey, Borwein, López de Prado and Zhu (2014) showed how the best backtest from many trials tends to do worse out of sample. The Sharpe ratio is the average return divided by how much returns swing, a measure of return per unit of risk. Harvey and Liu (2015) proposed reducing a reported Sharpe ratio according to how many strategies were tried. The article on backtest overfitting research covers these ideas in more depth.

How do you test a stock algorithm before trading it?

Test a stock algorithm on data it has never seen, with real costs, before any money is at risk. Out-of-sample data is history that the rules and their parameters never saw while you were building them. In-sample data is the part you used to build and tune.

  1. Write the rules down completely before looking at results: stock list, entry, exit, position size and rebalance day.
  2. Prepare the data: the stock list as it was on each date, prices adjusted for splits, and one clear choice about dividends.
  3. Set aside out-of-sample data, for example the most recent part of the history, and do not look at it while tuning.
  4. Include costs and next-bar execution in every run, not only the final one.
  5. Run walk-forward analysis: tune on one window, test on the next, move forward and repeat. The method is explained in walk-forward analysis.
  6. Count your variants. Write down how many rule and parameter combinations you tried, and judge the winner against that number.
  7. Forward test. Run the final rules on live prices, without money or at very small size, to compare real fills with the backtest's assumed fills.
A timeline split into a long in-sample part for building and tuning and a shorter out-of-sample part for testing; over the out-of-sample part one equity line keeps rising and holds up, the other goes flat because it only fitted noise Does it hold up on new data? Two possible out-of-sample results Holds up Fitted noise In-sample Out-of-sample Only new data shows real skill. So: test once, after tuning ends.
Build and tune on the in-sample part, then test once on the out-of-sample part. The out-of-sample line shows whether the rules learned something or only fitted the past.

When you compare the two parts, look at these signs:

MeasureGood signBad sign
Net average trade out of sampleStill clearly above the round-trip costNear zero or below the cost
Number of out-of-sample tradesEnough trades to judge, not a handfulToo few trades to tell luck from skill
Nearby parameter settingsSimilar results when a setting moves a littleOnly one exact setting works
Maximum drawdownSimilar in size to the in-sample drawdownMuch deeper than anything in-sample
Walk-forward windowsMost windows behave in a similar wayOne or two lucky windows carry the total

Running these checks the same way for every candidate is what strategy validation is for: the same steps, the same thresholds, and walk-forward analysis applied to every algorithm, not only to the one you like most.

What this means if you use AlphaPrime (Valynox): AlphaPrime applies this testing discipline to futures bar data, so a stock-market idea such as a trend rule on an index future gets costs, next-bar execution and out-of-sample checks in every test. Survivorship and dividend questions belong to individual stocks; index futures bring their own data question, the contract roll.

Frequently asked questions

What is the best stock algorithm for beginners?

No single algorithm is best for everyone, because results depend on the stocks, the costs and the period. A good start is a simple rule with few parameters, such as a moving-average trend rule on liquid large caps. Test it with realistic costs and keep part of the history untouched for an out-of-sample check.

Can individual traders use algo trading for stocks?

Yes. Individual traders can write rules, backtest them on historical bars and run them through a broker or trading platform. Individuals usually compete on holding period and patience rather than speed, so daily or weekly rules with costs well below the average trade are the practical place to start.

What is survivorship bias in stock backtesting?

Survivorship bias is testing only on stocks that still exist today, leaving out companies that failed or were delisted. It makes a backtest look better than reality because the worst outcomes are missing. The fix is a stock list as it was on each date, including stocks that were later removed.

Should a stock backtest use split- and dividend-adjusted prices?

Split adjustment is needed for almost every stock test, because unadjusted splits look like large price gaps and trigger false signals. Dividend adjustment is a choice: total-return data includes dividend income, while price-only data shows the price drop on ex-dividend dates. Pick one and use it for the whole test.

How much data do you need to test a stock algorithm?

You need enough history to cover several market phases, such as rising, falling and sideways years. The out-of-sample part also needs enough trades to tell skill from luck. A fast rule may reach that in a few years, while a monthly rebalancing rule needs much longer history.

References

  • Sullivan, R., Timmermann, A., & White, H. (1999). Data-Snooping, Technical Trading Rule Performance, and the Bootstrap. The Journal of Finance, 54(5), 1647–1691.
  • White, H. (2000). A Reality Check for Data Snooping. Econometrica, 68(5), 1097–1126.
  • Bailey, D. H., Borwein, J., López de Prado, M., & Zhu, Q. J. (2014). Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance. Notices of the American Mathematical Society, 61(5), 458–471.
  • Harvey, C. R., & Liu, Y. (2015). Backtesting. The Journal of Portfolio Management, 42(1), 13–28.

What AlphaPrime does here

AlphaPrime's strategy generation turns trend and mean reversion ideas into testable rules, and its backtesting includes fees, slippage, next-bar execution and trading sessions in every evaluation. Strategy validation then applies walk-forward analysis and your own thresholds to every candidate.

See plans and pricing