σμ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 4 · Lineage and the full pipeline›Topic 4.2·~1 hr 40 minAdvanced

Capstone: a validated ingestion pipeline for prices and fundamentals

Skill positionModule 4 of 4 · Topic 2 of 2
4.2 Capstone: a validated ingestion pipeline for prices and fundamentals
—Lab score— / 100Total XP—Streak—
Lecture0% read

11 min readCode examples: 5

  1. 01Many steps, one flow
  2. 02Run the steps in the right order
  3. 03A runner that remembers
  4. 04Fundamentals: figures with a filing date
  5. 05The point-in-time join
  6. 06Putting the pipeline to work
  7. 07What you will build

A vendor sends AAPL prices as printed before a split and fundamentals as filings with a date. A pipeline has to read, adjust, check and join them, and say where every table came from. How many days of three years would a join by the end of the quarter have fed a strategy a figure that nobody had yet? On real AAPL from 2019 to 2021 the answer is 267 of 757.

01

Many steps, one flow

Where we are: this is the last topic of the skill, and it has nothing new to teach about prices. It teaches how to connect what you already know into one flow that can be run, repeated, checked and explained. The eight earlier topics are the stages of the flow. Sources and formats gave one shape for many vendors. Names and calendars made them agree. Corporate actions made prices comparable across days. Tiers told which data you hold. Quality rules flagged what looks wrong. Idempotent loads made repetition safe. Backfills and late data kept every version. And contracts and lineage guarded the shape and recorded the origin. By the end of this topic you will be able to order the steps of a pipeline, run them while recording lineage, clean fundamentals, and join them to prices without looking into the future.

A pipeline of several steps is a graph. Each step produces a table from the tables of other steps, so some steps must wait for others. A DAG is the name for such a graph. Writing the pipeline as data, a dictionary from a step to its dependencies, has a big advantage over a long script: the same description can be ordered, run, drawn, checked for mistakes and compared between runs.

DefinitionPipeline

A set of steps in which each step turns the tables of earlier steps into a new table, described as a graph so that the order of the steps, the lineage of every table and the failure of any step are all handled by the same runner.

02

Run the steps in the right order

The first job of a runner is to find an order in which every step comes after the steps it needs. There is a simple method that works in rounds. In each round, find every step that is not done and whose dependencies are all done, take them in alphabetical order (so the answer never depends on how the dictionary was written) and mark them done. Repeat until all steps are done. A step with no dependencies is ready in the first round.

Worked example 1. *Problem:* four steps: report needs joined, joined needs prices and facts, and the last two need nothing. Find the order and print each round. *Plan:* start with nothing done and repeat the round until everything is in. *Steps:* find the ready steps, sort, add, mark done.

main.pyPython
dag = {"report": ["joined"], "joined": ["prices", "facts"], "prices": [], "facts": []}done, order = set(), []while len(order) < len(dag):    ready = sorted(name for name, deps in dag.items() if name not in done and all(d in done for d in deps))1    print("round:", ready)    order += ready    done.update(ready)print(order)
round: ['facts', 'prices']
round: ['joined']
round: ['report']
['facts', 'prices', 'joined', 'report']
  1. 1Ready means: not done yet, and every dependency done.

*Check:* the first round finds facts and prices (no dependencies), then joined becomes ready, then report, and the dependencies are always before their steps. *What to notice:* the simple method, running the steps in the order they are written, depends on the author of the dictionary and fails the day somebody adds a step in the wrong place. And if two steps depend on each other, a round finds nothing ready while steps are left. The runner must notice that and stop with an error, because otherwise the loop never ends.

main.pyPython
cyclic = {"a": ["b"], "b": ["a"]}done = set()ready = sorted(name for name, deps in cyclic.items() if name not in done and all(d in done for d in deps))print(ready)
[]

The empty list is the signal of a cycle. A dependency on a step that does not exist is a different mistake, a typo in the description, and it is better to report it by name before the first round than to let it look like a cycle.

Never loop on a cycle

If a round finds no ready step while some are not done, stop with an error. A loop that waits for a step that can never be ready runs forever, and a scheduler that waits forever hides the mistake.

Describing the pipeline as data also tells you what the real system needs next. Steps that do not depend on each other, like prices and facts here, can run at the same time on a bigger machine. A step whose inputs have not changed since the last run can be skipped, which is where the fingerprints of the lineage pay off, because comparing two fingerprints is cheaper than comparing two tables. And a drawing of the graph, made from the same dictionary, is the documentation that cannot go out of date.

03

A runner that remembers

Once the order is known, the runner calls each step with the results of the steps it depends on, keeps the result, and writes a lineage record. Two rules make it safe. A step is given only the tables it asked for, so it cannot depend on something it did not declare. And an exception in a step is not caught: the pipeline stops at once, and nothing after the failing step runs on a half-finished state, which is the same all-or-nothing idea as the atomic load.

