A bar whose high is below its close, the same day twice, a price ten times too large for one day: vendors really do send all of these. A pipeline cannot fix what it cannot see. In two years of SPY with 5 kinds of damage seeded into them, can five simple rules find every error and stay silent on the real data?
What a quality rule is
Where we are: the first four topics made data readable, named, adjusted and understood by tier. Nothing so far asks whether it is correct. Vendors make mistakes: a decimal point moves, a day is sent twice, a feed freezes and repeats the last price, an exchange glitch prints a bad tick. The cost of such an error is high because it travels: one bad close becomes two false returns, a false volatility and a false signal. By the end of this topic you will be able to write rules that find impossible bars, repeated dates, outlier returns, stale prices and missing days, and run them together in one report.
A data quality rule is a small function that returns a True or a False for each row, or a list of the rows it does not like. Three habits make rules useful. Each rule checks one thing and has a name, so a report can say which rule fired. A rule only flags: deleting or repairing a row is a separate decision that depends on the cause, and a rule that silently fixes data hides the evidence. And a rule must be quiet on good data, because a rule that fires every day teaches people to ignore it.
Where do errors come from? Most have a few causes that repeat. A vendor's software has a bug, or a manual correction has a typo. A feed drops out and the receiving system fills the gap with the last value. Two sources are merged and one row is added twice. A corporate action is applied twice or not at all (topic 3). Knowing the usual causes tells you what to look for, and each cause has a signature: a bug shows as an impossible bar, a dropout as a stale run, a double merge as a repeated date, a typo as a spike that comes back the next day.
A mark on a row (or the row's date) saying that a rule found it suspicious. A flag is evidence for a person or a later step, not a correction.
Rules that look at one bar
The easiest errors to find are the impossible ones. A bar summarises a day, so its high is the largest price of the day and must be at least the open, the close and the low; the low must be at most all three; and a price cannot be zero or negative. These rules need no history and no other source, which makes them the first line of defence. The method is to write each rule as a True/False for every row, combine them with | (or), and take the rows where the result is True.
Worked example 1. *Problem:* four bars (made-up numbers). Which have a high below the open, the close or the low? *Plan:* compare the high with the largest of the other three columns, row by row, with max(axis=1). A row that fails this comparison is impossible. *Steps:* build the largest of three, compare, read the flags. The first line of output shows the simple method, which compares the high with the close only.
bars = pd.DataFrame({"open": [10.0, 10.0, 10.2, 10.1], "high": [10.3, 9.9, 10.5, 10.1], "low": [9.8, 9.7, 10.0, 10.1], "close": [10.1, 9.8, 10.4, 10.1]})print((bars["high"] < bars["close"]).tolist())print((bars["high"] < bars[["open", "close", "low"]].max(axis=1)).tolist())1
[False, False, False, False] [False, True, False, False]
- 1max(axis=1) gives the largest of the three columns for every row.
*Check:* row 1 has a high of 9.9 and an open of 10.0, so it is impossible, and only the second line finds it. The last bar, where all four prices are 10.1, is a flat day (the market did not move) and is fine, which is why the comparison is strict. *What to notice:* the simple method of checking the high against the close alone misses an error that the open exposes. A good rule checks every relation that must hold.
A high that equals the close is normal: it means the day ended at its high. Writing <= instead of < flags those days and makes the rule fire on good data. When you write a bound, decide which side the equality belongs to.
A rule that compares a day with its neighbours
A price spike is not impossible: a bar with a close ten times larger can still have a consistent high and low. You find it because the return is far from the others. How far is far? A fixed limit such as 20% would flag every real crash and miss a small error in a calm market, so the limit should depend on how the table normally behaves. The standard idea is a z-score, the distance from the typical value measured in units of spread. The usual version uses the mean and the standard deviation, and it has a weakness: the spike itself raises the standard deviation, so it partly hides itself.
The fix is to measure the typical value by the median and the spread by the MAD. These barely move when one value is extreme. The modified z-score 0.6745 * (r - median) / mad is on the same scale as an ordinary z-score for normal data, and the constant 0.6745 makes that so.
Worked example 2. *Problem:* eight daily returns, one of which is a 30% jump. Compare the z-score from the mean and the standard deviation with the modified z-score. *Plan:* compute both for every return and look at the spike. *Steps:* mean score, median and MAD, modified score.
returns = pd.Series([0.002, -0.001, 0.003, -0.002, 0.001, 0.30, -0.002, 0.000])mean_z = (returns - returns.mean()) / returns.std()1median = returns.median()mad = (returns - median).abs().median()robust_z = 0.6745 * (returns - median) / mad2print(mean_z.round(2).tolist())print(robust_z.round(1).tolist())
[-0.34, -0.36, -0.33, -0.37, -0.35, 2.47, -0.37, -0.35] [0.5, -0.5, 0.8, -0.8, 0.2, 101.0, -0.8, -0.2]
- 1The mean and the standard deviation are both pulled by the spike.
- 20.6745 puts the score on the scale of an ordinary z-score.
*Check:* the ordinary score of the spike is only 2.47, a value that would not alarm anybody, while the modified score is 101. *What to notice:* the simple method fails exactly when it is needed. The median and the MAD of this table are 0.0005 and 0.002, which describe the ordinary days. Two details matter in the code you will write: the first row has no return, so it has no score, and if the MAD is 0 (a table that moves in perfect steps) the score would divide by zero, so the rule says that nothing can be scored.
A close that is ten times too large is wrong for one day. The return into it is +900% and the return out of it is -90%, so both days are flagged. A rule that reports dates should report both, and a repair step can then see that the second day is the first one's echo.
Rules for what did not change, repeated and missing
Some of the worst errors look perfectly normal on any single day. A feed that stops updating and repeats the last price shows a valid bar every day; only the run of identical closes gives it away. A stale price is found by looking for runs: sequences of consecutive rows that share a value. Grouping consecutive equal values is what itertools.groupby does.
Worked example 3. *Problem:* the closes are 20.0, 20.1, 20.1, 20.1, 20.1, 19.9, 20.0, 20.0. Find the runs of at least 3 identical closes. *Plan:* group the consecutive equal values, measure each group, keep the long ones. *Steps:* group, count, filter.
import itertoolscloses = [20.0, 20.1, 20.1, 20.1, 20.1, 19.9, 20.0, 20.0]runs = [(key, len(list(group))) for key, group in itertools.groupby(closes)]1print(runs)print([run for run in runs if run[1] >= 3])2
[(20.0, 1), (20.1, 4), (19.9, 1), (20.0, 2)] [(20.1, 4)]
- 1groupby only groups values that are next to each other.
- 2A run of 4 is reported once, with its full length.
*Check:* the groups are one 20.0, four 20.1, one 19.9 and two 20.0, and only the run of four reaches 3. The two 20.0 at the end are a run of 2, and the first 20.0 is not joined to them because 20.1 and 19.9 sit in between. *What to notice:* the same price on separate days is not a run, and the simple method of counting how often a price occurs would be wrong.
A repeated date is the next rule. Pandas can mark the repeats with duplicated(). By default it marks only the second and later copies and leaves the first unmarked, which is what you want for dropping copies and not what you want for reporting them. With keep=False every copy is marked, so the date can be reported.
Worked example 4. *Problem:* the dates 1 March, 2 March twice and 3 March three times. Report the repeated dates, once each. *Plan:* mark every copy with keep=False, take the distinct dates, sort. *Steps:* mark, select, format.
days = pd.Series(pd.to_datetime(["2021-03-01", "2021-03-02", "2021-03-02", "2021-03-03", "2021-03-03", "2021-03-03"]))print(days.duplicated().tolist())print(days.duplicated(keep=False).tolist())1print(sorted({f"{d:%Y-%m-%d}" for d in days[days.duplicated(keep=False)]}))2
[False, False, True, False, True, True] [False, True, True, True, True, True] ['2021-03-02', '2021-03-03']
- 1keep=False marks all the copies, the first one too.
- 2A set removes the repeats of the date; sorted makes the order fixed.
*Check:* the default marks 3 rows, and keep=False marks 5, and the report names each repeated date once even though 3 March has three rows. Missing days, the fifth rule, you already have: it is the function of topic 2, which compares the table with the calendar.
One report per table
Rules are most useful together. A report runs every rule on a table and puts the results side by side, under the name of each rule, so a person can see at a glance what fired and where. Keep the rules in a dictionary from name to function, and the report is a loop. New rules then need one new line, and the report does not change. The example shows the idea with two rules on a small table.
Worked example 5. *Problem:* a table of three bars has one impossible bar and one repeated date. Count what each rule flags. *Plan:* put each rule in a dictionary as a function from a table to a True/False per row, then loop over the dictionary and sum. *Steps:* define the rules, loop, print.
table = pd.DataFrame({"date": pd.to_datetime(["2021-03-01", "2021-03-02", "2021-03-02", "2021-03-03"]), "open": [10.0, 10.0, 10.0, 10.0], "high": [10.5, 9.0, 9.0, 10.5], "low": [9.5, 9.0, 9.0, 9.5], "close": [10.1, 9.5, 9.5, 10.2]})rules = {1 "ohlc": lambda t: t["high"] < t[["open", "close", "low"]].max(axis=1), "repeated": lambda t: t["date"].duplicated(keep=False),}for name, rule in rules.items(): print(name, int(rule(table).sum()))2
ohlc 2 repeated 2
- 1Each rule is a function from a table to a True or False per row.
- 2Adding a rule is one more line in the dictionary.
*Check:* the two copies of 2 March have a high of 9.0 below their open of 10.0, so both rows are impossible and both are repeats: the first rule flags 2 rows and the second flags 2 rows. *What to notice:* one bad row can fire several rules, and that is useful, because the combination (a copy that is also impossible) says more about the cause than either flag alone.
In production a report is not the end. Each rule is given a severity: some findings stop the pipeline (an impossible bar means the source is broken), others only raise a warning for a person to read (a large but possible return). The severity belongs next to the rule, as data, so that a rule's meaning is not buried in code. The lab stays with the report itself, which is the part every severity scheme needs.
Putting the rules to work
How do you know a set of rules is good? Test it twice. First on data you trust, where it should be silent: a rule that fires on clean data is too strict. Then on data with errors that you put in yourself, where it should find every one and nothing else: a rule that misses a known error is too loose. This is the seeded-damage method, and the lab uses it on two years of SPY. The threshold k of the outlier rule is the dial between the two. The example below scores sixteen returns, four of them rather large, and counts the outliers for five values of k.
returns = pd.Series([0.004, -0.002, 0.001, 0.003, -0.004, 0.002, -0.001, 0.0, 0.008, -0.003, 0.002, 0.012, -0.015, 0.001, 0.035, -0.036])median = returns.median()mad = (returns - median).abs().median()score = (0.6745 * (returns - median) / mad).abs()for k in (2, 3, 5, 8, 20): print(k, int((score > k).sum()))
2 4 3 3 5 2 8 1 20 0
A low threshold flags more days, including some that are only large, and a high one flags only the most extreme. With k = 2 four days are flagged, with k = 8 only the day of 3.6% and with k = 20 none. There is no best k in general: it depends on how costly a missed error is compared with a false alarm, and on how much human attention is available. A pipeline therefore records the threshold with the report, so that a result can be reproduced and discussed.
- FunctionQuestion it answers
- ohlc_violations(frame)Which bars are impossible?strict comparisons
- repeated_dates(frame)Which dates appear more than once?each date once
- return_outliers(frame, k)Which days move far from normal?median and MAD
- stale_runs(frame, n)Which prices froze?consecutive rows only
- quality_report(frame, k, n, holidays)What fires on this table?flags, never repairs
- study(bars)Does the rule set find known damage and stay silent otherwise?seeded damage
What you will build
The lab follows the lecture. Task 1 finds impossible bars and task 2 finds repeated dates. Task 3 finds outlier returns with the median and the MAD, and task 4 finds runs of a stale price. Task 5 runs the five rules in one report, and task 6 runs the report on two years of real SPY, with damage that was put in on purpose, and checks that every error is found.
Next topic: you can now say whether a table is wrong. The next topic, Idempotent and incremental loads, is about what to do with a correct table: how to put it in a store, again and again, as new data arrives, without ever duplicating or losing a row.
Lab · what's graded
6 tasks · 100 pts- Impossible bars15 pts
- Repeated dates10 pts
- Outlier returns20 pts
- Stale prices15 pts
- One report15 pts
- The study on the SPY table25 pts