Register
Learn guide

Backtesting in Python: A Coding Course

Backtesting in Python (beta) teaches you how to build a small chronological simulator for rules you have written yourself. You will work with fictional opening and closing values, record when a decision becomes possible and verify that the simulated fill cannot occur earlier. The result is an audit trail of your code, not a forecast, a recommendation or a claim about results in a market. QuantPower is software, not an adviser.

QuantPower Research · Updated 27 Nov 2026 · 17 min read

Use Python 3.10 or later, a text editor and an offline folder. Start with Python basics for traders if you have not used functions and tests. Review market data and candles for interval boundaries and missing data, and Python trading indicators for time-aligned transformations. For the broader product workflow, read backtesting; this course is about writing and inspecting a local simulator instead of operating the platform's backtester.

We use lessons, exercises and an answer check. A small paper ledger is your reference. Quanty exercise review (beta) can help you reason through one synthetic event trace after you have run the local tests. None of the examples uses a broker account, a recorded account export or a live market endpoint. The placeholder levels and units are invented to make arithmetic hand-checkable.

Lesson 1: Write a fixture whose outcome you can explain

Small simulator fixture: Fictional candles → Scripted signals → Expected ledger.
Small simulator fixture: Fictional candles → Scripted signals → Expected ledger.

Start by expressing the exercise rule without a code editor: “Read a completed bar's close. If it is above the fixed classroom level, set the next simulated bar's target state to one unit; otherwise set it to zero.” The exercise is not to select a level that predicts anything. It is to test when a condition becomes available, when a simulated change takes place and how fees affect the accounting entries.

Write a tiny table of four bars. Give each bar a sequence index, an opening value and a closing value. Make the opening value on the third row noticeably different from the second row's close. If these numbers were accidentally used interchangeably, the final ledger should change. Small deliberately informative fixtures are more useful here than a long constant series whose output looks acceptable under several incorrect implementations.

The code models a single fictional unit, with no short state, no search for parameters and no accounts. It assumes one timeline and ordered complete bars, which the previous course teaches you to audit. If those prerequisites do not hold, the simulator should not infer a missing moment from prices. In this exercise, the sequence index starts at zero and explicitly increases by one; a gap or duplicate causes validation to fail.

For your first exercise, choose four input rows and the level so that the target changes twice. Before entering data, write down each completed close and its proposed target for the next row. Leave the last proposed target in your note even if there is no later row on which to apply it. That is an expected pending decision, not missing data or evidence that a fill occurred.

Answer check. Ask whether each row in your trace says what was known, what was requested or what was realised in the model. A clear answer should not use “trade” as a catch-all term for all three events. The distinction is central to verifying timing. Use invented values only.

Lesson 2: Keep the simulation clock explicit

Clock order: Observe close → Queue action → Next open.
Clock order: Observe close → Queue action → Next open.

Treat each bar as two ordered points in the simulator. At the opening point, you may apply a target determined at an earlier close. At the closing point, you may observe that bar's closing value and calculate a new target. That new target cannot affect the opening that already passed. This has nothing to do with Python's speed. It is a property of what information is available at each time.

At the start of a run the state is flat. There is no preceding completed close in the input, so there is no target to apply to the first opening. On the last bar, a new target can be recorded but there is no following opening within the fixture. Do not automatically fill it at the last close just to satisfy the ledger. The reference records the last target and the ending model state without silently inventing a fill.

A good exercise uses a large difference between the decision close and next open. Suppose the first close is 105, the invented threshold is 104 and the next open is 109. The first close may propose one unit; 109 is the opening value at which the simplified model applies it before adjustments. Using 105 would make the simulation look neater, but it would be a different timing rule. Record both fields so a reviewer can see which value was used.

For the exercise, draw a chronological event line: bar zero open, bar zero close, bar one open, bar one close. Place each event on the line. Then add the information content under it: the first close is known at the second point; the earlier open cannot depend on it; the first target may influence the next opening. Restore the line when you add more rows. If you are using actual dates in another project, be explicit about the source timestamp and interval label rather than relying on a chart layout.

Answer check. Give Quanty a trace with one deliberate violation: a target from bar one's close apparently filled at bar one's opening. Ask which information arrived too late for the recorded fill. A good response explains the event order and does not recommend altering the underlying rule to make the model look good.

Lesson 3: Specify what an accounting entry means

Separate ledger columns: Action → Execution price → Fees and mark.
Separate ledger columns: Action → Execution price → Fees and mark.