Worked example 2. *Problem:* three steps: load makes a table of 1, 2, 3; double doubles it; total sums both. Run them in order and print the lineage record of each. *Plan:* each step is a function of the dictionary of its dependencies; after each call write the record with the fingerprints and row counts. *Steps:* loop, call, record.

main.pyPython
dag = {"load": [], "double": ["load"], "total": ["double", "load"]}steps = {    "load": lambda deps: pd.DataFrame({"x": [1, 2, 3]}),    "double": lambda deps: deps["load"] * 2,    "total": lambda deps: pd.DataFrame({"x": [deps["double"]["x"].sum() + deps["load"]["x"].sum()]}),}results, lineage = {}, []for name in ["load", "double", "total"]:    inputs = {dependency: results[dependency] for dependency in dag[name]}1    results[name] = steps[name](inputs)    lineage.append(lineage_step(name, list(inputs.values()), results[name]))2for record in lineage:    print(record["step"], record["rows_in"], "->", record["rows_out"], record["inputs"], record["output"])
load [] -> 3 [] 4bf0e63035dd
double [3] -> 3 ['4bf0e63035dd'] 6206722c5051
total [3, 3] -> 1 ['6206722c5051', '4bf0e63035dd'] adb4aec7897c
  1. 1Only the declared dependencies are passed to the step.
  2. 2The record uses the dependencies in the order the dag lists them.

*Check:* load has no inputs, double has the fingerprint of load as its input, and total has two inputs in the order double, load, as the dag lists them. The fingerprints are fixed codes, so running the same pipeline again prints exactly the same lines. *What to notice:* a lineage list that is equal between two runs is the proof that the same data went through the same steps.

A failing step is a feature

A step that raises, such as a validation of a contract, should stop the whole pipeline, and the lineage should show the last step that finished. Silent recovery, for example replacing a failed table with an empty one, would let bad data reach the end.

04

Fundamentals: figures with a filing date

Fundamentals are the figures of a company's accounts, such as the net income of a quarter. They are filed some weeks after the quarter ends, and sometimes filed again, with a restatement, much later. Two dates matter. The period_end is the last day of the quarter that the figure describes, and the filed_at is the day it became public. The market could only use the figure from the second date on. A clean table of fundamentals keeps both dates, removes the rows with no figure, and keeps for each period the first filing, because that is what the market saw; later restatements would be a separate, versioned history, as in topic 7.

Worked example 3. *Problem:* four rows: the period of 31 March was filed on 15 January 2021 (9.0) and also on 1 May 2020 (5.0); 30 June has no figure; 30 September was filed on 1 November (7.0). Which rows remain, and what would keeping the last filing give? *Plan:* drop the missing figure, sort by filing date, then drop repeated periods and keep the first. *Steps:* dropna, sort, drop_duplicates.

main.pyPython
rows = pd.DataFrame({"period_end": ["2020-03-31", "2020-03-31", "2020-06-30", "2020-09-30"],                     "filed_at": ["2021-01-15", "2020-05-01", "2020-08-01", "2020-11-01"],                     "net_income": [9.0, 5.0, None, 7.0]})kept = rows.dropna(subset=["net_income"]).sort_values("filed_at")1print(kept.drop_duplicates(subset="period_end", keep="first")[["period_end", "filed_at", "net_income"]].to_string(index=False))2print(kept.drop_duplicates(subset="period_end", keep="last")["net_income"].tolist())
period_end   filed_at  net_income
2020-03-31 2020-05-01         5.0
2020-09-30 2020-11-01         7.0
[7.0, 9.0]
  1. 1Sort first, so that first means earliest.
  2. 2keep="last" would keep the restated figure of 9.0.

*Check:* the first query keeps the 5.0 filed on 1 May 2020 for the first quarter and the 7.0 for the third; the quarter with no figure is gone. The second query's list contains 9.0, the restatement that was filed eight months later. *What to notice:* sorting before dropping duplicates is what gives "first" its meaning. Without the sort, the row that comes first in the file wins, and the file order is arbitrary.

A figure belongs to the day it was filed

The period end says what the figure is about, and the filing date says when anyone could know it. Joining prices to fundamentals by the period end gives every day of a quarter a figure that is published weeks later. Strategies tested that way look much better than they could ever have been in real time.

05

The point-in-time join

A point-in-time join gives each day of prices the latest figure that was filed on or before that day. Pandas does this with merge_asof, which matches each row of the left table with the last row of the right table whose key is not after it, as long as both tables are sorted by their keys and both keys have the same type. The same-day rule is the one of the as-of view in topic 7: a filing on a day is known that day.

