LearnFinance
← Spreadsheets & Python for Finance Lesson 6 of 6 · 16 min · +50 XP
Spreadsheets & Python for Finance · Lesson 06

A first analysis in Python: returns, volatility and a simple backtest

Putting the module together: daily returns from adjusted prices; annualising average return and volatility, step by step with a calculator; a maximum drawdown worked by hand; a Sharpe ratio; then an honest backtest of a 200-day moving-average rule, with a one-day lag against look-ahead, trading costs, and the tax drag that India's July 2024 rise in short-term gains tax makes worse for active strategies.

Facts reviewed Oct 2026

This lesson brings the module together. It uses clean, adjusted data from the previous lesson, pandas from the one before, and the statistics from Statistics & Probability for Finance.

The goal: a short, honest analysis of an index, and a first backtest of a simple trading rule that avoids the most common traps.

Returns and volatility

Start from adjusted daily closes:

close = nifty["Close"]
ret = close.pct_change().dropna()          # daily returns

ann_ret = ret.mean() * 252                 # average daily return × trading days
ann_vol = ret.std() * 252 ** 0.5           # volatility grows with √time
sharpe = (ann_ret - 0.065) / ann_vol       # extra return for each unit of risk
  • A year has roughly 250 trading days in India; 252 is the common convention in code.
  • Average returns grow in line with time, so multiply by 252. Volatility grows with the square root of time, so multiply by √252, about 15.9. (The Maths of Money explains why.)
  • The Sharpe ratio takes away a risk-free rate, here 6.5%, and divides by volatility. (Portfolio Management covers it.)
  • The compounded return is lower than the simple average, by roughly half the variance. This is volatility drag.

Worked example. An index’s daily returns average 0.05%, with a standard deviation of 1.1%.

  1. Yearly average return: 0.05% × 252 = 12.6%.
  2. Yearly volatility: 1.1% × 15.9 = about 17.5%.
  3. Sharpe ratio: (12.6 − 6.5) ÷ 17.5 = about 0.35.
  4. Volatility drag: half the variance = 17.5² ÷ 200 = about 1.5 points.
  5. Compounded return: 12.6 − 1.5 = about 11.1% a year.

Drawdowns

The maximum drawdown, the largest fall from a peak, often matters more to investors than volatility. It’s the loss you’d have had to sit through.

wealth = (1 + ret).cumprod()
drawdown = wealth / wealth.cummax() - 1
max_dd = drawdown.min()

Worked example. A portfolio’s value at seven month-ends: 100, 110, 105, 120, 90, 96, 125.

  1. Running peak (cummax): 100, 110, 110, 120, 120, 120, 125.
  2. Drawdown each month (value ÷ peak − 1): 0%, 0%, −4.5%, 0%, −25%, −20%, 0%.
  3. Maximum drawdown: the lowest of these, −25%, from 120 down to 90.

The portfolio ended up 25% overall. But anyone who held it lived through a fall of a quarter on the way.

The cost of trading

A strategy that trades often pays costs on every switch. There’s brokerage, securities transaction tax (STT), exchange fees and GST. There’s also the gap between buying and selling prices.

A strategy trading 12 round trips a year (12 buys and 12 sells), at 0.3% per round trip, loses 12 × 0.3% = 3.6 points a year to costs, before it does anything clever.

From daily statistics to annual numbers, and the cost of trading
Annual average return
12.6%
Annual volatility
17.46%
Sharpe ratio
0.35
Compounded return after volatility drag (approx.)
11.08%
Cost drag a year
3.6%

The defaults: 12.6% average, 17.5% volatility, a Sharpe ratio of about 0.35, about 11.1% compounded, and a 3.6-point cost drag for 12 round trips. At 40 round trips a year, costs eat almost all of the return.

A first backtest, done honestly

A classic rule: hold the index when it’s above its 200-day moving average (the average close of the last 200 trading days). Otherwise, hold cash. The honest version:

ma = close.rolling(200).mean()
signal = (close > ma).astype(int).shift(1)          # decide today, act tomorrow
strat = (signal * ret).dropna()                      # earn the return only when invested
trades = signal.diff().abs().reindex(strat.index).fillna(0)
strat_net = strat - trades * 0.0015                  # 0.15% cost each time we buy or sell
growth = (1 + strat_net).cumprod()

Three details make it honest:

  1. shift(1) avoids look-ahead bias. You can’t know today’s close before the close, so you act the next day.
  2. Costs are charged on every switch. The cost should include brokerage, STT, market impact and slippage (getting a worse price than expected).
  3. Compare with buy-and-hold on the same data. Compare returns, volatility, drawdown and Sharpe, not just final wealth. And decide what the cash earns when you’re out of the market.

