Before Acquiring ETF Data: Sources, Price Definitions, and Quality Checks
Receiving a price file is different from establishing that it is ready for research. Code can detect duplicate dates and missing prices, but the meaning of close, adjustment methodology, and retention/sharing permissions require provider documentation and terms.
This article separates criteria set before acquisition from small checks performed afterward. The checks use a deliberately faulty synthetic CSV, not actual ETF prices.
It concerns the initial research-design stage. Subsequent real SPY/IEF/GLD results appear in the 12-month momentum baseline comparison. The synthetic checks here have not newly been applied to that dataset.
1. Specify acceptance conditions before downloading
Selecting SPY, IEF, GLD, and a research period does not mean a suitable file has already been acquired.
| Item | Record | If unknown |
|---|---|---|
| Source/access | Provider, API/download location, authentication | Mark unverified |
| Asset identity | Research ID, provider symbol, product, exchange, currency | Do not equate products by ticker alone |
| Requested range | Start/end, frequency, included sessions | Separate requested and returned periods |
| Price definition | Column, adjusted events, method | Defer return-column selection |
| Date definition | Trading date or timestamp, timezone, conversion | Do not equate UTC date and trading date arbitrarily |
| Usage terms | Research, retention, derived-output and raw-data sharing terms; check date | Do not assume publication is permitted |
This is a collection checklist, not a report that a provider's terms were checked. Access does not itself authorize redistribution. Record supporting terms and their review date, and determine raw-data sharing scope from applicable conditions.
Distinguish these ranges:
Requested acquisition rangeActually returned observation rangeWarm-up range needed for indicatorsRange eligible for strategy evaluationThey can differ. The first file row need not already support every required indicator.
2. Define how prices will be used, not just their column names
This working dictionary must be refined using provider definitions.
| Field | Meaning to verify | Risk of confusion |
|---|---|---|
Close | Trade, session, and calculation defining the close | Comparing same-date values on different bases |
Adjusted Close | Which corporate actions are adjusted and how | Treating adjusted prices as executable prices or actual share-count inputs |
| Distributions/splits | Amounts, ratios, reference and effective dates | Counting an effect already embedded in prices twice |
Volume | Units, session, allowed representation | Rejecting valid data or accepting invalid data |
| NAV | Whether the value represents net asset value | Treating it as the exchange market price |
Adding dividends as cash income to returns from a dividend-adjusted series can double-count them. Determine the price definition first.
The later baseline uses adjclose as a price index approximating dividend reinvestment and distinguishes its modeled units from actual shares. State both the chosen column and its computational interpretation.
3. Preserve raw data, transformations, and checks separately
Raw input and acquisition metadata→ normalized copy with transformation history→ quality-check report→ documented handling decisions→ accepted version used for researchRetain raw files only as permitted by provider terms. Do not overwrite them during normalization or correction.
| Artifact | Contents |
|---|---|
| Raw input/acquisition metadata | Provider, request, collection time, filename, raw hash |
| Normalized data/transformation history | Date/column/type rules, code version, links to original rows |
| Check report | Rules, issue types, affected rows/counts, environment |
| Handling decisions | Keep, exclude, replace, or defer; reasons and evidence |
| Research input | Accepted version, normalized hash, remaining limits |
Python's standard library can calculate SHA-256. hashlib documentation
A raw-file hash compares downloaded bytes. A normalized-data hash compares inputs created under specified ordering, column, numeric-format, and encoding rules. Whitespace or metadata changes can alter raw hashes; normalization-rule changes alter the meaning of normalized comparisons.
Matching hashes establish neither economic price accuracy nor that the same values were available historically.
4. Run checks on a deliberately faulty synthetic CSV
The data and tickers SYN_A, SYN_B, and SYN_C are fictional. This example requires:
- Columns
ticker,date,close, andvolume. - Dates in exact
YYYY-MM-DDformat. - Nondecreasing input dates within each ticker.
- Unique ticker/date pairs.
- Finite positive prices.
- Finite nonnegative integer volumes.
The volume rule is this example's contract, not a universal provider rule. Put the following blocks in one file in order; no external packages are required.
Inputs and inspection functions
import csvimport iofrom collections import defaultdictfrom copy import deepcopyfrom datetime import datefrom decimal import Decimal, InvalidOperationFIELDS = ("ticker", "date", "close", "volume")def number(text): try: result = Decimal(text) except InvalidOperation: return None return result if result.is_finite() else Nonedef inspect(rows): if not rows: raise ValueError("EMPTY_INPUT") issues = {key: [] for key in ( "bad_date", "not_ascending", "duplicate_key", "missing_required", "bad_price", "bad_volume", )} seen = defaultdict(list) previous = {} for row_id, raw in enumerate(rows, 1): if any(key not in raw for key in FIELDS): raise ValueError(f"SCHEMA_ERROR row={row_id}") if any( raw[key] is not None and not isinstance(raw[key], str) for key in FIELDS ): raise ValueError(f"TYPE_ERROR row={row_id}") row = { key: (raw[key] or "").strip() for key in FIELDS } if any(not row[key] for key in FIELDS): issues["missing_required"].append(row_id) day = None if row["date"]: try: day = date.fromisoformat(row["date"]) if day.isoformat() != row["date"]: day = None except ValueError: pass if day is None: issues["bad_date"].append(row_id) ticker = row["ticker"] if ticker and day is not None: seen[(ticker, day)].append(row_id) if ticker in previous and day < previous[ticker]: issues["not_ascending"].append(row_id) previous[ticker] = day if row["close"]: price = number(row["close"]) if price is None or price <= 0: issues["bad_price"].append(row_id) if row["volume"]: volume = number(row["volume"]) if ( volume is None or volume < 0 or volume != volume.to_integral_value() ): issues["bad_volume"].append(row_id) issues["duplicate_key"] = sorted( row_id for group in seen.values() if len(group) > 1 for row_id in group ) return issuesdef require_valid(issues): bad_rows = sorted({ row for rows in issues.values() for row in rows }) if bad_rows: raise ValueError(f"QUALITY_FAILED rows={bad_rows}")Decimal can parse special values such as NaN and Infinity, so successful conversion is insufficient; check is_finite() too. Python decimal documentation
Inspection neither sorts nor deletes original rows. Whitespace stripping applies only to a separate inspection copy. Row numbers count data records excluding the header; in real processing, associate them with a file identifier to distinguish versions.
Synthetic input
sample = """ticker,date,close,volumeSYN_A,2025-01-03,100,100SYN_A,2025-01-02,,100SYN_A,2025-01-02,99,-1SYN_B,2025-01-02,-101,50.5SYN_B,2025-01-03,Infinity,100SYN_B,not-a-date,101,100,2025-01-03,100,100SYN_C,2025-01-02,NaN,100SYN_C,2025-01-03,abc,Infinity"""rows = list(csv.DictReader(io.StringIO(sample)))before = deepcopy(rows)issues = inspect(rows)expected = { "bad_date": [6], "not_ascending": [2], "duplicate_key": [2, 3], "missing_required": [2, 7], "bad_price": [4, 5, 8, 9], "bad_volume": [3, 4, 9],}assert issues == expectedassert rows == beforefor name, found in issues.items(): print(f"{name}: count={len(found)} rows={found}")try: require_valid(issues)except ValueError as error: print(error)else: raise AssertionError("invalid input was accepted")Output:
bad_date: count=1 rows=[6]not_ascending: count=1 rows=[2]duplicate_key: count=2 rows=[2, 3]missing_required: count=2 rows=[2, 7]bad_price: count=4 rows=[4, 5, 8, 9]bad_volume: count=3 rows=[3, 4, 9]QUALITY_FAILED rows=[2, 3, 4, 5, 6, 7, 8, 9]| Check | Rows detected | Reason |
|---|---|---|
| Invalid date | 6 | not-a-date cannot be parsed |
| Reversed date order | 2 | Earlier than the preceding valid date for that ticker |
| Duplicate composite key | 2, 3 | Repeated SYN_A / 2025-01-02 |
| Missing required value | 2, 7 | Blank price or ticker |
| Invalid price | 4, 5, 8, 9 | Negative, infinity, NaN, or nonnumeric text |
| Invalid volume | 3, 4, 9 | Negative, fractional, or infinite |
Two duplicate findings mean two rows belong to one duplicate-key group, not two duplicate groups. Counts across checks also differ from the number of problematic rows: one row can fail multiple checks. Eight of nine rows have issues.
An empty string is missing_required; string NaN is bad_price. Actual provider missing-value conventions need a separate rule.
Confirm valid input passes too
Testing only bad input cannot distinguish a checker that rejects everything. Include a small valid case:
good = [ { "ticker": ticker, "date": day, "close": "100", "volume": "0", } for ticker in ("SYN_A", "SYN_B") for day in ("2025-01-02", "2025-01-03")]require_valid(inspect(good))print("CLEAN_SYNTHETIC: PASS")Output:
CLEAN_SYNTHETIC: PASSAllowing zero volume follows the stated contract. It does not prove a real trade was possible.
5. Stop calculation on errors and record handling decisions
inspect() reports issues; require_valid() prevents further calculation when issues remain. The example catches an exception to display the expected failure. A real workflow must not catch it and silently continue backtesting.
Do not automatically delete or fill every problematic value.
| Finding | Investigate | Record |
|---|---|---|
| Reversed dates | Provider's native order or mixed file assembly? | Sorting rule and raw-row mapping |
| Duplicate ticker/date | Identical duplicate, conflicting values, or revision? | Selection rule and exclusion evidence |
| Blank price | Provider missing marker or collection/transformation failure? | Original value and findings |
| Nonfinite/text value | Parse failure or provider error representation? | Error category and reason for deferral |
| Volume violation | Expected units and aggregation definition? | Source of the volume contract |
Record original order before sorting. Conflicting duplicates make unsupported “keep first” rules inappropriate. Forward-filling also needs a decision: holidays, missing trading days, and missing individual fields are different problems.
The example does not automatically clean and export data. Its purpose is to separate detection from acceptance decisions.
6. An unperformed check has not passed
The code checks format, values, input order, and duplicates. Additional checks need further evidence:
| Question | Required evidence/rule | Status here |
|---|---|---|
| Missing trading-day rows | Applicable market/product calendar and period | Not checked |
| Rows outside listing/trading life | Product validity periods | Not checked |
| Cross-asset date mismatch | Asset ranges and alignment policy | Not checked |
| Whether a large move is erroneous | Corporate actions, adjustment definitions, other evidence | Not checked |
| Historical availability | Historical publication/revision records | Not checked |
| Price correctness | Independent comparison data | Not checked |
Equal date sets do not prove calendar completeness: the same day can be missing from both assets. Conversely, taking only the intersection can hide gaps. Investigate date differences before choosing a policy.
An extreme-move threshold identifies a candidate for investigation, not sufficient grounds to alter a price before its cause is understood.
7. Separate this execution from later real-data work
The synthetic checks ran with Python 3.14.5 and the standard library while preparing the revision on 2026-10-24.
| Check | Result |
|---|---|
| Issue categories and row numbers in nine synthetic rows | Expected results matched |
| Blocking invalid input | QUALITY_FAILED |
| Valid synthetic input | Passed |
| Empty input | Rejected with EMPTY_INPUT |
| Missing required columns | Rejected with SCHEMA_ERROR |
| Impossible date or date without separators | Detected |
Zero price, negative infinity, special NaN, volume NaN | Detected as value errors |
| Original input before/after inspection | Unchanged |
These are new results from the revision's code and synthetic inputs, not a retroactive claim that the original unexecuted example had run.
Later real-data work is available in:
- SPY/IEF/GLD baseline article.
- Execution and data-interpretation guide.
- Results JSON with periods, row counts, and hashes.
That JSON records Yahoo Finance adjclose, input dates 2005-01-03 through 2025-12-31, and evaluation dates 2007-01-03 through 2025-12-31. Raw-file and normalized-price hashes are separate.
The revision checked that record; it did not redownload ETF inputs or rerun the backtest. Public hashes also do not guarantee that outside readers can obtain the identical raw snapshot.
Data preparation is complete for this article when three questions can be answered:
- Which source and definitions will be used?
- Which checks ran, what did they find, and what remains unchecked?
- Which evidence supports handling decisions and the accepted input version?
Next, examine the time contract for signals, execution, and labels. Correctly formatted data can still distort research when used at the wrong time.
Report an error or share feedback
Open a draft with this article’s title and URL. Review the message and recipient before sending.
Open email draftIf no email app opens, copy these details into your usual email service.
Related posts
Quant & Data Research A Safe Way to Do Quant Research with LLMs: From Questions to Verification and Research Records
Review research-memo claims using synthetic prices and fixed rules; distinguish signal and holding returns and record checks, corrections, and unknowns.
Quant & Data Research What Makes a Good Backtest Different? Design Validation Before Looking at Returns
Compare random and chronological splits on a changing synthetic series, examining sample composition, accuracy, interpretation limits, and subsequent validation.