The same instrument arrives as BRK.B, BRK/B and NYSE:BRK.B, a trade at 01:30 UTC belongs to the evening before in New York, and a weekday with no row may be a holiday or a hole. In the first 300 days of SPY there are 10 holidays, and removing two rows creates 2 gaps that are not holidays.
One name, one clock, one calendar
Where we are: the last topic turned three vendor formats into one canonical bar table and merged them. Each table now has the same columns, but the contents still do not agree on three things that every pipeline must settle before it joins any two sources: what an instrument is called, which calendar day an event belongs to, and which days should have data at all. By the end of this topic you will be able to write a symbol cleaner, convert UTC time stamps to a market's session date, list the trading days between two dates and find the days a table is missing.
Start with names. A ticker symbol is how one market or vendor labels an instrument, and there is no single standard. One class of Berkshire Hathaway stock is written BRK.B, BRK/B, BRK B or NYSE:BRK.B, depending on who sends it. If you join tables on the raw text, the same company becomes four companies and the join silently drops rows. Making all the spellings equal is called normalising. Upper-casing is the first idea that comes to mind, and the code below shows that it is nowhere near enough (the symbols here are another company's, Brown-Forman, so that the lab's own symbols stay yours to solve).
raw = ["BF.B", "bf/b", "NYSE:BF.B", "BF B", "bf_b.us"]print(len(set(raw)), "spellings,", len({s.strip().upper() for s in raw}), "after upper-casing")
5 spellings, 5 after upper-casing
A symbol is also not an identity. Exchanges reuse tickers: FB was the ticker of one company for years and later belonged to a different one, so a table keyed only by the ticker can glue two companies into one history. Serious data stores therefore add an identifier that never changes, and keep the ticker as a label that is valid for a date range. The lab keeps to tickers, but remember the limit: a canonical symbol makes spellings equal, it does not make a symbol permanent.
The one agreed spelling of an instrument's ticker, chosen by rules, such as upper case with a single dash between the company and the share class. Every table of the pipeline uses it as the join key.
Rules that clean a symbol
A cleaner is a short list of rules applied in a fixed order, then a check that the result has the shape you expect. The order matters, because a rule can only see what the earlier rules left behind. The method has four steps.
- 1Trim and fold the case
strip()removes spaces at the ends,upper()makes the case the same. - 2Drop the decorationsRemove what is not part of the name: an exchange prefix before a
:and a vendor suffix such as.US. - 3Replace the separatorsTurn every separator the vendors use into the one you chose. A regular expression with a character class does this in one call.
- 4Check the shapeMatch the whole result against the pattern of a valid symbol and raise
ValueErrorif it does not fit, so a bad symbol stops the pipeline instead of becoming a new instrument.
Worked example 1. *Problem:* a crypto vendor sends pairs such as btc/usd, BTC_USD, Btc usd and KRAKEN:BTC.USD. Make them all BTC-USD, and reject btc. *Plan:* the exchange name before the colon is a decoration; /, _, . and a space are separators; a valid pair is three to five letters, a dash, three letters. *Steps:* trim and fold, drop the prefix, replace the separators, check the shape.
def tidy(raw): pair = raw.strip().upper().split(":")[-1]1 pair = re.sub(r"[./_ ]", "-", pair)2 if not re.fullmatch(r"[A-Z]{3,5}-[A-Z]{3}", pair):3 raise ValueError(f"not a pair: {raw!r}") return pairfor raw in ["btc/usd", "BTC_USD", "Btc usd", "KRAKEN:BTC.USD"]: print(repr(raw), "->", tidy(raw))try: tidy("btc")except ValueError as error: print("ValueError:", error)
'btc/usd' -> BTC-USD 'BTC_USD' -> BTC-USD 'Btc usd' -> BTC-USD 'KRAKEN:BTC.USD' -> BTC-USD ValueError: not a pair: 'btc'
- 1split(':')[-1] keeps what follows the last colon, and the whole text when there is none.
- 2One character class replaces every separator.
- 3fullmatch checks the whole text, not a piece of it.
*Check:* the four spellings print the same pair, and btc stops with an error. *What to notice:* the simple method of upper-casing, which the first figure tried, fails because the differences are not only in the case. Also notice that the rules never look up a list of known pairs: they work for a pair that you have not met.
Normalising must never merge two different instruments. BRK.A and BRK.B are two classes of shares with very different prices; after cleaning they must still be BRK-A and BRK-B. A cleaner that drops the class letter to be tidy would join them and corrupt every price.
New York time without a time zone database
Now time. Vendors stamp events in UTC, but a market's day follows its own clock. A trade at 01:30 UTC on 2 March is still the evening of 1 March in New York, so it belongs to the session of the 1st. If a pipeline files it under the 2nd, it lands in a day on which the market had not opened yet. To find the market's date you add an offset in hours to the UTC time, and the offset is not constant: it changes by one hour when daylight saving time starts and ends.
A daily bar has only a date, which looks like it avoids the problem, but the date was decided somewhere by exactly this rule: the vendor assigned each trade to a session before it summed them. If two vendors assign sessions with different clocks, their daily volumes differ without either being wrong, which is a common reason why "the same" volume does not match across sources. Intraday data keeps the full time stamp, so the conversion must be done by you.
Production code usually asks a time zone database for the offset. Here you write the rule yourself, which shows exactly what the database knows. A rule has a start moment and an end moment each year, found as "the second Sunday of March" or "the last Sunday of October". Two worked examples show the two ideas you need: adding a fixed offset to get a date, and finding a Sunday in a month.
Worked example 2. *Problem:* Tokyo has no daylight saving time and is 9 hours ahead of UTC. Which Tokyo date does a trade at 2021-03-01T20:00:00Z have, and one at 2021-03-01T14:59:59Z? *Plan:* parse the text, add 9 hours, keep the date. *Steps:* strptime, add a timedelta, strftime.
def tokyo_date(stamp): utc = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ") return (utc + timedelta(hours=9)).strftime("%Y-%m-%d")1print(tokyo_date("2021-03-01T20:00:00Z"), tokyo_date("2021-03-01T14:59:59Z"))
2021-03-02 2021-03-01
- 1Adding the offset moves the clock; the date follows from the shifted time.
*Check:* 20:00 plus 9 hours is 05:00 the next day, and 14:59:59 plus 9 hours is 23:59:59 the same day, so the two dates differ although the instants are only five hours apart. *What to notice:* the date of a time stamp is not a property of the stamp, it is a property of the stamp and a place.
Worked example 3. *Problem:* London is at UTC+0 in winter and UTC+1 in summer. Summer time starts on the last Sunday of March at 01:00 UTC and ends on the last Sunday of October at 01:00 UTC. Give the offset at four moments around the changes in 2021. *Plan:* first a helper that finds the last Sunday of a month: calendar.monthcalendar lists the weeks of a month as rows of seven numbers, Monday first, with 0 for days of other months, so the Sunday is the last number of a row. Then compare the moment with the two change moments.
def last_sunday(year, month): weeks = calendar.monthcalendar(year, month) return max(week[6] for week in weeks if week[6])1def london_offset(utc): starts = datetime(utc.year, 3, last_sunday(utc.year, 3), 1) ends = datetime(utc.year, 10, last_sunday(utc.year, 10), 1) return 1 if starts <= utc < ends else 02print(last_sunday(2021, 3), last_sunday(2021, 10))for stamp in ["2021-03-28T00:59:59", "2021-03-28T01:00:00", "2021-10-31T00:59:59", "2021-10-31T01:00:00"]: print(stamp, london_offset(datetime.fromisoformat(stamp)))
28 31 2021-03-28T00:59:59 0 2021-03-28T01:00:00 1 2021-10-31T00:59:59 1 2021-10-31T01:00:00 0
- 1Sunday is the last column (index 6); 0 means the day belongs to another month.
- 2The start moment is included, the end moment is not.
*Check:* the last Sundays of March and October 2021 were the 28th and the 31st, and the offset changes exactly at the first printed moment of each change (1 from 01:00 UTC on 28 March, 0 from 01:00 UTC on 31 October). *What to notice:* the simple method, assuming a fixed offset of 0 or 1 all year, is wrong for half the year. The boundary tests (one second before, and at, the change) are the ones that find an off-by-one error in a rule like this.
The US moved its daylight saving dates in 2007, and other countries change theirs more often. A rule written from today's law is correct only for recent dates. That is why production systems read the rules from a maintained time zone database, and why this lab only asks for years from 2008 on.
Trading calendars
A trading calendar is the third thing that every source must agree on. Most markets are closed on weekends and on a list of holidays, and the list is different for every market and every year (Good Friday is a US exchange holiday but not a bank holiday, Easter Monday is closed in Europe and open in New York). The calendar is therefore data, not code: a function takes the holiday list as an argument and returns the open days. A pipeline that hard-codes weekday < 5 thinks every holiday is a missing day.
Worked example 4. *Problem:* a market closes on Good Friday (2 April 2021) and Easter Monday (5 April 2021). List its open days from 31 March to 7 April. *Plan:* pd.bdate_range gives every weekday between two dates; keep the ones that are not in the holiday list, compared as text. *Steps:* weekdays, format, filter.
holidays = ["2021-04-02", "2021-04-05"]days = [d.strftime("%Y-%m-%d") for d in pd.bdate_range("2021-03-31", "2021-04-07") if d.strftime("%Y-%m-%d") not in holidays]print(days)
['2021-03-31', '2021-04-01', '2021-04-06', '2021-04-07']
*Check:* eight calendar days contain six weekdays, and removing the two holidays leaves four, so the printed list has four dates. *What to notice:* the dates are compared as text with the text of the holiday list. If you compared a timestamp with a text, nothing would match and no holiday would ever be removed.
pd.bdate_range returns timestamps, and a holiday list holds texts. A timestamp is never equal to a text, so a comparison between them removes nothing and raises no error. Format the timestamps with strftime first, or turn the holidays into timestamps, but never mix them.
Half days, such as the afternoon of the day after Thanksgiving, are open days with a shorter session. They have rows, so they never appear as gaps, but their volume is much lower than a normal day. A calendar that only lists open days cannot tell you that; a quality rule on volume can, and the next topics come back to it.
Missing days
With a calendar you can ask the question that finds holes: which open days does this table not have? A day that is a holiday is normal, a day that is open and absent is a finding that someone must explain. Only the days between the first and the last date count. A table that simply ends early looks complete, and detecting that is a different check, one that compares the table with how fresh the source is.
Worked example 5. *Problem:* using the open days of the last example, find the ones missing from a table that has 2021-03-31, 2021-04-01 and 2021-04-07. *Plan:* build a set of the dates the table has, then keep each open day that is not in the set. *Steps:* open days, set, filter.
holidays = ["2021-04-02", "2021-04-05"]days = [d.strftime("%Y-%m-%d") for d in pd.bdate_range("2021-03-31", "2021-04-07") if d.strftime("%Y-%m-%d") not in holidays]have = {"2021-03-31", "2021-04-01", "2021-04-07"}print([day for day in days if day not in have])
['2021-04-06']
*Check:* the two April holidays are not reported, and the open day 2021-04-06 is. *What to notice:* the report is only as good as the holiday list: a holiday that is missing from the list turns a normal closure into an alarm, and a day that is wrongly in the list hides a real hole.
A report of missing days is a to-do list, not a verdict. Each date on it has one of three explanations: the market was closed and the holiday list is incomplete, the source never had the day, or the pipeline lost it. Telling them apart means looking at the same date in a second source, which is what the merge from the last topic is for. A date that every source lacks is almost always a holiday you did not list.
Putting the calendar to work
In practice you run the check twice, on purpose. First on data you trust, to prove that the holiday list explains every gap (an empty report means the calendar is right). Then on the data you are testing, where every reported day is a real problem. The lab does this with two years of real SPY: the clean window has no unexplained gap, and after two rows are removed the check finds exactly those two days.
- FunctionQuestion it answers
- canonical_symbol(raw)What is this instrument called?shape check raises ValueError
- symbol_table(pairs)Which spellings map to one name?vendor is ignored
- eastern_offset(utc)How far is New York from UTC now?rules since 2007
- session_date(timestamps)Which market day does a UTC stamp belong to?keeps the input order
- trading_days(start, end, holidays)Which days was the market open?holiday list is data
- missing_days(frame, holidays)Which open days has the table skipped?inside first and last date only
What you will build
The lab follows the lecture. Task 1 cleans one symbol and task 2 builds the table of spellings. Task 3 gives the offset from UTC to New York and task 4 uses it to find session dates. Task 5 lists the trading days between two dates, task 6 finds the open days that a table skips, and task 7 runs the checks on two years of real SPY, in which two rows have been removed.
Next topic: you now agree on names, days and calendars. The next topic, Corporate actions and adjustment factors, deals with prices that look wrong on days that are present: a stock split changes the price by the split ratio overnight, and a pipeline must adjust for it before any two days can be compared.
Lab · what's graded
7 tasks · 100 pts- Clean a symbol15 pts
- Tabulate the spellings10 pts
- The New York offset15 pts
- The session date15 pts
- List the trading days10 pts
- Find the missing days10 pts
- The study on the SPY table25 pts