σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Data pipelines skill›Module 3 · Repeatable loads›Topic 3.2·~50 minAdvanced

Backfills and late data

Skill positionModule 3 of 4 · Topic 2 of 2
3.2 Backfills and late data
—Lab score— / 100Total XP—Streak—
Lecture0% read

10 min readCode examples: 5

  1. 01The past changes
  2. 02Keep every version
  3. 03Two views of the same history
  4. 04Backfills
  5. 05Putting the history to work
  6. 06What you will build

Three weeks after the fact, a vendor corrects the close of 10 March. A backtest that ran last week must not have seen that correction, and one that runs tomorrow must. Can a store answer both, and also fill the days a feed dropped? On real SPY, one correction and one backfill show that the answer is to keep every version of every row.

01

The past changes

Where we are: the last topic loaded data safely, and an incremental load deliberately ignored anything older than its watermark. But the past does change, in three ways. A source corrects a value it sent earlier. A feed drops some days and sends them later, which is called late data. And you find a gap in your own history and fill it, which is called a backfill. If the store overwrites old values, the correction erases what you believed before, and you can never again say what a result was based on. By the end of this topic you will be able to record versions with the day each was learned, view the history as it is now and as it was on any day, find the gaps in a range, and backfill them.

Two dates describe every fact in a history, and mixing them up is a classic mistake. The first is the date of the data: the trading day that the close belongs to. The second is the day the pipeline learned it, called here known_at. A close for 1 March may be known on 2 March and corrected on 20 March. Both dates are needed: the first to know which day the number describes, the second to know which number was believed when.

People who design databases call this idea bitemporal: every fact has a date of validity (what it is about) and a date of knowledge (when we learned it). You do not need a special database to use it. A table with the key, the values and a known_at column is enough, and the two views of this topic are two simple queries over it. What the idea buys is reproducibility: a result computed from the as-of view of a given day can be computed again years later and will come out the same, because later corrections cannot reach it.

DefinitionVersion

One value of a row together with the day it was learned. A correction adds a new version instead of replacing the old one, so the history of a row is the list of its versions, oldest first.

02

Keep every version

The simplest storage overwrites. It is also the one that loses information. The code below treats the same correction twice, once by overwriting the old close and once by adding a version with the day it was learned.

main.pyPython
overwrite = {"2021-03-01": 10.0}history = {"2021-03-01": [("2021-03-02", 10.0)]}overwrite["2021-03-01"] = 10.5history["2021-03-01"].append(("2021-03-04", 10.5))1print(overwrite)print(history)
{'2021-03-01': 10.5}
{'2021-03-01': [('2021-03-02', 10.0), ('2021-03-04', 10.5)]}
  1. 1The new version goes at the end; the old one stays.

The overwritten store now says 10.5 and has forgotten that 10.0 ever existed. The history says that 10.0 was learned on 2 March and 10.5 on 4 March, and so it can answer any question about what was known when. Recording follows three rules. A row that is not in the history yet starts a list with one version. A row whose values differ from the last version adds a version. A row whose values equal the last version adds nothing, because learning the same thing twice is not news.

Worked example 1. *Problem:* the days 1 and 2 March are learned on 3 March. On 10 March the same two days arrive again, and the close of the 2nd is different. Record both deliveries and report what happened. *Plan:* for each row compare it with the last version of its day: new, same or revised. *Steps:* loop, three cases, count.

main.pyPython
history = {}def learn(rows, known_at):    counts = {"new": 0, "revised": 0, "same": 0}    for day, close in rows:        if day not in history:            history[day] = [(known_at, close)]1            counts["new"] += 1        elif history[day][-1][1] == close:2            counts["same"] += 1        else:            history[day].append((known_at, close))            counts["revised"] += 1    return countsprint(learn([("2021-03-01", 10.0), ("2021-03-02", 10.2)], "2021-03-03"))print(learn([("2021-03-01", 10.0), ("2021-03-02", 10.4)], "2021-03-10"))print(history)
{'new': 2, 'revised': 0, 'same': 0}
{'new': 0, 'revised': 1, 'same': 1}
{'2021-03-01': [('2021-03-03', 10.0)], '2021-03-02': [('2021-03-03', 10.2), ('2021-03-10', 10.4)]}
  1. 1The last version is the one that counts for the comparison.
  2. 2A changed value adds a version.

*Check:* the first delivery has 2 new rows; the second finds one row the same and one revised, and the history of 2 March now holds two versions. *What to notice:* the simple method of comparing with the first version would call a value that goes back to the old one "same" and lose the change. One more rule protects the order of the versions: if a row arrives with a known_at earlier than the last version, something is wrong with the delivery order, and the lab raises ValueError.

