σμ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 1 · Sources and normalisation›Topic 1.1·~45 minIntermediate

Sources and formats of market data

Skill positionModule 1 of 4 · Topic 1 of 4
1.1 Sources and formats of market data
—Lab score— / 100Total XP—Streak—
Lecture0% read

13 min readCode examples: 10

  1. 01One shape for many sources
  2. 02Vendor A: CSV text
  3. 03Vendor B: JSON lines and epoch seconds
  4. 04Vendor C: whole numbers instead of decimals
  5. 05Merging sources by priority
  6. 06When sources disagree
  7. 07Putting the first stage together
  8. 08What you will build

Three vendors send the same trading day in three shapes: US dates, seconds since 1970, or prices as whole numbers. A pipeline starts by making them one shape. In the first 14 days of SPY, three vendors overlap on 4 days, and one of them is wrong by 0.01 on a single close.

01

One shape for many sources

This is the first topic of the data pipelines skill, so there is no earlier result to build on. Here is what you will be able to do by the end: read the same market data from three different vendor formats into one table, merge the vendors by priority, and find the days on which they disagree.

Market data does not arrive in one tidy format. Every vendor, exchange and file has its own way of writing a date, its own column names, its own order of rows and its own idea of how to write a price. Code that trusts any one of those shapes breaks the day a second vendor is added. So the first stage of a data pipeline does one boring and very valuable thing: it turns every source into the same table, called the canonical table, before anything else touches it.

DefinitionCanonical bar table

A DataFrame with the columns date, open, high, low, close, volume, in that order, one row per day, oldest first, with a fresh index 0, 1, 2. The date is a real timestamp, the prices are floats and the volume is an integer. Every later step of the skill can rely on this shape.

A bar is the summary of one trading day: the first price (open), the highest (high), the lowest (low), the last (close) and the number of shares traded (volume). The function to_canonical is given to you. It takes any frame that has the six columns and fixes the types and the order. Watch what it does to a small table whose dates are text and whose rows are newest first (the prices here are made up).

main.pyPython
raw = pd.DataFrame({"date": ["2021-03-02", "2021-03-01"], "open": [50.0, 49.5], "high": [51, 50.2], "low": [49, 49], "close": [50.5, 49.9], "volume": [1000, 2000]})print(raw["date"].iloc[0], type(raw["date"].iloc[0]).__name__)out = to_canonical(raw)1print(out)print(out["date"].dtype.kind, out["low"].dtype, out["volume"].dtype)
2021-03-02 str
        date  open  high   low  close  volume
0 2021-03-01  49.5  50.2  49.0   49.9    2000
1 2021-03-02  50.0  51.0  49.0   50.5    1000
M float64 int64
  1. 1One call fixes the types, sorts by date and renumbers the rows. Each parser you write ends with this call.

The first line shows that the date is the text 2021-03-02, not a date. After to_canonical the first row is the oldest day, date has the kind M (a timestamp), low was whole numbers and is now a float, and volume is an integer. So a parser only has to produce the six columns with the right content. The tricky part is that each vendor hides the content in a different way. The next three sections show one hiding place each, with a different vendor than the ones in the lab, so the method is yours to apply.

Before you write a parser, read the vendor's description of the data, which people call the source sheet. It answers the same handful of questions every time, and each wrong guess becomes a wrong number in the table later.

  • The separator and the decimal mark (, or ;, . or ,).
  • The date format, and whether the time is a local time, UTC or no time at all.
  • The unit of time stamps (seconds or milliseconds) and of volume (shares or lots).
  • The scale of prices (dollars, cents or a fixed number of decimals).
  • The order of the rows, and what an empty or missing value looks like.
02

Vendor A: CSV text

A CSV file is the most common way to receive bars. Three things vary: the separator, the way decimals are written and the way dates are written. A CSV is also usually newest first. The method has four steps.

  1. 1
    Read the textWrap the string in io.StringIO so pandas can read it like a file, and tell read_csv the separator and the decimal mark.
  2. 2
    Check the columnsCompare the names you need with frame.columns. If one is missing, raise a ValueError that names it, so the pipeline stops with a clear message.
  3. 3
    Turn the dates into datesConvert the date text with pd.to_datetime and an explicit format. Never let pandas guess a format on data you do not control.
  4. 4
    Rename, then finishRename the columns to the canonical names and call to_canonical, which also sorts oldest first.

Worked example 1. *Problem:* a vendor sends the text below: semicolons between columns, a comma as the decimal mark, dates as day.month.year, newest first. Make a table with real dates, oldest first. *Plan:* the first line of the text tells us the separator is ; and a price like 50,5 needs decimal=",", and the date shape 02.03.2021 is day first, so the format is %d.%m.%Y. *Steps:* read, convert the dates, sort. *Answer, check, what to notice:* below.

