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
- Calculate returns and rolling averages
- Distinguish a current average from the last value available at the decision time
- 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 ↓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.
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.
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.
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.
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.
Points follow the order in the example. See the table for exact values.
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)
Try the calculations
Use the values in each question. Enter amounts and percentages in the requested units, including a minus sign where needed.
Explain your reasoning
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.
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.