Worked example 4. *Problem:* three price days (15 July, 3 August, 15 October 2020) and three fundamentals with the period end, the filing date and the figure. What does each day get when the join uses the filing date, and when it uses the end of the quarter? *Plan:* run merge_asof twice, once on filed_at and once on period_end, each with the facts sorted by that key. *Steps:* two joins, two lists.

main.pyPython
prices = pd.DataFrame({"date": pd.to_datetime(["2020-07-15", "2020-08-03", "2020-10-15"])})facts = pd.DataFrame({"period_end": pd.to_datetime(["2020-03-28", "2020-06-27", "2020-09-26"]),                      "filed_at": pd.to_datetime(["2020-05-01", "2020-07-31", "2020-10-30"]), "income": [11.2, 11.3, 12.7]})by_filing = pd.merge_asof(prices, facts.sort_values("filed_at"), left_on="date", right_on="filed_at")1by_quarter = pd.merge_asof(prices, facts.sort_values("period_end"), left_on="date", right_on="period_end")2print(by_filing["income"].tolist())print(by_quarter["income"].tolist())
[11.2, 11.3, 11.3]
[11.3, 11.3, 12.7]
  1. 1Both tables are sorted by their join key.
  2. 2The same call with the period end gives other numbers.

*Check:* by filing date, the 15th of July still sees the figure filed on 1 May (11.2), because the figure of the quarter ended 27 June was not filed until 31 July; by quarter end, it sees 11.3, a number nobody had yet. The 15th of October is the same: the correct 11.3 against a leaked 12.7. *What to notice:* the two lists differ on the first and the third day, which are the days between the end of a quarter and its filing. Over three years of AAPL that is 267 of 757 days, about a third.

Two practical details cause most errors with merge_asof. Both tables must be sorted by the key you join on, and the keys must have the same type, including the unit of time of the dates, which is why the canonical table in this lab keeps its dates in nanoseconds. After the join you compute the age of the figure, the days since it was filed, which a model can use as a feature and a person can use to spot a figure that is suspiciously old.

The same pattern extends to what comes next. A third source, say an index of interest rates, is one more step with no dependencies and one more join. A new rule from the quality topic is one more check inside the clean step. A schema contract for the joined table is one more validate after the join. None of them changes the runner, which is the reason to write the flow as data in the first place.

06

Putting the pipeline to work

The lab runs the whole flow on AAPL from 2019 to 2021, in the way a vendor would deliver it. The prices are first turned back into what the market printed before the 2020 split, and written as the CSV of vendor A. The pipeline reads the text, adjusts the prices for the split, validates them against the contract, cleans the fundamentals, and joins the two with the point-in-time rule. The runner records every step. The study then runs the pipeline twice and checks that the record is identical, and it counts the days on which a join by quarter end would have used a figure from the future.

  • FunctionQuestion it answers
  • topological_order(dag)In which order do the steps run?rounds, alphabetical
  • run_pipeline(steps, dag)Run the steps and record where each table came from.stops at a failing step
  • facts_table(rows)Which figures did the market first see?first filing of each period
  • point_in_time_join(prices, facts)Which figure was public on each day?looks back, never forward
  • study(bars)Does the whole pipeline hold on real AAPL?two runs, one record
What the real data saysAAPL daily bars from 2019 to 2021 and its quarterly net income
Price days757adjusted, validated, joined
Facts72quarters with a figure, first filing each
Figure on 2020-08-3111.253bnthe quarter filed on 2020-07-31
Days with a leak267a join by quarter end would use an unfiled figure

Key takeaways

  • Describe the pipeline as data. A dictionary of steps and dependencies can be ordered, run, checked and compared by one runner.
  • Record, stop, repeat. Each step leaves a lineage record, a failing step stops everything, and a second run must give the same record.
  • Join on the day a figure was filed. A point-in-time join looks back to the latest filing on or before each day, and never to the end of the quarter.
Quick check
Your turn. A quarter ended on 26 September 2020 and its figure was filed on 30 October 2020. The previous quarter's figure was filed on 31 July 2020. Which figure does a point-in-time join give to the price day of 15 October 2020?
Pick an answer.
07

What you will build

The lab follows the lecture and ties the skill together. Task 1 orders the steps of a pipeline and task 2 runs them while recording lineage. Task 3 cleans the fundamentals and task 4 joins them to prices as of each day. Task 5 runs the whole flow on real AAPL, as a vendor would deliver it, and measures what the point-in-time join protects you from.

This completes the data pipelines skill. You can now take market data from vendor formats to a table that is named, comparable, checked, repeatable, versioned, guarded and joined to what was known when. The same ideas carry over to the other data skills of the academy, which build on it.

Lab · what's graded

5 tasks · 100 pts
  • Order the steps15 pts
  • Run and record20 pts
  • Clean the fundamentals15 pts
  • The point-in-time join25 pts
  • The study on the SPY table25 pts
Explorer · lab-dp-09
▾ lab-dp-09
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-dp-09$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-dp-09 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