Never overwrite

An UPDATE that replaces a value destroys the evidence. If a number in a report is later questioned, you can no longer show what the table said on the day of the report. Add a version, and let the views of the history decide which one to show.

03

Two views of the same history

A history is queried in two ways. The current view answers "what do we believe now": it takes the last version of each key. The as-of view answers "what did we believe on day D": for each key it takes the latest version whose known_at is not after D, and a key whose first version was learned later is simply absent. The second view is also called a point-in-time view, and it is what a backtest must use.

Worked example 2. *Problem:* three days of data. Day 1 was corrected on 10 March, and day 8 was only learned on 12 March. Show the as-of view on four days. *Plan:* for each key keep the versions known by the given day and take the last one, leaving out the key when there is none. *Steps:* filter by known_at, take the last, skip empties.

main.pyPython
history = {"2021-03-01": [("2021-03-03", 10.0), ("2021-03-10", 10.4)], "2021-03-02": [("2021-03-03", 10.2)], "2021-03-08": [("2021-03-12", 10.9)]}def as_of(when):    view = {}    for day, versions in history.items():1        known = [close for known_at, close in versions if known_at <= when]2        if known:            view[day] = known[-1]    return viewfor when in ("2021-03-02", "2021-03-03", "2021-03-10", "2021-03-12"):    print(when, as_of(when))
2021-03-02 {}
2021-03-03 {'2021-03-01': 10.0, '2021-03-02': 10.2}
2021-03-10 {'2021-03-01': 10.4, '2021-03-02': 10.2}
2021-03-12 {'2021-03-01': 10.4, '2021-03-02': 10.2, '2021-03-08': 10.9}
  1. 1<= includes the day itself: learned on that day counts.
  2. 2A key with no known version is left out, not shown as None.

*Check:* on 2 March nothing was known, on the 3rd both early days are there with the first close of day 1, on the 10th day 1 shows the corrected 10.4, and only on the 12th does day 8 appear. *What to notice:* the simple method, always showing the last version, would put day 8 and the correction into the view of the 2nd, which is a view from the future.

A backtest on current data sees the future

If a strategy is tested on the current view, each day it trades on numbers that were only corrected later. The result looks better than it could have been in real time. A test that is honest uses the as-of view of each trading day.

The difference can be large. In the next example the close of the second day is corrected from 101 to 90 on 20 March, weeks after the trade. The return from the second to the third day depends on which view you use: the current view says the market rose 13%, and what was known on 4 March says it rose 1%.

main.pyPython
history = {"2021-03-01": [("2021-03-02", 100.0)], "2021-03-02": [("2021-03-03", 101.0), ("2021-03-20", 90.0)], "2021-03-03": [("2021-03-04", 102.0)]}now = {day: versions[-1][1] for day, versions in history.items()}1then = {day: [close for known_at, close in versions if known_at <= "2021-03-04"][-1] for day, versions in history.items()}2print(now)print(then)print(round(now["2021-03-03"] / now["2021-03-02"] - 1, 4), round(then["2021-03-03"] / then["2021-03-02"] - 1, 4))
{'2021-03-01': 100.0, '2021-03-02': 90.0, '2021-03-03': 102.0}
{'2021-03-01': 100.0, '2021-03-02': 101.0, '2021-03-03': 102.0}
0.1333 0.0099
  1. 1The current view: the last version of each day.
  2. 2The view of 4 March: only what was known by then.

Two practical habits follow from the as-of view. First, when a report or a model is produced, record the day it was produced, so that the same data can be asked for later. Second, when a source announces a restatement (a company changes its past figures), treat it as a batch of revisions with the day of the announcement as known_at. Fundamental data is full of these, and a model trained on the restated figures would use information that the market did not have. The same versioning idea carries over to every dataset in this skill.

04

Backfills

A backfill fills days that are missing from the history. First you need to know which days: a gap is a trading day in a range that has no version of the symbol, with holidays not counted, which is the calendar of topic 2. Then you ask a source for those days only. The rule that keeps a backfill safe is that it touches the gaps and nothing else. If the source also disagrees with a day you already have, that is a correction, and it deserves its own record with its own known_at, because a backfill that silently rewrites old days would be an overwrite in disguise.

Worked example 3. *Problem:* the history has 1, 2 and 5 March, and the range is 1 to 5 March. The source has 3 March and 5 March (with a different close), but not 4 March. Which days are gaps, what is filled and what is still missing? *Plan:* gaps are the trading days not in the history; fill only the gaps that the source has; report the rest. *Steps:* find the gaps, intersect, subtract.