This example has two model adjustments. First, a nonnegative adverse price adjustment changes the recorded fill value away from the unadjusted opening: an increase to acquire the fictional unit or a decrease to release it. Second, a separate fee is taken per simulated state change. Neither number is an estimate of what an exchange, broker or service would charge. Use a fictional fee and adjustment only to prove that the signs and timing are implemented.

The notebook tracks cash, unit state and a final mark from remaining units. If you acquire a unit, cash decreases by the fill value and fee. If you release it, cash increases by the fill value less the fee. The final mark in this exercise uses the last closing value for any remaining unit. Marking a remaining unit is not the same as selling it; the simulation will not fabricate a final state change or a fee at the mark.

Choose a simple hand-checkable case. Let initial cash be 1,000 fictional units. Suppose the model acquires one unit at a base opening of 109, with an adverse adjustment of 1 and a fee of 2. The effective fill is 110 and the resulting cash is 888. If a later state change releases the unit at an opening of 111, its effective fill is 110 and its cash contribution after fee is 108. Ending cash is 996 when there is no remaining unit. These numbers are arithmetic examples, not results for a trade.

Make the next scenario end with the unit still held. Compare final cash with final marked value. The difference comes from the last closing value applied to the remaining unit; it is not another fee or an executed release. If a chart reports only one final number, a reader cannot tell which definition it uses. Record both in the result and write which one you compare in your tests.

For the exercise, manually calculate a case with a zero fee and a nonzero adjustment; then use a fee and no adjustment. Confirm that the adverse shift is applied once at each state change and not again in the marked result. Use a constant target for multiple rows to show that no accounting entry occurs when the state is already at the requested value. Repeating a recommendation to hold the same model state is not the same action as acquiring the unit again.

Answer check. Show one computed ledger entry and ask Quanty to explain each sign. The response should be able to identify the difference between an unadjusted value, an adjusted fill, a separate fee and a final mark. If those distinctions are lost, improve the table before comparing totals.

Lesson 4: Implement only what the fixture contract promises

Simulation boundary: Offline fixture → Simulator → Event trace.
Simulation boundary: Offline fixture → Simulator → Event trace.

Save the following as offline_backtest.py. It contains no execution or network integration. The code validates the sequence and records every model state change and every closing decision explicitly. Use the Python decimal documentation if you want to examine the numeric representation and context.

Python
from dataclasses import dataclass
from decimal import Decimal


@dataclass(frozen=True)
class Bar:
    index: int
    open: Decimal
    close: Decimal


@dataclass(frozen=True)
class Event:
    index: int
    phase: str
    kind: str
    target: int
    fill: Decimal | None = None
    cash: Decimal | None = None


@dataclass(frozen=True)
class Result:
    events: tuple[Event, ...]
    cash: Decimal
    held: int
    marked: Decimal
    final_target: int | None


def run(
    bars: list[Bar],
    level: Decimal,
    initial: Decimal,
    fee: Decimal = Decimal(0),
    adverse: Decimal = Decimal(0),
) -> Result:
    if any(not v.is_finite() for v in (level, initial, fee, adverse)):
        raise ValueError("settings must be finite")
    if level <= 0 or initial < 0 or fee < 0 or adverse < 0:
        raise ValueError("invalid classroom settings")
    for index, bar in enumerate(bars):
        if type(bar.index) is not int or bar.index != index:
            raise ValueError("bars must be contiguous starting at zero")
        if any(not v.is_finite() or v <= 0 for v in (bar.open, bar.close)):
            raise ValueError("bar values must be finite and positive")
        if bar.open <= adverse:
            raise ValueError("adjusted release value must remain positive")

    cash = initial
    held = 0
    pending = None
    events = []
    for bar in bars:
        if pending is not None and pending != held:
            if pending == 1:
                fill = bar.open + adverse
                charge = fill + fee
                if cash < charge:
                    raise ValueError("fixture cash cannot cover model move")
                cash -= charge
            else:
                fill = bar.open - adverse
                if cash + fill < fee:
                    raise ValueError("fixture cash cannot cover model move")
                cash += fill - fee
            held = pending
            events.append(Event(bar.index, "open", "model fill", held, fill, cash))
        pending = int(bar.close > level)
        events.append(Event(bar.index, "close", "decision", pending))
    marked = cash + held * bars[-1].close if bars else cash
    return Result(tuple(events), cash, held, marked, pending)


if __name__ == "__main__":
    D = Decimal
    report = run(
        [Bar(0, D("101"), D("105")), Bar(1, D("109"), D("100")), Bar(2, D("111"), D("106"))],
        D("104"), D("1000"), D("2"), D("1"),
    )
    for event in report.events:
        print(event)
    print("cash", report.cash, "marked", report.marked, "held", report.held)

