Choosing a strategy per stock by backtesting in a Go paper trader
My golang paper trader backtests eight strategies on every NIFTY 50 stock each morning and only trades a stock if the winner made money over enough trades. Here is how the selection code works, and why a backtest winner proves very little.
Most strategy code I see online picks one strategy and runs it on every stock. I wanted to try something else in my paper trader: let each stock pick its own strategy every morning, based on how each one did on that stock's recent history. Then paper trade only the stocks where the pick looked sane.
Before anything else. This is a post about golang code, not investment advice. The trader only does paper trades, I am not telling anyone this approach makes money, and further down there is a whole section on why a backtest winner can be pure luck.
The code started as a separate repo called algotrader at the end of October and now lives in my algo-trade repo as a job. It uses Kite Connect for candles and Postgres for storing positions.
What happens every morning
Once a Kite access token is available (they expire daily, so I log in each morning), the engine does this for every symbol in data/nifty50.txt.
- Fetch the last
BACKTEST_DAYSof five minute candles. The default is 60 days. - Backtest every strategy in the panel over those candles.
- Keep the one with the highest PnL.
- Mark the stock tradable for the day only if that PnL is positive over at least
BACKTEST_MIN_TRADEStrades. Default 5.
The settings come from environment variables. This is the non-secret part of my dev.env.example.
export TRADE_MODE=paper
export PAPER_MONTHS=1
export UNIVERSE_FILE=data/nifty50.txt
export CAPITAL_PER_STOCK=2000
export CANDLE_INTERVAL=5minute
export BACKTEST_DAYS=60
export BACKTEST_MIN_TRADES=5
The selection is saved to Postgres with every strategy's result as JSON, so a restart in the middle of the day loads the saved picks and doesn't backtest everything again. There's also a /selections?date= endpoint to see what got picked and why.
The panel of strategies
There are eight. Each one is a name and a signal function.
var All = []Strategy{
{"ema_crossover", emaCrossover},
{"vwap_cross", vwapCross},
{"opening_range_breakout", openingRangeBreakout},
{"rsi_reversal", rsiReversal},
{"bollinger_reversion", bollingerReversion},
{"donchian_volume_breakout", donchianVolumeBreakout},
{"supertrend_flip", supertrendFlip},
{"macd_cross", macdCross},
}
Every one of them trade both ways. A signal can be long (buy first) or short (sell first and buy back). So the winner for a stock can turn out to be a short biased read of it.
There's one rule for all signal functions, written in a comment at the top of the file. A signal must fire only on the bar where the condition becomes true, like a cross or a break, never on every bar where it stays true. If ema_crossover returned Long for every bar where EMA9 is above EMA21, the live scan and the backtest would enter on different bars and the backtest would be testing something else.
The backtest uses the live exit rules
This was the main design decision. The backtest sizes positions the same way the engine does, and it calls the same exit function. At most one trade per stock per day, entries only between 09:30 and 14:30, square off at 15:15.
The exits in short. Book half at +1%. After that, close the rest at +1.5% or as soon as profit falls below +1%. At -1% run a recovery check, which needs at least 30 minutes left and two of four signs (momentum turning, RSI stretched, EMA9 and EMA21 still on our side, price near VWAP). If the check fails, close. Hard stop at -1.5%.
A strategy can look great with a "hold till close" exit and terrible with these scaled exits, or the other way round. Choosing under one set of exits and trading under another would make the selection close to meaningless. That's why both paths call exits.Evaluate.
Inside a bar the backtest doesn't know the order prices were hit. It assumes the worst: open, then the adverse extreme, then the favourable one, then close. A bar that touched both the stop and the target is counted as a stop.
Picking the winner
Here is the selection logic, cut out of backtest.SelectBest so it builds by itself. The real function first runs each strategy and then does exactly this sort.
package selectbest
import "sort"
type Result struct {
Strategy string `json:"strategy"`
Trades int `json:"trades"`
Wins int `json:"wins"`
PnL float64 `json:"pnl"`
WinRate float64 `json:"win_rate"`
}
// Pick sorts results best first and reports whether the best one is worth
// trading: at least minTrades trades and a positive total PnL.
func Pick(results []Result, minTrades int) ([]Result, bool) {
sort.SliceStable(results, func(a, b int) bool {
ea, eb := results[a].Trades >= minTrades, results[b].Trades >= minTrades
if ea != eb {
return ea
}
if results[a].PnL != results[b].PnL {
return results[a].PnL > results[b].PnL
}
return results[a].WinRate > results[b].WinRate
})
ok := len(results) > 0 && results[0].Trades >= minTrades && results[0].PnL > 0
return results, ok
}
The sort has three levels. Strategies with enough trades come first, no matter their PnL. Then higher PnL. Then higher win rate as a tie break.
The first level matters more than it looks. Without it, a strategy that traded twice in 60 days and got lucky both times would beat one that traded eleven times and made a small profit. Two trades is not evidence of anything, that's just luck.
A test with made up numbers shows both cases.
func TestPick(t *testing.T) {
results := []Result{
{Strategy: "rsi_reversal", Trades: 2, PnL: 900, WinRate: 1},
{Strategy: "ema_crossover", Trades: 11, PnL: 140, WinRate: 0.55},
{Strategy: "vwap_cross", Trades: 14, PnL: -60, WinRate: 0.43},
}
best, ok := Pick(results, 5)
if !ok || best[0].Strategy != "ema_crossover" {
t.Fatalf("best = %+v ok=%v", best[0], ok)
}
losers := []Result{
{Strategy: "macd_cross", Trades: 9, PnL: -35},
{Strategy: "supertrend_flip", Trades: 7, PnL: -120},
}
best, ok = Pick(losers, 5)
if ok {
t.Fatalf("a losing best should not be tradable: %+v", best[0])
}
t.Logf("best loser: %s", best[0].Strategy)
}
go test -v ./...
The second case is the one I care about most. When every strategy lost money on a stock, the code still records the least bad one, but ok is false and the stock is not traded that day. "Nothing worked here lately" is a perfectly good answer and the code is allowed to give it.
In the engine the result goes into a log line per symbol, something like this (numbers invented).
selection RELIANCE ema_crossover tradable=true trades=11 win=55% pnl=140.00
selection INFY macd_cross tradable=false trades=9 win=33% pnl=-35.00
strategy selection done: 1 of 2 symbols tradable today
Only paper, on purpose
The config loader refuses any other mode.
// Only the paper broker exists. Refuse anything else rather than
// silently paper trading under a "live" label.
if cfg.TradeMode != "paper" {
return Config{}, fmt.Errorf("TRADE_MODE=%q is not supported: only paper trading is implemented", cfg.TradeMode)
}
There is no live broker in this code at all. Fills are simulated at the last traded price. I still wanted the check, because the worst outcome is setting TRADE_MODE=live, seeing it start without complaint and believing real orders were going out. An error at startup is much better than a misleading label.
The paper window is also limited. It starts on the first trading day and lasts PAPER_MONTHS, one by default. After that no new positions open. The PnL endpoints report gross numbers, before brokerage and taxes, which on intraday trades of this size is not small.
Why the backtest winner can be meaningless
This is the important part, and I would rather over explain it.
Picking the best of eight strategies on the same 60 days you measured them on is a textbook way to overfit. If all eight had zero real edge, one of them would still come out on top just by noise, and on most stocks the top one would show a profit. The more strategies you add to the panel, the better the best one looks, and the less that means. And the rule of five trades helps a bit. It does not fix this.
Some other biases sit in this setup too.
- The universe is today's NIFTY 50. Stocks that dropped out of the index are not in the list, so history looks kinder than it was.
- Gross PnL ignores charges and slippage. A strategy with lots of small wins can flip to a loss once you add them.
- The fills in the backtest are at the exact target or stop level. Real limit orders don't always fill there.
- 60 days is one market mood. A trend following strategy that won in a trending month will look awful when things go sideways.
The honest test is forward. Pick for today using only data up to yesterday, then see how today goes, and repeat for weeks without touching the parameters. That is what the paper window is for. And even a good paper month is one sample. I am treating this whole thing as a way to learn golang and market plumbing, not as a money machine.
If you build something like this, log every day's full result JSON like I do with the selections table. Then you can check later whether the backtest winners actually did better than a random pick from the panel the next day. That comparison will tell you more than any single backtest number.