main.pyPython
text = "Day;Close;Vol\n02.03.2021;50,5;1000\n01.03.2021;49,9;2000\n"frame = pd.read_csv(io.StringIO(text), sep=";", decimal=",")1print(frame["Day"].tolist())frame["Day"] = pd.to_datetime(frame["Day"], format="%d.%m.%Y")2frame = frame.sort_values("Day").reset_index(drop=True)print(frame)
['02.03.2021', '01.03.2021']
         Day  Close   Vol
0 2021-03-01   49.9  2000
1 2021-03-02   50.5  1000
  1. 1sep and decimal describe this vendor, not CSV in general.
  2. 2The format names the day first.

*Check:* the list printed first shows the dates are still text after reading, so they must be converted; after the conversion 01.03.2021 is first, and 50,5 became the number 50.5. *What to notice:* the simple method, sorting the dates as text, fails. Text is sorted letter by letter, so the day decides before the month. Here is the proof, followed by the same dates sorted as real dates.

main.pyPython
days = ["02.03.2021", "15.02.2022", "01.04.2021"]print(sorted(days))print([d.strftime("%Y-%m-%d") for d in sorted(pd.to_datetime(days, format="%d.%m.%Y"))])
['01.04.2021', '02.03.2021', '15.02.2022']
['2021-03-02', '2021-04-01', '2022-02-15']
Month first or day first

A date such as 04/05/2021 is 5 April for one vendor and 4 May for another, and pandas will not warn you. Always pass format. A wrong format on a date like 13/04/2021 raises an error, which is the good case: the bad case is a date where both readings are valid.

main.pyPython
print(pd.to_datetime("04/05/2021", format="%m/%d/%Y").strftime("%Y-%m-%d"))print(pd.to_datetime("04/05/2021", format="%d/%m/%Y").strftime("%Y-%m-%d"))
2021-04-05
2021-05-04
03

Vendor B: JSON lines and epoch seconds

Feeds that come over a network are often JSON lines: each line is a small object such as {"ts": 1614556800000, "px": 49.9}. There is no header, and the date is a number: the count of seconds, or of milliseconds, since midnight UTC on 1 January 1970 (the epoch). The unit matters by a factor of a thousand, and the vendor's documentation is the only place that tells you.

Worked example 2. *Problem:* the text below has two lines and a blank one, and the dates are in milliseconds. Make a table sorted by date. *Plan:* go through the lines one by one, skip the blank one (an empty line is not valid JSON), parse each with json.loads, build one row each, and let pd.to_datetime(..., unit="ms") turn the number into a date. *Steps:* loop, skip, parse, collect rows, build the frame, sort.

main.pyPython
text = '{"ts": 1614643200000, "px": 50.5}\n\n{"ts": 1614556800000, "px": 49.9}\n'rows = []for line in text.splitlines():    if not line.strip():1        continue    record = json.loads(line)    rows.append((pd.to_datetime(record["ts"], unit="ms"), record["px"]))2print(pd.DataFrame(rows, columns=["date", "px"]).sort_values("date").reset_index(drop=True))
        date    px
0 2021-03-01  49.9
1 2021-03-02  50.5
  1. 1A blank line would make json.loads fail.
  2. 2unit="ms" because this vendor counts milliseconds.

*Check:* 1614556800000 ms is 1 March 2021 00:00 UTC, so the first printed row is the earlier price, 49.9. *What to notice:* the simple method, passing the number without a unit, or with the wrong unit, gives a date that is wrong but valid. Reading seconds as milliseconds lands in January 1970. If you ever see 1970 in a price history, the unit is the first suspect.

Seconds are not milliseconds

A date in 1970 means a unit mistake. pd.to_datetime(1614556800, unit="ms") is 19 January 1970. Look at the number of digits: 10 digits are seconds, 13 digits are milliseconds.

main.pyPython
print(pd.to_datetime(1614556800, unit="ms"))print(pd.to_datetime(1614556800, unit="s"))
1970-01-19 16:29:16.800000
2021-03-01 00:00:00
04

Vendor C: whole numbers instead of decimals

Some feeds send a price as a whole number of tiny units, called fixed-point. The reason is exactness: a computer cannot store most decimals exactly in a float, so sending 4990 and the scale 100 avoids any rounding on the wire. The reader divides by the scale. The data often arrives as an object of parallel lists: the first date goes with the first price, the second date with the second price, and so on.

Worked example 3. *Problem:* {"scale": 100, "d": ["2021-03-01", "2021-03-02"], "px": [4990, 5050], "vol": [2000, 1000]}. Make a table with the price in dollars. *Plan:* the lists must all have the same length, because position i of each list belongs to the same day; the price is the whole number divided by the scale. *Steps:* check the lengths, build the frame, divide.