Then test out of sample. Develop the idea on one period, check it on another, and resist tuning the “200” to whatever worked best. That’s the data-mining trap from Statistics & Probability for Finance. (Algorithmic & Systematic Trading covers the wider checklist.)

Quick check

A backtest uses today's closing price both to make the signal and to trade at that same close. What's wrong?

A real case: tax makes active strategies harder in India

Backtests usually ignore tax. In India, that hides a big cost for strategies that switch in and out.

From 23 July 2024, tax on short-term gains from listed shares and equity funds, held 12 months or less, rose from 15% to 20%. Long-term gains are taxed at 12.5%, above ₹1.25 lakh a year. (Investor Taxation in India has the rules.)

Worked example. Two investors each start with ₹10 lakh, and each earns 12% a year before tax for 10 years. No costs, no difference in skill.

  1. Buy-and-hold: pays tax only once, at the end. ₹10 lakh × 1.12¹⁰ = about ₹31.1 lakh. The gain is ₹21.1 lakh; tax at 12.5% on the gain above ₹1.25 lakh is about ₹2.5 lakh. After tax: about ₹28.6 lakh.
  2. Active switcher: sells within a year every time, so every year’s gain is taxed at 20%. After-tax return: 12% × 0.8 = 9.6% a year. ₹10 lakh × 1.096¹⁰ = about ₹25 lakh.
  3. The gap: about ₹3.6 lakh, from tax alone.

So an active rule must beat buy-and-hold by a clear margin after costs and tax, not just before.

Presenting results

A short, honest summary includes:

  • the period and data source;
  • yearly return, volatility, Sharpe ratio and maximum drawdown, for both the strategy and buy-and-hold;
  • the number of trades, and the cost assumption;
  • results in sub-periods, such as before and after 2020;
  • a chart of both growth curves on a log scale, so equal percentage moves look equal.

Note the limits too: one market, one period, simplified costs, and taxes left out.

Going further: why log scales and log returns. On an ordinary chart, a rise from 1,000 to 2,000 looks small next to one from 10,000 to 20,000, though both are doublings. A log scale spaces values by ratio, so equal percentage moves look equal, and long histories become readable. Log returns, ln(today ÷ yesterday), have a matching advantage: they add up over time. Three days of log returns of +1%, −2% and +1.5% sum to +0.5%, which is exactly the log return over the three days. Simple returns don’t add like that; you have to multiply (1 + r) terms. For small daily moves the two are almost equal, but over long periods or big moves, the difference matters.

Common mistakes

  • Annualising volatility by 252 instead of √252. Volatility grows with the square root of time.
  • Reporting the simple average as the growth rate. Take off the volatility drag.
  • Forgetting shift(1). It’s the most common look-ahead error in backtests.
  • Ignoring costs and tax. For active rules, they often decide the result.
  • Tuning the rule until it works. Test on data you didn’t use to build it.
Practice 1: A more active strategy has the same daily statistics, but trades 40 round trips a year at 0.3% each. What's left after costs and volatility drag?
  1. Compounded return before costs: about 11.1%.
  2. Cost drag: 40 × 0.3% = 12 points.
  3. Left over: 11.1 − 12 = about −0.9% a year, worse than holding cash.

Enter 40 round trips in the calculator to check. Costs, not cleverness, decide most retail strategies.

Practice 2: Month-end values are 200, 180, 210, 168, 189, 230. What's the maximum drawdown?
  1. Running peak: 200, 200, 210, 210, 210, 230.
  2. Drawdowns: 0%, −10%, 0%, −20%, −10%, 0%.
  3. Maximum drawdown: −20%, from 210 to 168.

Key takeaways

  • Work out daily returns from adjusted prices. Annualise the average × 252 and volatility × √252.
  • Report the Sharpe ratio, maximum drawdown, and the compounded return after volatility drag.
  • An honest backtest lags the signal with shift(1), charges realistic costs, compares with buy-and-hold, and is tested out of sample.
  • Costs grow with trading, and tax too: since July 2024, short-term equity gains are taxed at 20%. In the example, tax alone left an active switcher ₹3.6 lakh behind over 10 years.

Go deeper

Complete this lesson
Pass the quiz below (60% or more) to earn +50 XP and unlock the next lesson.
Quiz not passed yet
🧠

Quiz: A first analysis in Python: returns, volatility and a simple backtest

5 questions · pass 60% to complete