The Āagman Backtesting Playbook
A practical guide to testing trading and investment strategies with natural language in Āagman.
“If I had traded this exact rule set in the past, what would have happened?”
1. The mental model
Backtesting answers the question above. In Āagman, you write the rule set in plain English. Āagman parses your words into a structured plan, fetches historical prices, runs the simulation bar by bar, and shows you the outcome.
What happens under the hood
You type a prompt — e.g. "Buy RELIANCE when EMA(20) crosses above EMA(50)"
Āagman parses the prompt into an internal plan: symbols, indicators, entry rules, exit rules, sizing, dates
Āagman loads market data from NSE/BSE historical records
The simulation runs bar by bar, applying your rules at the close and filling at the next open
You get a report: metrics, equity curve, and trade table
Key assumption: next-bar execution
Āagman evaluates conditions at the close of a bar and executes at the open of the next bar. This prevents look-ahead bias — the simulator never uses future information to make a decision.
A caution on what backtests can and can't tell you
A good backtest is a hypothesis test, not a prediction. Even a strong result overstates likely live performance for four reasons:
The more knobs you tune to make history look good, the less the rules describe a real edge.
The market conditions that produced past returns may not repeat.
Live fills, slippage, and liquidity rarely match the simulator's assumptions.
The stocks in today's index aren't the ones that were in it ten years ago.
Treat every backtest as one piece of evidence. Confidence comes from testing across symbols, periods, and market regimes — not from optimizing a single result.
2. How do I run my first backtest?
Open the chat, describe your strategy in plain English, and ask Āagman to backtest it. The agent replays years of market data and returns performance metrics.
Paste this into a new backtest workspace.
You'll see a strategy card summarizing the rules, a Run Risk Checks button, and a Run Backtest button. Click Run Risk Checks, then Run Backtest. After a few seconds you'll see the total return, max drawdown, win rate, number of trades, an equity curve, and a trade table.
What to notice
The strategy only takes trades when the fast EMA crosses the slow EMA. It's a simple trend-following idea. If RELIANCE trended strongly during 2024, the equity curve slopes up. If it chopped sideways, the strategy loses money to whipsaws.
A rule that sounds good in theory can fail in a specific market regime.
The prompt above has five ingredients — instrument, timeframe, date range, entry rule, exit rule — plus a few optional extras. Section 3 breaks each one down so you can build your own.
3. What makes a good backtest prompt?
A good prompt names the instrument, entry condition, exit rule, position size, and time period you want to test.
Every working prompt contains five pieces of information. Master these and you can describe almost any strategy.
Structured or free-form is fine. Āagman accepts both. You can label sections (Entry:, Exit:, Position sizing:) or write a single sentence ("Buy HDFCBANK when close crosses above the 20-day high, daily, Jan to Dec 2024"). Structured prompts are easier to review and share; free-form prompts are quicker to try.
3.1 The instrument
What are you trading?
- Single stock: RELIANCE, HDFCBANK, INFY
- Index: NIFTY, BANKNIFTY
- Basket: top 10 NIFTY 50 stocks
- Mutual fund: SBI Bluechip Fund
- Options underlying: NIFTY, BANKNIFTY, RELIANCE
- Commodity: GOLD, CRUDEOIL
3.2 The timeframe
How often does the strategy check for signals? 1m, 5m, 15m for intraday, 1h for hourly, 1d for daily (most common for beginners).
Only one timeframe per backtest.
3.3 The date range
- Explicit: from 1 January 2024 to 31 December 2024
- Relative: last 1 year, last 3 years
- Default: last 1 year for equities, last 6 months for options
Explicit dates make it easier to share results — a "last 1 year" backtest run today doesn't mean the same thing as one run next month.
3.4 The entry rule
When do you enter a position?
| Pattern | Example |
|---|---|
| Crossover | EMA(20) crosses above EMA(50) |
| Threshold | RSI(14) crosses above 30 |
| Breakout | close crosses above 20-day high |
| Confluence | RSI(14) > 50 AND close > SMA(200) |
| Candlestick | bullish hammer detected |
3.5 The exit rule
When do you close the position? Exit mechanics matter enough to get their own section — see §4 Designing exits. For now, a quick reference:
| Exit type | Example |
|---|---|
| Stop loss | stop loss at 2% below entry |
| Take profit | take profit at 6% above entry |
| Trailing stop | trailing stop at 2% below highest price since entry |
| Time stop | exit after 10 bars |
| Indicator exit | exit when RSI(14) crosses below 70 |
| No explicit exit | hold until the end of the backtest |
3.6 Optional but important
- Starting capital: Starting capital ₹10,00,000
- Position sizing: Buy 50 shares, or Use 10% of capital per trade, or 1 lot
- Fees and slippage: Fees 5 bps, slippage 3 bps
- Direction: long-only, short-only, long and short
Most examples in this guide use Fees 5 bps, slippage 3 bps — reasonable approximations for retail equity trading at typical discount brokers on liquid names. Trading illiquid stocks? Adjust slippage up (10–20 bps). Zero-brokerage plan? Reduce fees. For options, override both — bid-ask spreads and STT dominate the cost picture there.
4. How do I design exits?
Exits can be profit targets, stop losses, trailing stops, time-based exits, or indicator reversals — whatever matches your risk plan.
Exits decide whether a strategy makes money. A good entry with a bad exit loses; a mediocre entry with a good exit can survive. Āagman supports several exit types, and they can be combined.
4.1 Fixed stop loss and take profit
Simple and predictable. The main downside: a fixed take-profit caps your winners. If the trend runs for 20%, you still exit at 4.5%.
4.2 Trailing stop
A trailing stop lets winners run while protecting profits. Usually better than a fixed stop for trend-following strategies. The trade-off: you give back some open profit on every trade.
4.3 Time stop
Useful for event-driven or mean-reversion trades where you don't want to hold indefinitely. Also useful as a sanity check: if your strategy loses money with a time stop, the entry itself may have no edge.
4.4 Indicator exit
Exit when the condition that got you in reverses. Cleanest for mean-reversion.
4.5 Combined exits
Exits on whichever condition happens first: time stop, indicator exit, or stop loss. Combining exits is often the practical middle ground — you get protection against runaway losses (stop), reward-taking (indicator), and a fallback for stalled trades (time).
4.6 Choosing an exit type
- Trend-following strategy: trailing stop
- Mean-reversion strategy: indicator exit or fixed take-profit
- Options premium selling: premium-based SL (see §6)
- Event or news play: time stop
- When in doubt: fixed SL/TP first, iterate later
5. Pattern library: equity strategies
The following patterns are the building blocks of most equity backtests. Each pattern gets a concept, an example prompt, variations to try, and a common failure mode.
Trend following with moving averages
Concept. Buy when a short-term trend indicator turns up relative to a long-term trend indicator. Sell when it turns down.
Why it works (sometimes). Moving averages smooth out noise. When price is above a rising long-term average, the trend is up. The crossover captures the middle of a trend, not the exact bottom or top.
Base example
Variations to try
- Change the EMA periods: EMA(9) crosses above EMA(21) for faster signals
- Use SMA instead of EMA: SMA(50) crosses above SMA(200) for slower, cleaner signals
- Add a trend filter: only enter when close > SMA(200)
- Add ADX: only enter when ADX(14) > 25
In sideways markets, crossovers generate many false signals (whipsaw). Adding a trend filter or ADX filter reduces whipsaws but also delays entries.
Mean reversion with RSI
Concept. Buy when an asset becomes oversold and is expected to bounce back. Sell when it becomes overbought.
Why it works (sometimes). In range-bound markets, extreme RSI readings often precede a partial reversal. The SMA(200) filter ensures you only take oversold bounces in an overall uptrend, which cuts down the worst losers.
Base example
Variations to try
- Use RSI(21) for smoother signals
- Combine with Bollinger Bands: close crosses above lower Bollinger Band AND RSI(14) < 40
- Short the overbought side: RSI(14) crosses below 70 AND close < EMA(50)
Mean reversion fails disastrously in strong trends. A stock can stay oversold for months. The SMA(200) filter helps but doesn't eliminate the risk.
Momentum with MACD
Concept. Buy when momentum is accelerating. MACD measures the difference between two EMAs; when the MACD line crosses above its signal line, momentum is turning up.
Why it works (sometimes). MACD combines trend (the EMA difference) with a short-term signal filter (the signal-line crossover). This catches trend inflections earlier than a plain moving-average crossover, at the cost of more false signals.
Base example
Variations to try
- Require the MACD histogram to be positive: adds confirmation
- Use MACD line crosses above zero instead of the signal line
- Exit on MACD bearish crossover instead of fixed SL/TP
MACD in choppy markets is worse than useless — it fires constantly. Always pair with a trend filter or ADX threshold.
Breakout trading
Concept. Buy when price breaks above a previous resistance level. The N-day high is a simple proxy for resistance.
Why it works (sometimes). Prices that break to new highs attract stop-loss buying and trend-follower demand. When it works, the move can be sharp and self-reinforcing.
How Āagman handles it. When you say "20-day high," the engine uses MAX(high, 20) shifted by one bar. This matters: without the shift, today's close can never be greater than today's high, so the condition would never trigger.
Base example
Variations to try
- Add volume confirmation: volume > 1.5 * SMA(volume, 20)
- Use 52-week high for longer-term breakouts
- Short breakouts: close crosses below 20-day low
Breakouts often fail immediately. The classic "false breakout" traps traders. A stop loss is essential.
Candlestick patterns
Concept. Use price-pattern recognition to identify potential reversals. Āagman supports all 61 TA-Lib candlestick patterns, including hammer, engulfing, doji, morning star, and evening star.
Why it works (sometimes). Some candlestick patterns encode information about the day's supply-demand battle — where price opened, where it closed, how far it ranged. At key levels, these patterns can precede reversals. On their own, they don't have much edge.
Base example
Variations to try
- Use CDLENGULFING for stronger reversal signals
- Require the pattern at support: close near lower Bollinger Band
- Short version: CDLENGULFING bearish AND RSI > 55
Candlestick patterns are rare and context-dependent. They work better with a trend filter and often produce too few trades to be statistically meaningful.
Short strategies
Concept. The same logic in reverse. You profit when price falls.
Why it works (sometimes). Short strategies exploit asymmetric risk: markets fall faster than they rise. In bearish regimes or on weak individual names, short signals can produce sharp gains.
Base example
Variations to try
- Short overbought bounces: RSI crosses below 70 AND close < EMA(50)
- Short bearish engulfing patterns
- Use BOTH direction to allow the strategy to flip long/short on the same symbol
Long secular uptrends punish short strategies for years. Short-only equity strategies are especially fragile in indices dominated by growth names.
In Āagman backtests, shorting equities is simulated with CNC semantics. MIS/NRML product types are coerced to CNC.
Advanced composable rules
Recent updates unlocked several advanced features.
z-score
The z-score tells you how far an indicator is from its recent average, in standard deviations.
Arithmetic exits
This creates a dynamic stop loss that moves with the EMA.
Time-based entry
Indicator chaining
This smooths the RSI itself before using it as a signal.
6. Pattern library: options strategies
Options backtests are lot-based. Āagman resolves strikes, expiries, Greeks, and IV rank from historical option-chain data.
Several of the patterns below (short straddle, short strangle, naked short put) involve undefined or high risk. Backtests almost always understate this risk because the worst historical moves may not be in your date range, and because real fills during gap opens differ sharply from simulator prices. Size conservatively.
Short straddle
Concept. Sell an ATM call and an ATM put. Profit if the underlying stays near the strike. Lose if it moves a lot.
Why it works (sometimes). Options premium is generally overpriced relative to actual realised volatility (the "variance risk premium"). Selling premium collects this spread. Entering when IV is elevated improves the odds because implied and realised converge.
Base example
What to look for. Short straddles work in low-volatility, range-bound markets. High VIX entry helps because you collect more premium.
One large-move event (earnings, policy surprise, geopolitical shock) can wipe out months of profits. Short straddles are the classic "picking up nickels in front of a steamroller" trade. Never run one without a hard stop or wing protection (see iron condor, §6.3).
Short strangle
Concept. Sell an OTM call and an OTM put. Wider breakeven than a straddle, but lower premium.
Why it works (sometimes). Same variance-risk premium as the straddle, with a wider profit zone at the cost of smaller credit. The delta cushion means small-to-medium moves don't hurt.
Same as the short straddle — undefined risk on both wings. The wider strikes lull traders into oversizing, which magnifies gap-day losses.
Iron condor
Concept. Sell a call spread and a put spread. Defined risk, defined reward. Popular for income generation.
Why it works (sometimes). Combines the premium-selling edge of a strangle with the tail protection of long wings. Max loss is known and capped, which allows honest position sizing.
Iron condors look good in backtests dominated by range-bound periods. In trending or high-volatility regimes, the tested strike deltas may breach frequently. Test across multiple market regimes before trusting the result.
Long straddle
Concept. Buy an ATM call and an ATM put. Profit from a large move in either direction.
Why it works (sometimes). When implied volatility is very low, options are cheap relative to the eventual move. Straddles bought before major catalysts (results, budgets, elections) can produce large positive returns.
Time decay is brutal. If the expected move doesn't materialise within days, both legs lose value. Long straddles have a low win rate — the winners have to be big enough to pay for the losers.
Short put
Concept. Sell an OTM put. Bullish income strategy.
Why it works (sometimes). Selling puts collects premium while committing to buy the underlying at a discount if assigned. In an uptrend, most puts expire worthless.
In a crash, put losses accelerate far faster than the premium collected can compensate for. The March 2020 period is instructive — a strategy that made steady returns for years gave back all of it in a week.
Options with underlying filters
You can combine options entry with technical conditions on the underlying.
Temporal options entries
Restrict entries to specific days.
7. Pattern library: allocation & SIP strategies
Allocation strategies rank a universe of assets and periodically rebalance into the top N. SIP strategies invest a fixed amount at regular intervals.
Momentum rotation
Concept. Every month, pick the top 3 stocks by momentum score and hold them equal-weight. Rebalance monthly.
Why it works (sometimes). Momentum tends to persist in equities on horizons of three to twelve months. Monthly rebalancing captures trends while rotating out of laggards before they hurt too much.
Momentum crashes hard at market turning points. In late 2008 and March 2020, momentum strategies had their worst months on record. Consider adding a drawdown-based cash-out rule.
Risk-adjusted rotation
Use Sortino ratio or low volatility instead of raw return.
Why it works (sometimes). Ranking by risk-adjusted return favours steady performers over volatile ones. Low-volatility rotation exploits the empirical anomaly that low-vol stocks have historically delivered better risk-adjusted returns than high-vol ones.
Buy-and-hold benchmark
A useful baseline. If your rotation strategy doesn't beat buy-and-hold after costs, the complexity isn't worth it.
Dynamic filters
Only include assets that pass a technical condition at each rebalance.
Weighting schemes
- Equal weight — every selected asset gets the same allocation
- Market-cap weighted — larger companies get larger allocations
- Fixed weights — custom percentages
SIP examples
8. Prompt engineering
8.1 Be explicit about units
8.2 Use standard indicator names
Āagman understands TA-Lib names.
8.3 Specify SL/TP mode
- Percent: stop loss at 2% below entry
- Points: stop loss at 15 points below entry
- INR absolute: stop loss at ₹500 per trade
- Premium-based (options): stop loss at 100% of premium collected
8.4 Avoid unsupported patterns
Don't ask for:
- Mixed timeframes in one prompt
- Supertrend, Heikin-Ashi, Chandelier Exit
- Partial exits or pyramiding
- Covered calls (mixed equity + options legs)
- Dynamic position sizing based on volatility (not yet supported)
8.5 Use relative dates carefully
last 3 years works, but explicit dates make comparison easier. If you're sharing results with a team, use explicit dates.
9. Reading the results
9.1 The hero strip
The top of the result shows the most important numbers:
- Total return — your bottom line
- Max drawdown — the worst losing streak
- Win rate — how often trades were profitable
- Number of trades — sample size
9.2 The equity curve
The equity curve shows account value over time. Look for:
- Smooth upward slope — consistent performance
- Long flat periods — no trades or whipsaws
- Sharp drops — drawdowns; check whether they recover
9.3 The trade table
Each row is one completed trade. Check:
- Entry and exit reasons — did the engine follow your rules?
- Holding period — are trades too short or too long?
- Largest winner/loser — is one trade dominating results?
9.4 Key metrics explained
| Metric | What it tells you | Rough benchmark | Watch out for |
|---|---|---|---|
| Total return | Overall P&L | Depends on period | Doesn't reveal the risk you took |
| Max drawdown | Largest peak-to-trough loss | < 20% for most investors | Backtest may not include the worst regime |
| Sharpe ratio | Return per unit of total risk | > 1 respectable, > 1.5 strong | Gamed by strategies with hidden tail risk |
| Sortino ratio | Return per unit of downside risk | Higher is better | Same tail-risk blind spot as Sharpe |
| Calmar ratio | Return / max drawdown | > 1 is good | Sensitive to a single deep drawdown |
| Win rate | % winning trades | Meaningless alone | High win rate can pair with a catastrophic average loser |
| Profit factor | Gross profit / gross loss | > 1.5 is healthy | Dominated by one big trade in small samples |
| Expectancy | Average P&L per trade | Positive is required | Small positive − costs = negative live |
9.5 Red flags
- Very few trades — the result may be statistically meaningless
- Win rate near 100% with small returns — the strategy may be curve-fitted
- Massive drawdown relative to return — the risk may not be worth it
- One huge winner hiding many small losers — the strategy depends on outliers
10. How to iterate
The biggest mistake in backtesting is treating each run as a verdict. It isn't — it's one data point. Good iteration looks like this:
Start simple. One entry, one exit, one symbol. Get a baseline.
Check the trade table before the metrics. Verify entries and exits actually happened where you expected. Metrics can lie; individual trades don't.
Add one filter at a time. Trend filter, then volume filter, then time-of-day filter. If a filter doesn't clearly improve results across multiple symbols, drop it.
Test on different symbols. A strategy that works only on RELIANCE isn't a strategy — it's a story about RELIANCE.
Test on different date ranges. Especially: does it survive 2020 (Covid), 2022 (rate shock), 2018 (mid-cap crash)?
Compare against buy-and-hold. If you can't beat holding the index, the complexity isn't earning its keep.
Be skeptical of impressive results. The better a backtest looks, the more likely it's overfitted — especially results with fewer than 30 trades, one dominant winner, or parameters that were tuned to make history look good.
Reserve a chunk of history you never test on. Design the strategy on 2020–2023, then run it once on 2024–2025. That's your honest read.
11. Troubleshooting
"No trades generated"
- Date range too short for the indicator lookback
- Conditions are too restrictive
- Breakout condition not shifted properly (Āagman handles this automatically)
- Symbol has no data for the requested period
Fix: widen the date range, loosen conditions, or check symbol coverage.
"Capital too low"
Āagman requires enough capital to cover the position size. Increase starting capital or reduce position size.
"Risk blocked"
Some prompts require a stop loss or other risk controls. Add an SL/TP or confirm that you want to proceed without one.
"Symbol not found"
- Use the exact NSE symbol: RELIANCE, not Reliance Industries
- Mutual funds must be named clearly: SBI Bluechip Fund
- Options underlyings must be valid: NIFTY, BANKNIFTY, RELIANCE
"Unsupported feature"
You may have asked for mixed timeframes, partial exits, or stateful indicators. Simplify the prompt.
Results look wrong
Check the trade table first. Verify that:
- Entry dates align with your indicator signals
- Exits happened at the right levels
- Position sizes match your intent
Results look too good
This is more dangerous than results that look bad. Check:
- Trade count. Fewer than 30 trades and any metric could be luck. Fewer than 10 and you have no signal.
- Curve-fitting. If you tuned parameters until returns looked good, retest with slightly different values. If small parameter changes destroy the result, you've overfit.
- In-sample optimization. If you chose the date range because the strategy works in it, results are meaningless. Test on periods you didn't design against.
- One dominant trade. Remove the biggest winner. Does the strategy still work?
- Costs. Did you set fees and slippage realistically? A strategy that only works at zero cost isn't a strategy.
12. Appendix
12.1 Supported asset classes
- Equities & indices (NSE/BSE)
- Options (NIFTY, BANKNIFTY, FINNIFTY, MIDCPNIFTY, SENSEX, BANKEX, stock options)
- Mutual funds (AMFI scheme codes)
- Commodities (MCX futures, single-contract mode)
12.2 Supported timeframes
Only one timeframe per backtest.
12.3 Supported sizing models
- Fixed quantity (shares)
- Percent equity
- Fixed lots (options/commodities)
12.4 Supported indicator categories
Trend
Momentum
Volatility
Volume
Patterns
61 candlestick patterns (CDLDOJI, CDLHAMMER, CDLENGULFING, etc.)
Stats
Rolling
12.5 Known limitations
- Only one timeframe per backtest
- Equity MIS/NRML coerced to CNC in backtests
- Futures lack rollover / continuous contract logic
- No Supertrend, Heikin-Ashi, or Chandelier Exit
- No partial exits or pyramiding
- No covered calls (mixed equity + options legs)
- Fundamental metrics are static snapshots, not point-in-time