main.pyPython
payload = {"scale": 100, "d": ["2021-03-01", "2021-03-02"], "px": [4990, 5050], "vol": [2000, 1000]}print({len(payload[key]) for key in ("d", "px", "vol")})1frame = pd.DataFrame({"date": pd.to_datetime(payload["d"]), "px": pd.Series(payload["px"], dtype="float64") / payload["scale"]})2print(frame)print(0.1 + 0.2 == 0.3)
{2}
        date    px
0 2021-03-01  49.9
1 2021-03-02  50.5
False
  1. 1One distinct length means the lists line up.
  2. 2Divide by the scale in the payload, not by a number you remember.

*Check:* one distinct length was printed, so the lists line up, and 4990 / 100 is 49.9, a plausible price. *What to notice:* the simple method, using the numbers as they are, gives prices of 4990 dollars, which is why a plausible-range check is a cheap safety net. The last line shows why the vendor sends integers: 0.1 + 0.2 is not exactly 0.3 in floating point, so floats must never be compared with ==.

A cheap safety net for all three parsers is a plausibility check on the result: every close must sit between its low and its high, and a price must be above zero. If vendor C had been read with the wrong scale, the first check would fail on every row. Topic 5 turns such checks into rules; for now, print frame.describe() after a new parser and look at the minimum and maximum with your own eyes.

05

Merging sources by priority

With three canonical tables the next question is what to do about days that more than one vendor sent. You rank the vendors, best first, and keep the row of the best vendor for each date. This is a rule you can state and audit, which is far better than an average of vendors. Stack the tables in priority order, then drop repeated dates and keep the first row of each.

Why not average the vendors? An average looks fair, but it makes a bad number invisible: if one vendor is off by a cent, the average is off by a third of a cent and nobody can say where it came from. A priority rule keeps every stored number equal to one vendor's number, so a doubt can be traced back to a source. The next topics build on this idea, and the last topics of the skill turn it into a record of where every row came from.

Worked example 4. *Problem:* A has 1 and 2 March, B has 2 and 3 March, and they disagree on the 2nd (A says 50.5, B says 50.6). Build one table in which A wins. *Plan:* pd.concat keeps the order of the list, and drop_duplicates(subset="date", keep="first") keeps the first row of each date, so A's row survives. *Steps:* stack, count the repeats, drop them.

main.pyPython
a = pd.DataFrame({"date": pd.to_datetime(["2021-03-01", "2021-03-02"]), "close": [49.9, 50.5], "src": "A"})b = pd.DataFrame({"date": pd.to_datetime(["2021-03-02", "2021-03-03"]), "close": [50.6, 51.0], "src": "B"})stacked = pd.concat([a, b], ignore_index=True)print(len(stacked), stacked["date"].duplicated().sum())print(stacked.drop_duplicates(subset="date", keep="first"))1print(stacked.drop_duplicates(subset="date", keep="last")["src"].tolist())2
4 1
        date  close src
0 2021-03-01   49.9   A
1 2021-03-02   50.5   A
3 2021-03-03   51.0   B
['A', 'B', 'B']
  1. 1keep="first" means the earlier table wins.
  2. 2keep="last" would let the worst source win.

*Check:* 4 rows went in, one date repeated, 3 rows came out and the row for 2 March says A and 50.5. *What to notice:* the simple method, only stacking, leaves two rows for the 2nd, and a model fed that table would count the day twice. And keep="last" is a quiet bug: the table looks fine and the worst source wins. The order of the list is the policy.

06

When sources disagree

Priority picks one row, but it hides that the vendors disagreed. A pipeline should also report disagreements, because a disagreement is how you find an error in one vendor. For each date collect every close, then compare the highest with the lowest. Two closes of 50.5 and 50.5000001 are the same price for any practical purpose, so you compare with a tolerance, never with ==.

Worked example 5. *Problem:* for the rows below, which dates conflict with a tolerance of 0.005? *Plan:* group the closes by date with a dictionary, keep dates that have at least two closes, and test max - min > tolerance. *Steps:* group, filter, sort.

main.pyPython
print(50.5 == 50.5000001, abs(50.5 - 50.5000001) > 0.005)closes = {}for date, close in [("2021-03-02", 50.5), ("2021-03-02", 50.6), ("2021-03-03", 51.0)]:    closes.setdefault(date, []).append(close)1print(closes)print(sorted(d for d, v in closes.items() if len(v) > 1 and max(v) - min(v) > 0.005))2
False False
{'2021-03-02': [50.5, 50.6], '2021-03-03': [51.0]}
['2021-03-02']
  1. 1setdefault creates the list the first time a date is seen.
  2. 2A date seen once has nothing to disagree with.

