Your first backtest, the scorecard (Sharpe, Sortino, drawdown), and why "the best settings" can be an illusion.
We will test one very simple rule. Every day, compare today's price with the average of the last 50 days (the 50-day moving average).
The hope is not to predict anything. It is to ride long up-moves and avoid long falls.
Green zones are the days the rule is invested. Notice it stays out of the crash.
Why a simulated market? Your folder holds strategy code but no price history. A fake market that I generate is useful anyway, because I know exactly what is true about it (when the crash is, whether there is any edge). Real data comes later.
"It made money" is not enough. Two strategies can both end at +50% and be completely different experiences. These are the measures quants use.
CAGR is your average yearly growth rate. Volatility is how much daily returns bounce around (their standard deviation), scaled to a year. High volatility means a bumpy ride.
Think of two taxi drivers who each earn ₹1,000 a day on average. One earns exactly ₹1,000 every day. The other earns ₹0 some days and ₹3,000 on others. Same average, very different stress. Sharpe measures this:
Sharpe = (average return ÷ volatility) × √252
The √252 only converts daily numbers into yearly ones. As a rough guide: under 0.5 is weak, around 1 is good, and above 2 in a backtest should make you suspicious.
Sharpe has a flaw. Volatility counts a surprise gain as "risk" just like a surprise loss. Nobody complains about a day that was unexpectedly good. Sortino fixes this: the bottom of the fraction only uses the losing days.
Sortino = average return ÷ downside deviation, where downside deviation = √(average of (min(return, 0))²)
Here is a tiny example with 5 days each. Both strategies have the same average (+1%) and the same volatility, so Sharpe cannot tell them apart:
| Daily returns (%) | Average | Volatility | Sharpe (per day) | Downside dev. | Sortino (per day) | |
|---|---|---|---|---|---|---|
| A: many small losses, one big win | −1, −1, −1, −1, +9 | 1 | 4.47 | 0.22 | 0.89 | 1.12 |
| B: many small wins, one big loss | +3, +3, +3, +3, −7 | 1 | 4.47 | 0.22 | 3.13 | 0.32 |
Sharpe says "identical". Sortino says A is much better, because A's pain is mild (−1% days) and B's pain is a −7% day. That is the point of Sortino: it cares about the shape of your losses, not just their spread. Strategies that sell insurance (steady small gains, rare disasters) often have impressive Sharpe ratios but poor Sortino ratios.
The chart below shows the same idea with 2,000 days of returns. The red one has a long left tail, which is the hidden danger.
A correction. In my first message I computed Sortino with a shortcut (the standard deviation of only the negative days). The standard definition is the one above. With it, the MA50 strategy's Sortino is 0.59, not 0.43. The table below uses the correct numbers.
Drawdown is how far you are below your previous peak. If your account hit ₹100 and fell to ₹60, the drawdown is −40%. Max drawdown is the worst such fall. Ask yourself honestly: would I hold through that, or sell at the bottom?
| CAGR | Volatility | Sharpe | Sortino | Max drawdown | |
|---|---|---|---|---|---|
| Buy & hold | −10.0% | 21.2% | −0.39 | −0.53 | −72.6% |
| MA50 trend rule | +4.3% | 12.5% | 0.40 | 0.59 | −25.6% |
Top: growth of ₹1. Bottom: how far below the previous peak each is.
Be skeptical of this result. It is one simulated path, and I deliberately put a crash in it. Trend rules shine when there is a crash to avoid, and usually lag buy-and-hold in calm bull markets. One backtest is an anecdote, not proof. The same rule is not "better", it is better in this kind of market. We will test it across many markets later.
Our rule has a setting: the lookback, 50 days. Why 50? Why not 20 or 200? Optimising means trying many settings (5, 10, 15, ..., 200), measuring each one on past data, and keeping the one with the best score. These settings are called parameters. It sounds sensible, and it is the single most common way beginners fool themselves.
Imagine a student with 10 past exam papers. They memorise the answers to those exact papers and score 100% on them. On the real exam, with new questions, they score 40%. They learned the old papers, not the subject.
The standard practice: split your history. Choose settings on the first part (in-sample), then test once on the later part (out-of-sample). If the score collapses, you had memorised noise.
In a market of pure randomness, some lookback will always score well on the past by luck, just as among 40 coin-flippers someone will flip 8 heads in a row. Picking the winner of many tries picks the luckiest, and luck does not repeat. The more settings you try, the luckier the winner, and the bigger the disappointment later.
The market below is pure randomness: no trend, no edge. The rule truly has nothing to find. The chart shows the Sharpe ratio for every lookback on the first half of the data (in-sample, blue) and on the second half (out-of-sample, orange). The red marker is the "best" lookback by in-sample score.
Things to try:
The rule to remember: a good in-sample score is where research starts, not where it ends. Believe the out-of-sample number, and be more doubtful the more things you tried.
You said writing financial code is hard. It is normally just a handful of pandas ideas used repeatedly. Learn these six and you can read almost every backtest in your folder.
| Idea | What it does |
|---|---|
Series | A column of numbers with a date on each row. Our prices and returns are Series. |
(1 + r).cumprod() | Compounds returns. +1% then +2% gives 1.01 × 1.02. Turns "daily % changes" into a growth curve. |
.rolling(50).mean() | For each day, the average of that day and the 49 before it. The moving average. |
price > sma | Compares two columns row by row and gives True/False for each day. |
.shift(1) | Slides everything down one day, so today's row holds yesterday's value. This is how you avoid cheating (see section 6). |
.cummax() | Running highest value so far. Used for drawdowns. |
The complete small program is in minimal.py. Here it is in pieces, with the reasoning for each.
np.random.seed(7)
returns = pd.Series(np.random.normal(0.0003, 0.01, 1000))
price = 100 * (1 + returns).cumprod()
pd.read_csv(...) and use price.pct_change() to get returns.sma = price.rolling(50).mean()
in_market = price > sma
position = in_market.astype(float).shift(1)
position = position.fillna(0)
Why the delay? You only know today's closing price after the day ends, so the earliest you can act on today's signal is tomorrow. Without shift(1) the backtest secretly trades on information it could not have had.
strategy_returns = position * returns
def sharpe(x):
return x.mean() / x.std() * np.sqrt(252)
def sortino(x):
downside = np.sqrt((np.minimum(x, 0) ** 2).mean())
return x.mean() / downside * np.sqrt(252)
def max_drawdown(x):
equity = (1 + x).cumprod()
peak = equity.cummax()
return (equity / peak - 1).min()
np.minimum(x, 0) replaces every positive day with 0 and keeps the losses, so only bad days survive; we square them, average, and square-root, which gives the downside deviation. max_drawdown: build the growth curve, track its running peak, divide to see how far below the peak you are each day (a negative number), and take the worst one.def sharpe_for_lookback(n, r, p):
pos = (p > p.rolling(n).mean()).astype(float).shift(1).fillna(0)
return sharpe(pos * r)
first_half, second_half = slice(0, 500), slice(500, 1000)
scores_in = {n: sharpe_for_lookback(n, returns[first_half], price[first_half])
for n in range(5, 205, 5)}
best_n = max(scores_in, key=scores_in.get)
max(..., key=scores_in.get) returns the lookback with the highest score. Then we score that same lookback on the second half, which it never saw. That final number is the honest one.Buy & hold Sharpe 0.03 Sortino 0.04 MaxDD -35.3%
MA50 rule Sharpe 0.08 Sortino 0.11 MaxDD -24.3%
Best lookback on first half: 70 (in-sample Sharpe -0.22)
Same lookback on second half: (out-of-sample Sharpe 1.18)
On this one random market the "best" setting looked bad in-sample (−0.22) and then looked great out-of-sample (1.18). Both are just luck, since there is no edge in this data. One market tells you nothing. That is exactly why the widget above repeats the experiment on 300 markets.
python3 -m venv venv
source venv/bin/activate # on fish shell: source venv/bin/activate.fish
pip install numpy pandas matplotlib
python minimal.py # the small version
python sim.py # the full version that makes the charts
The folder's backtest/ma_cross.py uses a library called quanttrader. It feeds the strategy one day at a time through on_tick, which looks at the latest price, computes np.mean(df_hist['Close'][-lookback:]) (the same moving average), and buys if price > average. It is the same idea, run in an event loop that behaves like live trading, with a broker simulation handling orders. Our pandas version does it all at once, which is shorter and easier to learn from. The event-loop style is better for realistic order handling.
| Trap | What goes wrong | Defence |
|---|---|---|
| Look-ahead bias | Trading on a signal at a price you could not have known. In my test it turned ₹1 into ₹4.59, while the honest version made ₹1.32. | .shift(1) every signal |
| Ignoring costs | This rule made 96 trades. I charged 0.05% each. Frequent trading quietly eats profit. | Always subtract costs |
| Overfitting | Choosing the luckiest settings (section 4). | Out-of-sample testing, fewer parameters |
| One-path thinking | Judging a strategy from one history. | Test across many markets and periods |
Sharpe counts all volatility, up or down. Sortino counts only losses. If one strategy's volatility comes mostly from big wins and the other's from big losses, Sortino favours the first.
Test it on data it never saw (out-of-sample). Expect a lower number. The more combinations you tried, the more of that 1.8 is probably luck.
.shift(1)?Because you can only act on today's signal tomorrow. Without it, the backtest uses information from the future and the results are fake.
Overfitting. The settings were fitted to noise in the first period, and that noise did not repeat.
All data here is simulated for teaching. Educational content, not investment advice. The moving-average idea follows ma_cross.py from the open-source QuantResearch repo by Letian Wang (MIT license).
All strategy lessons · Next: Lesson 2, Breakouts versus bands