Notice that the reference refuses a request that exceeds the fictional cash available. It does not quietly provide funds, borrow or resize a simulated move. That is a modelling choice, not a complete risk system. A later research model might record a rejected event instead of terminating a fixture. Decide on that state transition and how it affects the pending target before adopting it. The exercise uses a precise failure because ambiguity would make the timing lesson harder to inspect.

Notice also that validation scans numeric fields before the event loop. It can reject the entire fixture if a future row is invalid. That is separate from the causal decision rule applied to valid data. Earlier decisions are computed using only their own completed close. Do not confuse a preflight check that aborts a dataset with an indicator that reads a future price to decide a past action. The prefix test below checks the event trace on valid inputs, while the explicit validity tests verify the data gate.

For the exercise, copy your paper fixture into the main block. Compare the events line by line. Group them by bar index, then compare the closing event's target with the next opening on which a state change was needed. Keep the model numbers small. If the final result disagrees, point to the earliest event with unexpected phase, target, fill value or fee effect. That is more productive than changing a setting to make the end total happen to match.

Answer check. Ask the review feature to describe what the final target means if it differs from the ending model state. Include the last two chronological events. The correct explanation is about the missing opportunity for a later opening within the fixture, not a special rule to execute the target immediately.

Lesson 5: Test event timing as well as arithmetic

Causality test: Previous close → Next open → No same-close fill.
Causality test: Previous close → Next open → No same-close fill.

Save this file as test_offline_backtest.py next to the program, then run python -m unittest -v. The standard unittest guide explains the runner and assertion methods.

Python
from decimal import Decimal as D
import unittest

from offline_backtest import Bar, run


def fixture():
    return [
        Bar(0, D("101"), D("105")),
        Bar(1, D("109"), D("100")),
        Bar(2, D("111"), D("106")),
    ]


class BacktestTests(unittest.TestCase):
    def test_orders_of_events_and_adjustments(self):
        result = run(fixture(), D("104"), D("1000"), D("2"), D("1"))
        self.assertEqual([(e.index, e.phase) for e in result.events],
                         [(0, "close"), (1, "open"), (1, "close"), (2, "open"), (2, "close")])
        fills = [e for e in result.events if e.kind == "model fill"]
        self.assertEqual([e.fill for e in fills], [D("110"), D("110")])
        self.assertEqual([e.cash for e in fills], [D("888"), D("996")])
        self.assertEqual((result.cash, result.held, result.marked), (D("996"), 0, D("996")))

    def test_last_decision_without_following_bar_remains_pending(self):
        result = run(fixture()[:1], D("104"), D("1000"))
        self.assertEqual([e.kind for e in result.events], ["decision"])
        self.assertEqual((result.held, result.final_target), (0, 1))

    def test_mark_is_not_a_fill(self):
        result = run(fixture()[:2], D("104"), D("1000"))
        self.assertEqual((result.cash, result.held, result.marked), (D("891"), 1, D("991")))
        self.assertEqual(len([e for e in result.events if e.kind == "model fill"]), 1)

    def test_valid_prefix_is_unchanged_by_later_data(self):
        prefix = run(fixture()[:2], D("104"), D("1000"))
        full = run(fixture(), D("104"), D("1000"))
        self.assertEqual(full.events[:len(prefix.events)], prefix.events)

    def test_rejects_missing_and_duplicate_bar_indices(self):
        for wrong in (Bar(0, D("109"), D("100")), Bar(2, D("109"), D("100"))):
            with self.subTest(wrong=wrong), self.assertRaisesRegex(ValueError, "contiguous"):
                run([fixture()[0], wrong], D("104"), D("1000"))

    def test_level_equality_is_not_above(self):
        report = run([Bar(0, D("100"), D("104"))], D("104"), D("1000"))
        self.assertEqual(report.final_target, 0)

    def test_unfunded_fixture_does_not_invent_cash(self):
        with self.assertRaisesRegex(ValueError, "cannot cover"):
            run(fixture(), D("104"), D("25"))

The exact chronology test detects a developer who fills at the decision close or reverses the ordering within a row. The marking test catches an extra release at the end. The prefix test checks that adding a valid later bar does not affect events already seen. It intentionally compares events, not final marks, because a later end date changes what “final” means even when all earlier actions were unchanged.

Try changing one assumption and relying only on a final total. Some changes cancel out and leave the same end number. An erroneous earlier acquisition and later release may offset each other in a synthetic example. That does not preserve the sequence, state or timing. Compare an expected event list as well as final values. Keep tests that show what information was used at each step.

Answer check. Give Quanty the test names without the implementation and ask which one would reveal an invented final release. Then run a deliberate mutation and confirm your answer. Restore the valid code afterward. A failing test is a diagnostic tool when you know what requirement it represents.

Lesson 6: Separate assumptions from comparisons

Comparison hygiene: Fixed inputs → One changed assumption → Compare traces.
Comparison hygiene: Fixed inputs → One changed assumption → Compare traces.

When you compare two hypothetical simulator policies, change one assumption at a time. Keep the data and target decision constant while changing the fee setting. Then restore the fee and change the adverse adjustment. If the test changes more than one policy at once, an unexpected outcome may have several plausible explanations. A short table of inputs, programmed assumptions and expected arithmetic makes it easier to tell which effect you are studying.

Do not rank or recommend an actual strategy from these figures. The example excludes liquidity, order restrictions, execution uncertainty, instrument rules, overnight events and other limitations. Even if a simulated number appears favourable relative to another model assumption, it tells you only about those synthetic inputs and instructions. A production or research workflow needs its own independently verified data, permissions, assumptions and review.

A different fill model may explicitly skip an unavailable opening or require separate criteria. If you design such a model, add cases that fail to fill and decide what happens to the pending target afterward. Does it persist unchanged, expire or get superseded by a later decision? These alternatives are meaningful algorithmic choices. The current exercise avoids them by requiring complete data and a single simple execution convention. That is deliberate scope, not approval to apply it elsewhere.

If you find yourself choosing a series of settings based on which outputs look impressive, pause and revisit the intended exercise. A test suite checks behaviour against a declared specification. A parameter comparison studies the effect of settings on data. These tasks have different goals. Preserve the original dataset and requirements in each experiment so another reader can reproduce what you changed rather than interpreting a selected output as a general finding.

Audit drill: Detect divergence early in a five-column trace

Make a ledger with index, event phase, expected target, applied model state and cash. Do not compress non-events into empty rows. A closing calculation can exist even when the next opening applies no state change. Use “no change” or separate entries so an independent reader can see that the rule was evaluated. The trace is more useful if it makes inactive steps explicit instead of leaving a space that might indicate a missing log.

Take a copy of the example and change the second close without changing the second open. Predict which events can change. The simulated fill at the second opening was determined by the first close, so it should stay the same. The second closing decision and third opening outcome may change. This exercise gives a direct causal check distinguishable from a test that simply judges the final cash after both events.

Next change the second opening while leaving all closes unchanged. The timing and targets should be stable, but the modeled cost of the state change may differ. Follow the resulting cash value through the subsequent entries. If your implementation changes an earlier target as a side effect of updating a later opening, the trace will reveal a deeper problem than a fee calculation. Test both changes because they expose different points in the model.

If another person reproduces the tests, ask them to explain the first differing field before trying to fix the table. A changed target points toward the rule input. A changed fill with the same target may point toward the assumed opening or adjustment. A changed cash value with identical fills may point toward fees or repeated accounting. The code is small enough that each category has a place. In larger systems, a concise diagnostic record serves the same purpose when a printout contains dozens of values.

Audit drill: Document what “complete” will mean in the next version

The contiguous index contract says every row between zero and the end is present. It does not say the file began at the real beginning of a venue session or contains every interval the venue should have offered. It is a local validation condition chosen for these invented files. If a later project needs session-aware validation, define an independent expected schedule first and decide how to represent intervals inside, outside or missing from that schedule. Do not let the simulation infer the schedule from whatever the input happened to contain.

Make a separate checklist for scenario preparation. Include the enrolled instrument identifier, the time convention, the allowed date range and the first and last expected interval. Here the symbol is only a hypothetical label and there is no real session calendar. In a future project, use the provider and venue's documented rules and retain the source date alongside the assumptions. These choices are not portable between all datasets or markets.

Then make one fixture that passes this course but fails your proposed expanded contract. For example, a three-row file may start at zero and contain consecutive indices even though it represents only the middle of a longer expected sequence. The expanded contract can refuse it without invalidating the original exercise. A good test demonstrates the distinction and records why you are adding the requirement. It does not treat a narrower course as if it were already a complete trading or risk system.

Answer check. Ask whether converting missing intervals into a continuous index would prove completeness. It would not: the operation could hide the missing evidence unless the dated rows were checked first. Record the source verification and simulation input as separate steps. They are separate questions even if a future application displays both in one report.

Audit drill: Compare scenarios without moving the reference input

Give your baseline scenario a short name. Write down the fixture, the target rule, the opening-fill assumption, the initial cash, the fee and the adjustment. Now copy the fixture name into a second experiment and change only the fee. A practical record has one column for the variable you changed and one for the outputs you expected it to change. Here a fee change may alter cash but should not alter completed close values or the target decisions in a case that still has enough cash. That is a falsifiable expectation.

