Get your API key

Lesson 3 of 5

Code the rule in pandas, without peeking ahead

Moving averages, signal, shift(1) to avoid look-ahead, returns and an equity curve, then a check table you verify in Excel.

10 min Log in to open

Education only. This is not investment advice and nothing here is a buy or sell recommendation. Trading carries risk of loss, and past results do not predict the future. Backtests are hypothetical: practise on paper only, never connect broker API keys or place live orders from these lessons. For personal advice, talk to a SEBI-registered Investment Adviser.

One step at a time, like flipping pages.

By the end of this lesson you will have a working backtest of the moving-average rule in pandas, understand the one line that prevents look-ahead, and have checked the result by hand in Excel.

You need: data/nifty50_daily.csv from lesson 2, your coding agent, Excel or Google Sheets · Time: 10 minutes

  1. Your rule from lesson 1 goes into the prompt almost word for word. The agent writes the code; your job is the rule and the check.

    Prompt · copy it into your AI agent
    Write backtest.py for my rule. Read data/nifty50_daily.csv (columns Date, Close, High, Low, Open, Volume).
    
    Rule (learning only, test data):
    - fast = 20-day simple moving average of Close, slow = 50-day simple moving average of Close. Skip the first days where slow is empty.
    - signal = 1 on days when fast is above slow at the close, else 0.
    - position = the previous day's signal (shift by 1). A signal can only affect returns from the next day.
    - market return = daily % change of Close; strategy return = position x market return.
    - equity curves for the strategy and for buy and hold, starting at Rs 1.
    
    Print the final value of Rs 1 for both, and a check table with 5 rows around the latest day the signal changed from 0 to 1 (Close, fast, slow, signal, position). Save all rows to data/backtest_rows.csv. No costs yet (next lesson). Explain each line in simple English, then run it.
    Python
    import pandas as pd
    
    FAST, SLOW = 20, 50          # rule inputs (examples, not "best" values)
    
    df = pd.read_csv("data/nifty50_daily.csv", parse_dates=["Date"], index_col="Date")
    df["fast"] = df["Close"].rolling(FAST).mean()
    df["slow"] = df["Close"].rolling(SLOW).mean()
    df = df.dropna(subset=["slow"]).copy()   # skip the first days with no slow average
    
    # Signal at today's close: 1 = fast above slow, 0 = not
    df["signal"] = (df["fast"] > df["slow"]).astype(int)
    # We can only act on it from the NEXT bar: shift(1) removes look-ahead
    df["position"] = df["signal"].shift(1).fillna(0)
    
    df["market_ret"] = df["Close"].pct_change().fillna(0)
    df["strategy_ret"] = df["position"] * df["market_ret"]
    df["equity"] = (1 + df["strategy_ret"]).cumprod()
    df["buy_hold"] = (1 + df["market_ret"]).cumprod()
    
    print("Final value of Rs 1, strategy :", round(df["equity"].iloc[-1], 2))
    print("Final value of Rs 1, buy & hold:", round(df["buy_hold"].iloc[-1], 2))
    
    # Check table: rows around the latest cross up, to verify in Excel
    first = df.index[(df["signal"].diff() == 1)][-1]
    i = df.index.get_loc(first)
    print(df.iloc[i - 2 : i + 3][["Close", "fast", "slow", "signal", "position"]].round(1))
    df.to_csv("data/backtest_rows.csv")

    The pandas words, in one line each:

    • rolling(20).mean(): the average of the last 20 rows, row by row (like dragging =AVERAGE(B2:B21) down in Excel).
    • shift(1): move a column down one row, so each day sees yesterday's value.
    • pct_change(): today's close divided by yesterday's, minus 1.
    • cumprod(): multiply the growth day after day, which turns daily returns into a running value of Rs 1.
    Why?

    You don't need to write pandas, but you need to recognise these four words. They are where almost every backtest bug hides.

Log in free to read the rest of this lesson

Every lesson is free. A free account unlocks all of them and saves your progress.

Still to come in this lesson:

  1. Signal today, position from tomorrow
  2. Run it and check by hand
  3. See look-ahead with your own eyes
  4. Recap