*Check:* the 2nd has two closes 0.1 apart, which is more than 0.005, and the 3rd has one close, so only the 2nd is reported. *What to notice:* the simple method, ==, calls two equal prices different (the first line shows it). The tolerance turns "are they identical" into "are they close enough".

Compare the highest with the lowest

With three sources, comparing the first with the last can miss a conflict: the middle source may be the one that is off. The spread max - min over all closes of the date catches it.

07

Putting the first stage together

A pipeline stage is always the same four moves, and the order matters. Render or receive each source, parse it into the canonical table, merge the tables in priority order, and compare them to find what disagrees. Finally the numbers go into a result you can print or test.

Worked example 6. *Problem:* two toy sources, B repeating a day with a different close. Produce the merged table and the list of conflicts. *Plan:* both tables are already canonical, so skip the parsing; merge with A first, then report the conflicts with a tolerance of 0.005. *Steps:* stack, drop, report.

main.pyPython
toy_a = pd.DataFrame({"date": pd.to_datetime(["2021-03-01", "2021-03-02"]), "open": [49.5, 50.0], "high": [50.2, 51.0], "low": [49.0, 49.0], "close": [49.9, 50.5], "volume": [2000, 1000]})toy_b = toy_a.iloc[1:].assign(close=[50.6])frames = [toy_a, toy_b]merged = to_canonical(pd.concat(frames, ignore_index=True).drop_duplicates(subset="date", keep="first"))print(len(merged), merged["close"].tolist())closes = {}for frame in frames:    for date, close in zip(frame["date"], frame["close"]):        closes.setdefault(date, []).append(close)print([f"{d:%Y-%m-%d}" for d, v in sorted(closes.items()) if len(v) > 1 and max(v) - min(v) > 0.005])
2 [49.9, 50.5]
['2021-03-02']

*Check:* there are 2 different days, so 2 rows is right (3 would mean the repeated day survived); the close of the 2nd day is A's 50.5, and the conflict list names the 2nd day because B said 50.6. *What to notice:* the merge and the report are two separate questions. The merge picks a row for every day, and the report keeps the memory that a choice was made. You need both.

  • FunctionQuestion it answers
  • from_csv(text)What does the CSV vendor say?sorted oldest first
  • from_json_lines(text)What does the JSON-lines vendor say?seconds, not milliseconds
  • from_columns(payload)What does the vendor of lists say?equal list lengths
  • merge_sources(frames)One table, best source first?order is the priority
  • conflicts(frames, tolerance)Where do the sources disagree?tolerance in dollars
  • study(bars)Does the whole stage work on real days?uses all of the above

Which parser do you reach for? Look at the shape of the input. Text with separators and a header: a CSV reader with the separator, decimal mark and date format that the header and the first rows show. Lines that each look like an object: JSON lines, with the unit of the time stamp checked. An object of lists with a scale: build the frame and divide. Whatever the source, end with to_canonical.

What the real data saysthe first 14 daily bars of SPY, from 2005-02-25 to 2005-03-16
Rows per vendor6A: rows 0-5, B: rows 4-9, C: rows 8-13
Different days1418 rows come in, 14 days come out
Shared rows4days that two vendors both sent
Seeded error0.01$added to vendor B's close on 2005-03-04

Key takeaways

  • One shape first. Every source becomes the canonical table before anything else touches it.
  • The format hides in the details. The date format, the time unit and the scale are the three things to read off the vendor, never to guess.
  • Priority picks, tolerance warns. Merge by a stated order, and report disagreements with a tolerance instead of using ==.
Quick check
Your turn. A vendor writes dates as month/day/year, and a line says 05/04/2021. Which day is it?
Pick an answer.
08

What you will build

The lab follows the lecture. Task 1 parses the CSV vendor, task 2 the JSON-lines vendor and task 3 the vendor of lists. Task 4 merges several canonical tables by priority. Task 5 reports the dates on which the sources disagree. Task 6 runs the whole stage on three vendors that overlap on real SPY days, with one seeded error to find.

Next topic: you now have one table per source and one merged table. The next topic, Normalising symbols and calendars, deals with what the parsers cannot see: the same instrument written under different symbols, and days that exist in one market and not in another.

Lab · what's graded

6 tasks · 100 pts
  • Parse the CSV vendor15 pts
  • Parse the JSON-lines vendor15 pts
  • Parse the vendor of lists15 pts
  • Merge by priority20 pts
  • Find the disagreements15 pts
  • The study on the SPY table20 pts
Explorer · lab-dp-01
▾ lab-dp-01
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-dp-01$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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