main.pyPython
have = {"2021-03-01", "2021-03-02", "2021-03-05"}gaps = [day for day in trading_days("2021-03-01", "2021-03-05", []) if day not in have]1print(gaps)source = {"2021-03-03": 10.1, "2021-03-05": 99.0}print({day: source[day] for day in gaps if day in source})2print([day for day in gaps if day not in source])
['2021-03-03', '2021-03-04']
{'2021-03-03': 10.1}
['2021-03-04']
  1. 1The calendar of topic 2 decides which days should exist.
  2. 2Only the gap days are taken: 5 March is in the source but is not a gap.

*Check:* the gaps are 3 and 4 March, the source fills the 3rd, and the 4th is still missing; the source's 99.0 for 5 March is ignored because that day is not a gap. *What to notice:* reporting what is still missing is part of the job. A backfill that says "done" while a day is still absent has hidden the problem.

known_at is the day of the backfill

The versions made by a backfill carry the day on which the backfill ran, not the date of the data. A day from March that is backfilled in April is known in April, and an as-of view of March must not show it.

Late data is the same event seen from the other side: a row that belongs to an old day arrives after that day was loaded. If the day was never loaded, it is a new key with a late known_at, which a backfill or record handles. If the day was loaded with other values, it is a revision. The incremental load of the last topic cannot handle either, because it skips every date that is not later than its watermark, so a pipeline needs both: the incremental load for the present and the versioned history for the past.

How big can the history get? Only the rows that changed add versions, because a row that is the same adds nothing. A year of daily bars with a handful of corrections holds a few hundred more versions than rows. That is cheap compared with the cost of an unanswerable question, and it is why the same-value rule matters: without it, every nightly run that sends the last month again would add thirty versions of nothing.

05

Putting the history to work

The lab tells one story in four acts on the first 40 days of SPY. A first delivery of the first 30 days arrives on 11 April with three days missing. On 20 April a late correction raises the close of one day by 5 cents. On 21 April a backfill fills the three missing days. In the end you look at the past three times: on 15 April, on 20 April and on 21 April. A correct history shows 27 rows on the first two days and 30 on the third, shows the old close on 15 April and the corrected close today, and has two versions of the corrected day.

  • FunctionQuestion it answers
  • record(history, rows, known_at)What is new, revised or the same?versions in time order
  • current(history)What do we believe now?the last version
  • as_of(history, when)What did we believe on that day?the point-in-time view
  • gaps_to_backfill(history, symbol, start, end, holidays)Which trading days have no data?holidays are not gaps
  • backfill(history, symbol, source, start, end, holidays, known_at)Fill the gaps from a source, and say what is left.only the gaps
  • study(bars)Does the story come out right on real SPY?four acts, three looks
What the real data saysthe first 40 daily bars of SPY, loaded as a first delivery, a correction and a backfill
First delivery2730 days minus 3 that the feed dropped
Gaps found311, 14 and 15 March 2005
Rows known on 15 April2730 on 21 April, after the backfill
Close of row 594.707394.7573 after the late correction of 5 cents

Key takeaways

  • Add versions, never overwrite. A correction adds a version with the day it was learned, so what was believed before is never lost.
  • Ask as of a day for a test, current for a report. A backtest must use the point-in-time view of each day, or it sees the future.
  • A backfill touches the gaps only. Find the gaps with the calendar, fill what the source has, and report what is still missing.
Quick check
Your turn. A close of 94.70 was learned on 11 April and corrected to 94.75 on 20 April. What does the as-of view of 19 April show for that day?
Pick an answer.
06

What you will build

The lab follows the lecture. Task 1 records rows as versions with the day they were learned, and task 2 gives the current view. Task 3 gives the as-of view of a day. Task 4 finds the gaps of a symbol in a date range, and task 5 backfills them from a source. Task 6 tells the four-act story on real SPY.

Next topic: you can now keep a history that is repaired and still honest. The next topic, Lineage and schema contracts, goes one level up: how to record where every table came from and what steps made it, and how to guard the shape of a table so that a vendor changing a column cannot break the pipeline silently.

Lab · what's graded

6 tasks · 100 pts
  • Record versions20 pts
  • The current view10 pts
  • The view as of a day20 pts
  • Find the gaps10 pts
  • Backfill15 pts
  • The study on the SPY table25 pts
Explorer · lab-dp-07
▾ lab-dp-07
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-dp-07$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-dp-07 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes