q.Quantitative TradingEnglish course · Lesson 12 of 24Course home

Lesson 12 / Reproduce Calculations in a Spreadsheet and Python

If you change one input, which outputs should change?

Put the data definitions to work in a reproducible calculation. Use five closing prices to calculate results by hand, then compare the page, a spreadsheet, and standard Python.

What you will learn

  1. Calculate returns and rolling averages
  2. Distinguish a current average from the last value available at the decision time
  3. Save the data, code, and verification steps

Allow about 30–45 minutes. The exercises use fictional data. The page checks structured answers in your browser. Export your work before refreshing.

Start with the concepts ↓
Concept 01

Start with five CSV rows

The columns are day,close, with D1 100, D2 102, D3 101, D4 104, D5 103. The D labels give the order of the observations. Prices are in fictional yuan, with no dividends, external cash flows, or fees.

With real data, parse timestamps, check unique keys, and sort first. Text sorting places D10 before D2. If a join increases the row count, check for a one-to-many match.

Concept 02

Each column becomes available at a different point

Period return = current close ÷ previous close − 1. The three-period average includes the current close. Leave its first two rows blank until there are three observations. Shift that column down one row for the previous period's average.

Before the D4 open, the latest three-period average is D3's 101. The average of 102.3333 that includes the D4 close is unavailable until D4 closes. Using an accurate value too early still introduces an error.

Concept 03

Perform the same calculation in a spreadsheet and code

Put day in column A and close in column B, with the first observation in row 2. Enter =B3/B2-1 in C3 and fill down. Enter =AVERAGE(B2:B4) in D4 and fill down. Enter =D4 in E5 and fill down. Leave C2, D2, D3, and the first three lagged values blank.

The Python example reads the same string with the standard CSV library and outputs returns, three-period averages, and lagged averages row by row. The page calculates independently in JavaScript. Copy the example to a local Python environment to run it.

Concept 04

Change one input to test the calculation

If D5 becomes 106, only the D5 return, its current moving average, and the cumulative return should change. D5's previous moving average uses D2–D4 and should stay at 102.3333.

Check AI-generated code for the same things as any other code, including input definitions, boundaries, timing, and accounting. Save the command, version, and hand-calculated expectations so others can reproduce the results.

Experiment · Predict the outcome, then change one input

Reproduce Calculations in a Spreadsheet and Python experiment

D5 defaults to 103. Compute the D3 three-period average, then change D5 to 106. Check that the previous-period average column is unaffected by the later value.

Use five ordered fictional closing prices. The first four stay at 100, 102, 101, 104. Change only the final price. Blank values indicate insufficient observations.

Python reference example

Uses the Python 3 standard library. Save as data_example.py and run python3 data_example.py. Run the code separately with the shown defaults or with your own inputs to cross-check results.

"""Five fictional closes with no cash flows or market connections."""
import csv
import io

CSV = """day,close
D1,100
D2,102
D3,101
D4,104
D5,103
"""
rows = list(csv.DictReader(io.StringIO(CSV)))
prices = [float(row['close']) for row in rows]
assert len({row['day'] for row in rows}) == len(rows)
assert all(p > 0 for p in prices)
previous_average = None
for i, price in enumerate(prices):
    ret = None if i == 0 else price / prices[i - 1] - 1
    average = None if i < 2 else sum(prices[i - 2:i + 1]) / 3
    print(rows[i]['day'], price, ret, average, previous_average)
    previous_average = average
print("Cumulative price return", prices[-1] / prices[0] - 1)
Practice with fixed inputs

Try the calculations

Use the values in each question. Enter amounts and percentages in the requested units, including a minus sign where needed.

Knowledge check

Explain your reasoning

1. At the D4 open, can you use a moving average that includes the D4 close?
2. How should you represent a three-period average with fewer than three observations?
3. What should you check if changing D5 changes a D4 result?
4. If the page displays a Python example, has the browser run it?

Record your work

Stage assignment

Stage 3 deliverable. Save a reproducible calculation note. The page export includes the current data and sample code.

Submit your calculation table

Use these closing prices: D1 = 100, D2 = 102, D3 = 101, D4 = 104 and D5 = 106. Calculate the results in a spreadsheet or Python and paste them below. Enter return_pct as a percentage value. ma3 includes the current close in its three-period window, and lag3 is the prior period's ma3. Leave cells blank or enter NA when history is insufficient. Keep at least four decimal places.

Complete the questions below before trying the optional writing exercise. Use the fixed inputs here, even if you changed the experiment above. Enter numbers in the units shown and keep at least two decimal places where needed. Follow the specified precision for tables. You can check one answer at a time or all answers together.

1. Check returns and averages row by row

Paste comma-separated CSV or tab-separated values copied from a spreadsheet. Include the header and rows D1–D5 in the column order shown below. Omit thousands separators. Leave missing cells blank or enter NA.

day,return_pct,ma3,lag3
D1,,,
D2,,,
D3,,,
D4,,,
D5,,,

Reference answer (try the question first)
2. Which average is available at the D4 open?
Reference answer (try the question first)
3. If you change D5 to 110, should the averages through D4 change?
Reference answer (try the question first)

Save your homework to export these results. Check again after changing an answer. Optional writing and self-assessment are ungraded. Save your work before refreshing.

Optional writing (ungraded)

Writing guidance and self-review

Record the inputs, rules, results and open questions in each field. You can cite the earlier calculations and experiments as fictional examples. Tie each conclusion to specific data or events.

Use the checklist to review your own writing. Use evidence from the study to evaluate the strategy.

Save the experiment, the run log, your first and current checks, written work and self-review. Export before refreshing or closing the page.