You need Python 3.10 or later and a text editor. Start here if you can run a file, pass arguments to a function and read a basic test result. If those steps are new, complete Python Basics for Traders first. Use only the fictional records printed below. They are not a depiction of an exchange schedule or prices from a real trading day.
Each lesson gives you a small contract to test. Learn the rule, change a fixture and compare the result with the expected output. Quanty exercise review (beta) is optional; use it to ask about a mismatch, not to certify the file or interpret a chart as a recommendation. The full sequence starts at learn to code for trading.
Lesson 1: A candle is a record with an interval
A candle summarises data over a defined interval, rather than describing everything that happened inside it. The open is the first value in the underlying sequence for the interval and the close is the last; the high and low bound the values recorded there. The volume field represents a quantity defined by the data source. It may mean something different for another instrument or dataset, so do not infer its unit from the column name alone. In this exercise it is a nonnegative integer count that belongs to the specified interval.
You cannot recover the path inside the interval from the four prices. The order in which a high and a low were reached is not encoded. Two underlying sequences can have identical open, high, low and close while visiting those extremes in different orders. Do not assume one path simply because a chart draws a wick. This is why the later simulation course will require stated assumptions before interpreting a bar as an execution opportunity.
The timestamp supplies context for those values. This file uses a beginning label: a record labelled 10:00 represents a practice interval that starts at 10:00 and ends before 10:05. A different source might label the same period 10:05 instead. If you join those rows with no conversion, apparently similar labels refer to different data. For a complete candle, the close cannot be known as a completed value until the interval ends. Do not let code act as if it knew the completed close at the beginning.
Practice on an example with opening price 100, highest 106, lowest 98 and closing price 103. Draw two fictional paths that respect those facts. Then draw a path whose last value is 104 and show which field it violates. There is no single correct path for the first task. The exercise is about identifying what a summary does and does not tell you. Use that distinction later when a test seems to prove more than its input supports.
Answer check. Give Quanty only the fictional prices and ask it why the high cannot be below both the open and close. Then ask why observing the high and low does not establish which came first. You want an explanation of the data contract, not an inference about sentiment or anything to buy or sell. Recheck both claims by drawing a minimal path on paper.
Lesson 2: Distinguish a clock reading from a moment in time
A timestamp without an offset can look complete while remaining ambiguous to a computer. It might be a clock reading supplied by a local venue, a clock reading in the system's current time zone or a mislabelled UTC value. The string alone cannot tell you which meaning is intended. The Python datetime documentation distinguishes aware objects, which carry offset information, from naive objects, which do not identify an unambiguous time by themselves.
The course requires each CSV timestamp to carry an explicit offset. Parse the timestamp and convert it to UTC before comparing rows. Keep the original row number for error reporting. For the examples, 10:00 at plus five hours and thirty minutes is the same instant as 04:30 UTC. The text differs but the normalised timestamp is the same. If both rows appear in a single instrument file they describe the same interval in this schema, not two independent samples.
Normalisation does not mean ignoring the original data source. In a real project record whether the source uses the beginning or end of the interval, how it encodes the offset, and what happens when data spans a clock change. An offset identifies a relationship to UTC at that moment. It is not a substitute for a named time zone if you need rules governing dates and transitions. See Python's zoneinfo documentation for time zones from the IANA database. This course avoids making those choices on behalf of an unknown dataset.
For the exercise, convert three times by hand before writing code: the 10:00 example above, 10:05 with the same offset, and a clock value with a zero offset. Put the result next to each original value. Then create a deliberately naive row, without a final offset, and explain why the program should reject it rather than pick your device's current offset. Finally describe what would go wrong if two teammates ran code that implicitly took the operating system's local time.
Answer check. Ask the optional exercise-review feature to compare an offset representation and its UTC equivalent after you compute them independently. If the answers differ, ask it to state the arithmetic and sign. Do not paste real identifiers, a calendar export or any source not intended for this exercise.
Lesson 3: Start with the smallest useful file
Use a text file called practice-candles.csv. Each row belongs to the same fictional instrument and each interval is five minutes. There is no symbol column in this exercise; do not join files from different instruments merely because their times align. The first line names the schema. Here is a valid example except for a deliberately omitted interval after the second line of data:
start,open,high,low,close,volume
2026-01-05T10:00:00+05:30,100.00,103.00,99.00,102.00,12
2026-01-05T10:05:00+05:30,102.00,104.00,101.00,103.00,15
2026-01-05T10:15:00+05:30,103.00,105.00,102.00,104.00,18Read CSV with the standard-library tool rather than splitting on every comma. The Python csv documentation describes its quoting rules and how to open a file with the right newline handling. The example uses DictReader so each field is assigned by name. It checks the header once, because a column that silently changes from start to time should not be treated as missing for hundreds of rows. It also detects a short record, an extra field and an empty required field rather than treating them as the same valid input.
A reader should not clean a file until it knows what a change means. A row with an extra delimiter can reflect a broken export, an unquoted decimal separator or a source with an additional column. Removing a value to make the lengths match could change a price without leaving an audit trail. Reject the row with a specific reason and keep its row number. A useful report distinguishes a parsing failure from a row that parsed well and then failed a domain check.
For the exercise, open a copy of the fictional file and add an extra field on the second data row. Then remove the final field on another row, and put a blank price into a third copy. Write down which row you expect the report to identify. After implementing the audit, verify that this mutation does not remove the explanation for any other failed record. If more than one field is invalid on the same row, this implementation reports the first issue found. You can expand the contract later if you need all row-level issues.
Answer check. Ask what difference the report should display between the wrong header and a single row with the wrong number of values. The former affects how every record is assigned and should stop the file; the latter does not prevent inspecting the remaining rows. Test both rather than treating the absence of a result as proof that one particular error occurred.
Lesson 4: Validate prices and volume without inventing values
Do not let an impossible price relationship pass just because every field is numeric. In this schema each price is positive and finite. The low may equal the high, and either may equal the open or close. A candle in which all four prices are equal is therefore valid. The low must not exceed either open or close, and the high must not be below either. A record can carry zero volume in this exercise; that fact alone does not contradict the chosen fictional schema. In a different feed, the producer's documentation might impose a different rule.
The program uses Decimal created from text for prices. This avoids changing the supplied values through a floating-point conversion before a comparison. It never rounds a value to make an invalid relationship look valid. For volume, str.isdecimal() accepts some Unicode digits. The example deliberately requires ASCII digits as part of the practice file format, so a non-ASCII but otherwise ordinary digit will be rejected. That is a schema choice, not a claim that one writing system cannot represent a number.
Try a record where the low and high are both 103 but the open is 102. The row fails even though all the numbers are finite and positive. Try one where high, low, open and close are 103 with zero volume. It passes. Finally try the strings "NaN", "Infinity" and a fraction in the volume column. They illustrate different invalid inputs. A test should show which invariant each one violates, not just count the number of rejected records.
For the exercise write three new rows with plausible labels and deliberately choose one boundary on each. Make the first row valid with a close equal to the low. Make the second invalid with a high below the close. Make the third invalid with a volume that is clearly not an integer. Record why each should pass or fail, and keep their timestamps distinct so the duplicate detector does not obscure the price conditions under test.
Answer check. Ask Quanty to reason through those examples using only your schema. If a suggestion says to replace an invalid high with the close, explain why this lesson treats automatic correction as out of scope. A reviewer can suggest an additional fixture, but any change to recorded prices must have a documented data policy and cannot be inferred from arithmetic alone.
Lesson 5: Audit the records and report gaps
The program below uses two groups: accepted rows and entries in issues. A first valid row at a timestamp is accepted for diagnostic purposes; later repeats are reported. A report with any issue is not a pass to use the file downstream. Choosing the first row only makes the rest of the inspection deterministic. It does not assert that the first record was the authoritative one.
The expected interval is fixed for the example. An interval start must align to a five-minute grid in UTC, and consecutive accepted starts in the file must be five minutes apart. Because the example assumes a single continuous practice segment, a gap is called out for review. In real data, a between-session break must not be treated as a feed failure: compare with the relevant market calendar, session rules and the source's definitions rather than demanding continuous bars across holidays or closures. This script does not encode those rules.
import csv
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import TextIO
STEP = timedelta(minutes=5)
COLUMNS = ["start", "open", "high", "low", "close", "volume"]
@dataclass(frozen=True)
class Candle:
line: int
start: datetime
o: Decimal
h: Decimal
l: Decimal
c: Decimal
volume: int
@dataclass(frozen=True)
class Issue:
line: int
reason: str
def parse_candle(line: int, row: dict) -> Candle:
if set(row) != set(COLUMNS) or any(
not isinstance(row[k], str) or not row[k].strip() for k in COLUMNS
):
raise ValueError("wrong number of fields or empty field")
start = datetime.fromisoformat(row["start"].strip())
if start.utcoffset() is None:
raise ValueError("timestamp needs an explicit offset")
start = start.astimezone(timezone.utc)
if start.second or start.microsecond or start.minute % 5:
raise ValueError("timestamp must align to the five-minute grid")
try:
o, h, l, c = (Decimal(row[k].strip()) for k in COLUMNS[1:5])
except InvalidOperation as error:
raise ValueError("invalid decimal price") from error
if any(not p.is_finite() or p <= 0 for p in (o, h, l, c)):
raise ValueError("prices must be finite and positive")
if not l <= min(o, c) or not max(o, c) <= h:
raise ValueError("open and close must be between low and high")
raw_volume = row["volume"].strip()
if not raw_volume.isascii() or not raw_volume.isdecimal():
raise ValueError("volume must be a nonnegative integer")
return Candle(line, start, o, h, l, c, int(raw_volume))
def audit(stream: TextIO) -> tuple[list[Candle], list[Issue]]:
reader = csv.DictReader(stream, strict=True)
accepted, issues = [], []
seen = set()
previous = None
try:
if reader.fieldnames != COLUMNS:
return [], [Issue(1, "unexpected CSV header")]
for row in reader:
line = reader.line_num
try:
candle = parse_candle(line, row)
except (ValueError, OverflowError) as error:
issues.append(Issue(line, str(error)))
continue
if candle.start in seen:
issues.append(Issue(line, "duplicate interval"))
continue
if previous is not None and candle.start < previous:
issues.append(Issue(line, "interval out of order"))
previous = candle.start
seen.add(candle.start)
accepted.append(candle)
except csv.Error:
issues.append(Issue(reader.line_num, "malformed CSV record"))
if not accepted and not issues:
issues.append(Issue(1, "no data rows"))
ordered = sorted(accepted, key=lambda record: record.start)
for left, right in zip(ordered, ordered[1:]):
if right.start - left.start > STEP:
issues.append(Issue(
right.line,
f"gap after {left.start.isoformat()} before {right.start.isoformat()}",
))
return ordered, issues
if __name__ == "__main__":
with Path("practice-candles.csv").open(encoding="utf-8", newline="") as source:
candles, issues = audit(source)
for issue in issues:
print(f"line {issue.line}: {issue.reason}")
print(f"{len(candles)} accepted rows; {len(issues)} issues")
raise SystemExit(1 if issues else 0)The program compares two different notions of order. It uses original input order to report that a valid, non-repeated row arrived earlier than its immediate predecessor. It sorts the accepted records by their normalised timestamps only after preserving the issues, so it can check for gaps even when the file was unordered. If you remove the reported order check and see only the sorted records, you would lose evidence that the raw file violated its contract. One visual inspection of a sorted list is not equivalent to an audit of the ordered input.
The gap check occurs after bad rows are removed. A rejected row may therefore cause two findings: the field-level problem on that row and an interval missing between two accepted rows. Those findings serve different purposes. The first helps a data owner identify the source of the rejected record. The second tells downstream logic it cannot assume a complete sequence. Do not replace the missing interval with a synthetic bar unless a separate, documented process makes that choice explicit.
For the exercise add the missing 10:10 record from the example, choosing fictional values between a reasonable high and low. Add it first in the wrong position. The gap should be gone, but the file should still fail because the record is out of order. Move it to the right place and run again. Then duplicate the 10:10 row using a UTC timestamp. The duplicate should be found because labels are normalised before comparison. This exercise demonstrates why the order, gap and duplicate conditions are independent.
Answer check. Share the four synthetic schedules, the report and the exit status, not an exported data file. Ask which detection rule supports each issue. If the reviewer says a successful printout means the script passed, point out the explicit exit status. The report is useful even when it refuses the file.
Lesson 6: Test parsing and auditing separately
Test a representative line directly if you are testing the timestamp or price rules. To test the entire report, construct tiny CSV inputs with StringIO so the test does not touch real files. Keep one invalid condition per ordinary test. If every fixture contains several invalid conditions, a new error can appear hidden behind an earlier rejection. Use an additional combined case only after straightforward cases identify the pieces.
Save the previous example as candle_audit.py. Save this file next to it as test_candle_audit.py. Run python -m unittest -v.
from datetime import timezone
from io import StringIO
import unittest
from candle_audit import audit
HEADER = "start,open,high,low,close,volume\n"
def row(time, prices="100,103,99,102,12"):
return f"{time},{prices}\n"
class CandleAuditTests(unittest.TestCase):
def test_clean_intervals_are_aware(self):
data = row("2026-01-05T10:00:00+05:30") + row("2026-01-05T04:35:00+00:00")
accepted, issues = audit(StringIO(HEADER + data))
self.assertEqual(issues, [])
self.assertEqual(len(accepted), 2)
self.assertIs(accepted[0].start.tzinfo, timezone.utc)
self.assertEqual(accepted[0].start.isoformat(), "2026-01-05T04:30:00+00:00")
def test_same_instant_is_duplicate(self):
data = row("2026-01-05T10:00:00+05:30") + row("2026-01-05T04:30:00+00:00")
accepted, issues = audit(StringIO(HEADER + data))
self.assertEqual(len(accepted), 1)
self.assertEqual([(i.line, i.reason) for i in issues], [(3, "duplicate interval")])
def test_gap_is_reported(self):
data = row("2026-01-05T10:00:00+05:30") + row("2026-01-05T10:10:00+05:30")
_, issues = audit(StringIO(HEADER + data))
self.assertEqual(len(issues), 1)
self.assertIn("gap after", issues[0].reason)
def test_order_violation_is_reported_without_a_gap(self):
data = row("2026-01-05T10:05:00+05:30") + row("2026-01-05T10:00:00+05:30")
_, issues = audit(StringIO(HEADER + data))
self.assertEqual([i.reason for i in issues], ["interval out of order"])
def test_bad_timestamp_and_bad_prices(self):
for time, prices, reason in (
("2026-01-05T10:00:00", "100,103,99,102,12", "explicit offset"),
("2026-01-05T10:01:00+05:30", "100,103,99,102,12", "five-minute grid"),
("2026-01-05T10:00:00+05:30", "100,101,99,102,12", "between low and high"),
("2026-01-05T10:00:00+05:30", "100,103,99,102,1.2", "nonnegative integer"),
):
with self.subTest(reason=reason):
accepted, issues = audit(StringIO(HEADER + row(time, prices)))
self.assertEqual(accepted, [])
self.assertIn(reason, issues[0].reason)
def test_short_row_and_header_are_different_failures(self):
_, issues = audit(StringIO(HEADER + row("2026-01-05T10:00:00+05:30", "100,103,99,102")))
self.assertIn("wrong number", issues[0].reason)
_, issues = audit(StringIO("time,open,high,low,close,volume\n"))
self.assertEqual(issues[0].reason, "unexpected CSV header")The first case confirms that different offsets can describe successive moments within the same sequence. The duplicate case deliberately makes the UTC values equal. The gap and order cases are independent: a sorted sequence can be missing an interval, and an unsorted sequence can contain every required interval. Because the fixtures are small enough to read, you can check manually what each case really establishes.
For the exercise, change the fixture so an invalid record occupies the only space between two legal bars. Write separate expectations for the invalid row and the resulting gap. Then switch the faulty row to a valid value and confirm both go away. Do not change the test simply to match the program's current behaviour. Ask what the data contract says should happen. If you later want a different data contract, update the description and test together.
Answer check. Ask what the suite does not cover. A technically sound response should mention at least one missing boundary, such as a header-only file, a blank required field or a malformed quoted record. Pick one, create the fixture and ensure it fails when the relevant guard is removed. Never use a real data provider merely to make an offline test appear more realistic.
Capstone: Write a data-acceptance note
Your final result is the script, the tests and a short note for someone who did not see your editor. State the source format, which instrument file it refers to, how the timestamp is labelled, which interval it uses, how you validate ranges, how you identify duplicates, how you distinguish order from gaps, and when you return a nonzero status. Include one example receipt for a clean file and one for a file you refuse.
Make a specific distinction between completeness and correctness. Passing the audit does not prove that the source delivered the right underlying values, that the example matches a live market, or that no required rows are missing at the very start or end. The code inspects gaps between accepted records; it does not know where the session should start or end. To detect leading or trailing omissions you would need an independently defined boundary and tests demonstrating that it agrees with the intended dataset.
Also state which decisions you have not made. This file uses one instrument at a time. It does not deal with corporate actions, source licensing, a changing market calendar, simultaneous trades or corrections that arrive later. If you extend the program, add one of those decisions at a time and check the source documentation before changing the file format. Do not put a live API request into the parser to compensate for a missing design.
If you use Quanty exercise review (beta), offer one compact question: “Here is my fictional data contract and one failed test. Is the failure about parsing, timestamp equivalence, a price relationship, an order change, or a gap? Explain the first failing condition and suggest a case the test misses.” That asks for analysis of the case in front of you. It does not invite recommendations about instruments, indicators or market timing.
Audit drill: Identify which interval is actually missing
Take the earlier example and write the complete expected list of starting times. Between 10:05 and 10:15 you expect a start at 10:10. If you also add a valid row at 10:25, the next pair of accepted bars needs 10:20. Think of the gap as an observation about the expected grid given a continuous practice segment. The program does not claim the underlying market was active at those minutes; it knows only what the educational contract says.
You can calculate the number of whole missing intervals from the difference between two aligned starts and the step. For a difference of ten minutes on a five-minute grid, there are two steps from left to right, but one missing start between them. For a difference of fifteen minutes, there are three steps and two missing starts. The formula subtracts one because the right edge is an observed start, not another missing record. Work these examples by hand before changing the report text. This training task is about counting known expected starts, not estimating which prices would have appeared in their rows.
If you extend the report to emit the full list, set a modest diagnostic bound first. An unexpected timestamp a long way in the future could otherwise generate thousands of messages and obscure the original problem. One report style is to count the possible gaps and include just the first few labels, with a clear note that the list is truncated. Another is to keep only the boundaries and total count. Both preserve the fact that the evidence is incomplete. Neither supplies a replacement value.
Test the boundary just below and just above your diagnostic limit. For a gap with exactly the number of entries you allow, the report should not say any were omitted. For one extra entry, it should say only the details were limited, not that the file had fewer missing intervals. As a separate check, run the code with one accepted row. There is no adjacent pair, so the gap loop cannot say anything about missing records before or after that row.
Answer check. Ask the exercise reviewer to derive the count for a specific fictional pair and point out the difference between “number of steps” and “unseen starts.” Add a note about whether you report the first gap, every gap or a bounded list. This is useful review material even if you have not written the extension.
Audit drill: Keep evidence when a provider corrects a record
Imagine a data provider charged with maintaining a licensed dataset sends one correction to a historical candle after the file has been stored. The exercise's duplicate error remains appropriate for the simple file, because that schema carries no revision field or source authority. For an intentionally revised feed you would need explicit evidence of what changed, when it changed and which record should remain visible in each downstream view. The source of truth cannot be whichever record happens to be first or last in a list.
Sketch two files. One contains a candle as first received. The other names the same fictional instrument and time but has a different close. Do not decide which is right by looking at the size of the price change. Give each record metadata of your own choosing: a revision number, a receipt time and a source identifier suitable for this offline drill. Write a rule for sorting by revision and a second rule specifying what happens if two sources give the same revision with different values. A defensible exercise rejects the conflict instead of selecting silently. Keep the source files intact to support the comparison.
Now ask who needs to see which version. A current data view might use the latest verified version. A research replay might need to recreate what was known at its chosen cutoff, in which case a later correction is unavailable to that replay. A user looking at diagnostics might need to see both records and a correction reason. These views can legitimately differ while using the same underlying history. Mixing them without describing the cutoff can make a research simulation appear to know something it did not.
Write a small acceptance note with the current audit's scope: “one instrument, one file, no revision fields; repeated start is rejected.” In a second document propose your revised schema and where it differs. Keep your tests for normalised timestamps and invalid price ranges; those facts still matter after introducing revisions. Add one test for two conflicting records at the same revision and one for choosing the correct version at an earlier cutoff. A reader should be able to identify which requirement each fixture checks.
Audit drill: Compare two files without hiding their time conventions
Take two fictional datasets for the same three bars. In the first, the timestamps label interval starts. In the second, use interval ends. The price numbers should match in the example. Write a mapping in plain words before writing a join: with a fixed five-minute interval, the second source's end label corresponds to the first source's start label plus five minutes. If the data producer defines a different interval, the mapping changes. Do not align the files by their positions in a list because a single omitted row would misalign every following result.
After applying the mapping, compare both timestamps and the separate price fields. A straight equality check of all values can tell you that something differs, but a useful report tells you whether there is a missing row on one side or a price difference on a matched row. Make three small tests: exact match after label conversion, a missing middle row on one side, and a last row with one changed field. Put the mismatched field name in the expected result. A one-line “false” output would not show whether the join or the input values caused the problem.
Keep this separate from the single-file audit. The original code rejects corrupt rows and timestamps before any comparison; the join assumes its inputs already passed that contract. If you combine the responsibilities, a failed join might mask a malformed CSV record. The final result of this drill is a plan and three fixtures, not a requirement to write a larger program. You are ready for the indicator course when you can explain how the program knows which close belongs to which interval, what rows were rejected and what assumptions the calculation will inherit.
FAQ about this data course
Does the interval label say when every price became known?
No. The interval label states the beginning under this file's contract. The completed high, low and close depend on values observed over the interval. If a later exercise uses completed bars, it must avoid treating the completion-dependent values as though they were available at the beginning.
Why can the duplicate checker reject different timestamp strings?
They may describe the same instant. Convert each aware timestamp to UTC, then compare the resulting instants. This example assumes one record per instrument per interval. If a different feed intentionally supplies several revisions of the same record, you need a revision policy and evidence, not a change that simply disables the duplicate check.
Should I trade using the price series after it passes?
No decision follows from this audit. It checks a limited file contract for a fictional exercise. It does not validate records against an exchange, establish market data quality for an investment decision, or recommend a trade. The exercise deliberately does not include order, account or position code.
Related
- Learn to code for trading: the sequence and practice format.
- Python basics for traders: revisit types, functions and local tests.
- Candlestick patterns: separate reference about interpreting charts, not part of this data audit.