Include a separate test that exposes the cash boundary. If a change makes a proposed model acquisition unaffordable, your experiment will fail instead of producing a final result. This is not a signal to skip the test or reduce the fee until the experiment runs. The failure is an outcome of the explicitly scoped model. Record the requirement and decide separately whether the next model should handle a rejected state change as an event. Doing so changes the state machine, not merely the display.

Now change only a closing value so it equals the threshold exactly. The exercise uses strictly greater than, so equality sets a target of zero. A conditional statement using greater than or equal would behave differently, and the difference first appears at the closing decision. Verify that any effect on a fill is delayed until the next opening. A test of an exact boundary can be more revealing than comparing several cases comfortably on either side of the threshold. This boundary also protects you from changing a user's wording when you translate their own rule.

Repeat the experiment with an empty input and an input containing only the first bar. The first makes no decision and leaves cash untouched. The second makes one decision but cannot apply it. If both return the same ending cash, that does not make their states equivalent: the second result has a pending target and an event trace. Keep the distinction in any report you make from the code. A reader should be able to tell whether an absence of simulated changes means the system saw no information or simply had no next opportunity.

Answer check. Give the exercise reviewer the five-column experiment record rather than an aggregate total. Ask which fields are invariant on a cash-eligible fee change and why those invariants no longer imply a complete run after the affordability failure. You want a testable scope statement, not a claim that the code selects a useful fee.

Audit drill: Debrief a result without turning it into advice

A notebook can be technically correct and poorly communicated. Ask what a reader might infer if you show only the final marked number. They may not know it includes a fictional remaining unit, relies on an assumed fill or uses a fee selected to teach arithmetic. Add the source status, assumptions and timing before the summary. Put the end number after the event trace. Label the exercise data as fictional on every copy so the evidence is not mistaken for a claim about real performance.

Draft a short debrief in three sentences. First state what behaviour the test established, such as “the close of bar zero determines at most a fill at the opening of bar one.” Second say what was assumed, such as “each simulated state change uses an invented next opening and an explicitly specified adjustment.” Third state the limit: “This does not tell us whether a real order would have filled or whether the rule would be suitable.” These claims stay tied to the evidence.

Now read your debrief with the code closed. Can a reviewer locate the case that supports each claim? Can they identify which data and settings were fictional? Could they mistake the summary for an order record or a recommendation? If the explanation depends on knowing an unexplained abbreviation or an internal function name, add a plain-language label. None of this requires expanding the example beyond a short fixture.

If you publish a separate educational scenario later, include a note about how you selected the data and why the scenario is examined. Comparing outputs after changing a test case is not the same as evaluating an actual rule on independent data. Avoid choosing only the examples that make a number look favourable. Keep failures that help readers understand the boundary conditions such as incomplete data, equality and missed opportunities. In this course those failures are part of the learning output, not embarrassing exceptions to delete.

Capstone: Prepare an evidence packet you can reproduce

Include your exercise specification, chronological fixture, expected events, code, tests and one note about the limitations of the model. Report the time convention, who defined the synthetic target, when information became visible, which source value was used at each simulated state change, how the fee and adjustment were applied, and which final decisions remained pending. Mark the file as fictional. It should not be mistaken for a broker report or executable order instructions.

Re-run the program in a separate terminal. Compare each event and the output summary against your written fixture. Repeat once with the last row removed to test the earlier prefix. Ask a reviewer to identify which one of your tests would break if the simulation filled a target too soon. If that test cannot be found, add it before claiming the course exercise is complete.

If you use Quanty, share one small synthetic comparison, your intended rule and the first mismatch. Ask it to explain the gap rather than optimise the outcome or decide whether to trade. You can do the entire exercise on paper and in a local terminal without contacting market services. Use the trading coding curriculum to find the separate parity lesson when you need to compare a user-written rule against another implementation.

FAQ about this course

Is the final mark the same as cash?

Not in this simulation when the ending state holds the fictional unit. The mark includes the last closing value of that unit, but no state change or transaction is assumed solely to display it. The result records ending cash, held units and marked value separately.

Does a green ledger test prove that a real transaction could have filled?

No. It proves the fixture produced the fictional event sequence and arithmetic you specified. It does not establish availability of an execution, market prices, permissions, liquidity or real results.

Why is the last target separate from ending state?

The last target is calculated at a completed closing point. The exercise can apply it only at a subsequent opening. If there is no subsequent bar in the fixture, the target remains pending. Showing it separately makes that boundary visible.