You need Python 3.10 or later, a text editor and the ability to run a file offline. If input validation is new, start with Python basics for traders. If candle ordering, timestamps or incomplete inputs are new, read market data and candles. This lesson deliberately assumes the sequence was audited earlier, describes how missing inputs are handled, and uses only fictional values.
The course format is a lesson, an exercise and an answer check. Keep a table of expected results next to the code. Quanty exercise review (beta) can be a second reader for an isolated mismatch, but you can complete all the checks without it. The full sequence is at learn to code for trading.
Lesson 1: Decide what one row means
An indicator is a function of specified data under a specified convention. Agree on both before writing the function. For this exercise a single input is a finite decimal closing value from a completed interval. The list is in chronological order. No missing placeholder is allowed in the input. A real implementation may choose different internal representations, but it should be able to say what it reads, when each value becomes available and what happens on missing data.
A single scalar calculation behaves differently from a time-aligned series. The first Python course calculated one average from the latest values. Here the output has the same length as the input. Position zero belongs to the first close, position one to the second and so on. A missing output at an early position says that a value is not yet defined, not that the indicator equals zero. This distinction matters when results are joined to a table: if you drop two missing early outputs and forget to drop two input rows, every pair will have a wrong timestamp.
Set an exact tiny case. Take four closes, 10, 13, 16 and 19, with a period of three. The first two positions have no three-value average. The third position sees only 10, 13 and 16, giving 13. The fourth sees 13, 16 and 19, giving 16. Write the expected output as four positions, not just the two numbers. If a later chart shows 13 beside the second input, the arithmetic might be correct while the alignment is wrong.
For the exercise, change the first close to 7 and leave the other three unchanged. Predict which outputs change. Under this convention the first defined average changes, but the second one does not. Both early positions remain undefined. Check the explanation by writing the exact window each result uses. When you later use more than four rows, this habit catches a surprising number of off-by-one mistakes.
Answer check. Show Quanty four fictional inputs and your four expected positions. Ask for an explanation of the first supported index and what the missing markers mean. A helpful answer should make the relationship to window length explicit. Reject a suggestion to use zero in place of a missing value unless your documented convention calls for that different behaviour.
Lesson 2: Build a simple moving average you can check
The simple moving average in this lesson assigns equal weight to each value in the last full window. Add the values and divide by the number of inputs in the window. The formula is not difficult; the implementation decisions around it deserve attention. If the period equals the length of the list, exactly one value is defined. If the period is larger than the input length, none is. A period of one returns each input value unchanged. We will test all three cases.
There are at least two reasonable ways to implement the arithmetic. The clearest beginner method repeats the sum for each full window. An efficient variant holds a rolling total, adds the incoming value and subtracts the outgoing one. These methods should agree for the small Decimal examples in this course. In other numeric systems or on long inputs, differences in rounding or accumulation order can become visible. Do not replace a transparent implementation with a faster one and assume agreement without a comparison test.
The example uses the straightforward version because you can trace each slice independently. For output at index i and a period p, the included indices are i - p + 1 through i. Python's slice excludes its right boundary, so the slice stops at i + 1. Keep the inclusive position you mean and the exclusive boundary the language uses as separate ideas. Using i as the stop would omit the current close and shift the window, even if the program returned a number at the correct index.
Try a varied sequence rather than a constant sequence when checking alignment. A constant set would give the same average under several incorrect window positions. Choose one case where the most recent value is outside the earlier range and write down the result for each successive window. This gives you evidence that the function uses the correct positions without treating an extreme fictional value as market guidance.
For the exercise, use [5, 8, 11, 17, 20] with periods one, two and three. For each period, write the number of undefined values, the first defined value and the final value. Then add a sixth value and compare the original five output positions. If any earlier result changes, the implementation depends on an input that was not yet available. That is a separate failure from a wrong average.
Answer check. Ask which test would catch a start boundary shifted by one. Include both a constant sequence and a varied sequence. The varied values should expose a wrong window even if the constant series does not. The answer is more useful when it says why the case distinguishes the two implementations.
Lesson 3: Make exponential smoothing conventions explicit
An exponential average is a recursive calculation, so it needs a starting value. Different tools can make different starting choices. Some start with the first available close, while others wait for a full period and take its simple average as the seed. The two outputs need not match, particularly near the start. Comparing them requires knowing the seed, input period, update coefficient, arithmetic precision and data boundaries on both sides.
This course uses the full-window simple average as the seed. The first defined output is at index period - 1. Each subsequent value uses the latest close and the preceding smoothed result. The coefficient for this exercise is 2 / (period + 1). This is a mathematical convention here, not a recommendation to choose a particular period. See the NIST explanation of single exponential smoothing for the recursive weighting idea and discussion of initialisation; the source's forecasting indexing need not match this time-aligned series.
A period of three gives a coefficient of one half. For closes 10, 13, 16 and 25, the seed is 13. The next smoothed value is half of 25 plus half of 13, which is 19. The simple average at that position would use 13, 16 and 25, giving 18. Seeing different values does not identify a defect: each transformation has a different definition. Label the output clearly instead of comparing mismatched column headers with the same name.
For the exercise, recompute that example with a seed equal to the first close. Write the output for the first three positions using coefficient one half, then compare it with the course's output on those indices. This is a comparison of definitions. It is not a claim that a different result is inferior or will affect any scenario in a particular way. An exported chart may intentionally use a different warm-up. To reproduce it, match the documented definition rather than guessing which result looks right.
The procedure also raises a useful precision question. The Decimal coefficient for periods other than the simple example may be a repeating fraction, so the calculation depends on the Decimal context precision. The reference program uses a fixed local precision and rounding mode for its arithmetic rather than inheriting an arbitrary setting from the calling application. It does not claim to calculate every fraction exactly. For formal behaviour and available rounding modes, see the Python decimal documentation.
Answer check. Give Quanty the same inputs and two written seed conventions. Ask it to explain why the first supported position can differ without changing either input. Ask for a small test that would distinguish a different seed from an off-by-one index. A useful test examines early positions rather than comparing one rounded value at the far end.
Lesson 4: Keep related transforms aligned
The third exercise subtracts the simple average from the exponential average at the same input position. It does not use the result as a signal or attach words such as bullish and bearish to its values. The difference just helps you compare two definitions on the same fictional data. A numeric zero says the two defined values agree there; it does not say either is missing. If either value is undefined, the result is undefined.
Require the two arrays to have the same length. Python's zip usually stops at the shorter iterable, which can make a mismatch seem to work silently. In an indicator chart, silent truncation can leave the output missing the most recent row. Refuse different lengths before pairing. In a real timestamped table, equal lengths alone would not prove correct alignment; you would also require matching timestamps or an explicit join policy. Here the two series come from the same ordered input, so the exercise compares positions.
For the exercise, make a three-element pair where both values are missing at the first position, one is missing at the second, and both defined at the third. Predict the output for the two missing cases and for the defined case. Then shorten one list and record the exact error you want, rather than expecting the program to fill it. Finally choose two equal defined results to confirm that zero remains a numeric output. This makes the representation convention visible.
Answer check. Ask what error a naive zip conceals and how to test that zero is not mistaken for missing. A concise explanation should say that Python values are compared to None by identity in this use, so a false-like number such as zero still counts as defined.
Lesson 5: Implement the three series
Save this example as indicators.py. The parser validates the whole input. Use strings that can be converted to finite positive Decimals. No network service or real price is involved.
from decimal import Decimal, InvalidOperation, ROUND_HALF_EVEN, localcontext
def read_closes(raw: list[str]) -> list[Decimal]:
result = []
for ix, item in enumerate(raw):
try:
value = Decimal(item.strip())
except InvalidOperation as error:
raise ValueError(f"close at index {ix} is not decimal") from error
if not value.is_finite() or value <= 0:
raise ValueError(f"close at index {ix} must be finite and positive")
result.append(value)
return result
def check_period(period: int) -> None:
if type(period) is not int or period <= 0:
raise ValueError("period must be a positive integer")
def sma(raw: list[str], period: int) -> list[Decimal | None]:
check_period(period)
closes = read_closes(raw)
out = [None] * len(closes)
with localcontext() as ctx:
ctx.prec = 28
ctx.rounding = ROUND_HALF_EVEN
for i in range(period - 1, len(closes)):
out[i] = sum(closes[i - period + 1 : i + 1], Decimal(0)) / Decimal(period)
return out
def ema(raw: list[str], period: int) -> list[Decimal | None]:
check_period(period)
closes = read_closes(raw)
out = [None] * len(closes)
if len(closes) < period:
return out
with localcontext() as ctx:
ctx.prec = 28
ctx.rounding = ROUND_HALF_EVEN
alpha = Decimal(2) / Decimal(period + 1)
value = sum(closes[:period], Decimal(0)) / Decimal(period)
out[period - 1] = value
for i in range(period, len(closes)):
value = alpha * closes[i] + (1 - alpha) * value
out[i] = value
return out
def difference(left: list[Decimal | None], right: list[Decimal | None]):
if len(left) != len(right):
raise ValueError("series lengths differ")
with localcontext() as ctx:
ctx.prec = 28
ctx.rounding = ROUND_HALF_EVEN
return [None if a is None or b is None else a - b for a, b in zip(left, right)]
if __name__ == "__main__":
closes = ["10", "13", "16", "25"]
simple = sma(closes, 3)
exponential = ema(closes, 3)
print("Index | Close | SMA | EMA | Difference")
for i, values in enumerate(zip(closes, simple, exponential, difference(exponential, simple))):
print(i, *values, sep=" | ")Walk the example from the parser to the final print loop. Both indicator functions create an output list of the same length as the input and fill it from the first defined index. That means an empty list produces an empty result for a valid period. It does not mean the function succeeded in finding a price. If the source sometimes has no records, the caller decides whether an empty calculation is acceptable. The numerical function should not make up records to satisfy it.
The code assumes string input and does not sanitise arbitrary objects. A real program accepting JSON, spreadsheet cells or user entry should put schema and size validation at the ingest boundary. The exercise shows finite and positive checks because they matter here, not because they replace input verification in every application. Use synthetic values when testing and keep screenshots of personal accounts out of your practice notes.
For the exercise, edit the main block to display a second period without changing either function. Label the output so that you can tell which period produced each series. Then add a price you previously rejected in a separate run. Confirm that the function fails before the display suggests there is a valid output. Choose an accepted positive value and restore the four-price hand calculation when you finish.
Answer check. Ask which responsibility should change if a new interface supplies Decimal values rather than text. The expected answer distinguishes parsing from the arithmetic. Adapting the parser is an architectural option; rewriting the indicator expression to accommodate unchecked values is not a requirement. Keep one clear input type in the examples.
Lesson 6: Test the calculations and their limits
Save the test file below next to the program and run python -m unittest -v:
from decimal import Decimal
import unittest
from indicators import difference, ema, sma
class IndicatorTests(unittest.TestCase):
def test_reference_rows(self):
data = ["10", "13", "16", "25"]
simple = sma(data, 3)
exponential = ema(data, 3)
self.assertEqual(simple, [None, None, Decimal(13), Decimal(18)])
self.assertEqual(exponential, [None, None, Decimal(13), Decimal(19)])
self.assertEqual(difference(exponential, simple), [None, None, Decimal(0), Decimal(1)])
def test_short_and_empty_examples(self):
for method in (sma, ema):
self.assertEqual(method([], 3), [])
self.assertEqual(method(["10", "11"], 3), [None, None])
def test_period_one(self):
raw = ["1.25", "2.75", "1.01"]
for method in (sma, ema):
self.assertEqual(method(raw, 1), [Decimal(v) for v in raw])
def test_early_values_do_not_change_when_a_close_is_added(self):
raw = ["5", "8", "11", "17", "20"]
for method in (sma, ema):
self.assertEqual(method(raw, 3), method(raw + ["100"], 3)[:-1])
def test_bad_period_and_bad_old_close_are_visible(self):
for method in (sma, ema):
with self.assertRaisesRegex(ValueError, "period"):
method(["100"], True)
with self.assertRaisesRegex(ValueError, "index 0"):
method(["NaN", "10", "11", "12"], 3)
def test_compare_rejects_different_lengths(self):
with self.assertRaisesRegex(ValueError, "lengths differ"):
difference([Decimal(2), None], [Decimal(1)])A test for values on a tiny sequence gives exact evidence about the first few positions. A separate test that compares earlier values with and without a later close checks the direction in which information flows. If a transformation unexpectedly depends on that later close, the future changed the past as far as the calculation is concerned. Passing this test does not prove an arbitrary larger pipeline has no such dependency; any join, aggregation or execution timing must also be tested on its own.
Try mutation testing by editing one line temporarily. Replace the simple-average slice with one that stops at the current index instead of just after it. Run the tests and notice which are sensitive to that change. Restore it before trying a second mutation that makes the exponential average start with the first close. If a test still passes, ask whether it was intended to cover the modified behaviour. A green test unrelated to a mutation is not evidence for or against the change.
Now test an additional case on your own. Use large and small decimal fractions so you can show what changes when precision changes. The aim is not to rank floating point and decimal arithmetic in the abstract. It is to expose the boundary that your own contract chooses. Record whether you compare exact values, rounded display values or a documented tolerance. In a cross-platform parity exercise, choose the rule in advance before seeing the discrepancies.
Answer check. Ask for one direct test of an input rule and one direct test of an output property. “Returns a number” is not enough for the second. A more useful test checks the length, the first defined position and the expected value after a known change. Give the reasoning and run the test yourself.
Capstone: Build a four-column parity report
Make the report with the input index, simple average, exponential average and difference. Include the close value in a separate input note or as an additional column. For at least five fictional inputs, hand-check the first defined row and one later row. Include an early index in the report and print a dash or another explicit marker for undefined values. Keep the raw data and round only a separate display string if you choose to round.
Now ask whether another person could reproduce the numbers without your software. Give them the input sequence, the period, the seed convention and the amount of precision you displayed. Have them calculate one row using the previous row if needed. If they get a different result, compare the seed and first differing index before changing rounding or replacing the reference values. The reason for the discrepancy is part of the work.
Write a note about what the report still leaves out. It does not model execution, market costs, test a real dataset or say anything about a profitable rule. It shows how numeric features can be produced and verified. The separate technical indicators guide explains broader concepts, while this coding course concentrates on arithmetic and tests. Return to the trading coding curriculum for the next lesson.
Review drill: Find the first disagreement, not the largest disagreement
Suppose one spreadsheet produces a simple average of 13 on the third row and a Python program produces 13 on the fourth row. Before comparing large data exports, reduce the problem to the first four rows. Copy each sequence into a little table and label the timestamp or index, the close and the resulting value. Check the position, not just whether the number appears anywhere. An output can look plausible and still belong to the wrong interval.
If the numbers disagree at the correct position, write the exact window each side used. An earlier value can enter through a long lookback, an unshown seed or an earlier input record. A later value can enter if a developer used a centred window. Both differences change the calculation, but they represent different mistakes or intentions. A centred rolling average can be valid in retrospective analysis and still invalid for a chronological test that is supposed to represent what was known then. Ask which interpretation a given program is built to support.
Select two traces for your review. In the first, change an early value outside the final simple window. In the second, change the most recent value. A correct simple average at the final row ignores the early change and responds to the recent change. The exponential series may still depend on the early change because its previous state follows from earlier states. The expected effects distinguish the two mathematical definitions without appealing to how the plot looks.
Now compare the traces with your program. Record the first mismatch and describe exactly why it matters. It is possible to have a later value that accidentally agrees after several wrong earlier outputs. A test that examines only the final row could miss the earlier disagreement, while a mismatch late in the series may be the amplified effect of an earlier small difference. Tracking the first disagreement helps isolate the cause and makes a bug report reproducible.
Answer check. Use Quanty exercise review (beta) to propose the smallest test that distinguishes an offset error from a different mathematical seed. Include one small dataset, the two observed output positions and the chosen definition. Avoid telling it which implementation you suspect; you are testing whether the evidence points to that conclusion.
Review drill: Round the display, not the evidence
A simple report might display two decimal places because that is easier to read. Display precision is not the same as the precision used throughout a recursive calculation. If you round each stored exponential average before using it in the next row, the state is different from a calculation that preserves intermediate precision until display. The two approaches may show the same numbers on a short example and still diverge on another one.
Choose fictional values that need more than two places, such as 1.012, 1.039 and 1.074. Compute a new result in the original program and then format each defined value for a two-decimal display. Compare that with a modified version that rounds intermediate state and uses that rounded state for later computation. Keep the initial seed rule unchanged; otherwise you cannot tell which change produced a difference. Put the exact intermediate values or their documented precision beside the displayed values in the review note.
Disagreement does not automatically mean you must change one tool to match the other. A display may intentionally round while an exported series stays more precise. A specification might ask for prices represented in exact units or for a tolerance on a long, floating-point transform. Be clear about which values are data, which are internal state and which are presentation. For basic exercises, exact small Decimal examples are a good starting point. For comparisons across tools, agree on the expected rounding convention, numeric precision and any tolerance before seeing the results.
If you use a tolerance in a test, state why it exists. A tolerance that hides an entire tick, one time interval or a different calculation is too weak for a parity check meant to expose that difference. Conversely, insisting on identical strings can make numerically equal values look different when one displays fewer trailing zeros. A useful check first compares defined versus undefined positions, then compares numeric results under the agreed rule, and only then compares formatting if formatting is itself a requirement.
Write two fixtures. One should demonstrate two equivalent numbers displayed differently. The other should demonstrate that a larger real difference cannot pass under your chosen tolerance. Run both before accepting a proposed change. This review drill does not establish any convention for handling live prices; it clarifies how to compare results you already have.
Review drill: Test the update property using multiple periods
Pick three periods that expose different boundaries: one, three and one greater than the length of your sequence. For each, calculate the number of defined positions without using the program. With period one, both definitions immediately return every value. With period three, the first defined position is index two. With a period larger than the sequence, no position is defined. This exercise checks what the program does when an apparently ordinary setting is not meaningful for the amount of data supplied.
Start with an empty list and append your synthetic closes one at a time. After each append, calculate and save the results. At the end, compare those results with the corresponding prefixes of the batch output. This checks that the batch implementation behaves consistently when an input becomes visible only at its own time. It does not distinguish two implementations that use different but causal definitions; you still need precise reference rows, such as the hand-calculated seed and the immediately following exponential update.
Then remove one close from the middle deliberately. The list remains ordered, but it no longer represents the same intervals. The indicator function cannot infer this from the values because it receives no timestamps. The prior data course's audit is a dependency, not a check the signal arithmetic has to guess. If you decide to accept missing intervals in a new project, document how the gap changes a rolling window and a recursive state. Possible choices differ, and the precise effect must be tested rather than silently ignored.
One exercise is to carry a small timestamped audit report alongside the list. Keep a flag saying whether the rows are complete under the source contract. Do not change the indicator function to silently slide over a missing record. If the audit did not pass, let the calling program refuse to calculate or explicitly choose an alternate policy. This design makes a missing-input issue distinguishable from a calculation issue that appears only because your previous step discarded an interval.
Answer check. Ask for the two changes you would need if you made period length depend on elapsed clock time rather than the number of rows. A useful answer should mention that timestamps and the definition of each window must become part of the interface. It should not assume that a list of values already carries enough information. Keep the exercise as a design note; the reference program intentionally uses a count of validated, completed rows.
FAQ about these exercises
Why not print zero during the warm-up?
Zero can be a defined result in a difference series. A missing marker says the definition is not supported by enough input. Conflating them means a downstream reader cannot distinguish a numeric result from an interval that lacked data. Align the outputs by position and decide where undefined values belong before rendering.
Why did my chart application return a different first EMA?
The examples use a particular seed, period, input alignment and precision. Compare those parts of the definition first. Then isolate the first row where the outputs diverge. A late mismatch alone may give little evidence about the cause. A chart may use more historical input than is visible, or use a different documented seed.
Do these output definitions tell me what to trade?
No. The numbers compare mathematical transforms on invented data. These examples do not pick instruments, enter or exit positions, or evaluate which strategy is profitable. Use the tests to check that a program implements the calculation you described, not as an argument for trading.
Related
- Learn to code for trading: the full coding curriculum.
- Market data and candles: check what each input row represents.
- Technical indicators: a separate conceptual overview.