Forge Fate
Quant & Data Research

Before Acquiring ETF Data: Sources, Price Definitions, and Quality Checks

6 min read

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.

ItemRecordIf unknown
Source/accessProvider, API/download location, authenticationMark unverified
Asset identityResearch ID, provider symbol, product, exchange, currencyDo not equate products by ticker alone
Requested rangeStart/end, frequency, included sessionsSeparate requested and returned periods
Price definitionColumn, adjusted events, methodDefer return-column selection
Date definitionTrading date or timestamp, timezone, conversionDo not equate UTC date and trading date arbitrarily
Usage termsResearch, retention, derived-output and raw-data sharing terms; check dateDo 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:

text
Requested acquisition rangeActually returned observation rangeWarm-up range needed for indicatorsRange eligible for strategy evaluation

They 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.

FieldMeaning to verifyRisk of confusion
CloseTrade, session, and calculation defining the closeComparing same-date values on different bases
Adjusted CloseWhich corporate actions are adjusted and howTreating adjusted prices as executable prices or actual share-count inputs
Distributions/splitsAmounts, ratios, reference and effective datesCounting an effect already embedded in prices twice
VolumeUnits, session, allowed representationRejecting valid data or accepting invalid data
NAVWhether the value represents net asset valueTreating 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

text
Raw input and acquisition metadata→ normalized copy with transformation history→ quality-check report→ documented handling decisions→ accepted version used for research

Retain raw files only as permitted by provider terms. Do not overwrite them during normalization or correction.

ArtifactContents
Raw input/acquisition metadataProvider, request, collection time, filename, raw hash
Normalized data/transformation historyDate/column/type rules, code version, links to original rows
Check reportRules, issue types, affected rows/counts, environment
Handling decisionsKeep, exclude, replace, or defer; reasons and evidence
Research inputAccepted 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, and volume.
  • Dates in exact YYYY-MM-DD format.
  • 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

python
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

python
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:

text
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]
CheckRows detectedReason
Invalid date6not-a-date cannot be parsed
Reversed date order2Earlier than the preceding valid date for that ticker
Duplicate composite key2, 3Repeated SYN_A / 2025-01-02
Missing required value2, 7Blank price or ticker
Invalid price4, 5, 8, 9Negative, infinity, NaN, or nonnumeric text
Invalid volume3, 4, 9Negative, 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:

python
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:

text
CLEAN_SYNTHETIC: PASS

Allowing 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.

FindingInvestigateRecord
Reversed datesProvider's native order or mixed file assembly?Sorting rule and raw-row mapping
Duplicate ticker/dateIdentical duplicate, conflicting values, or revision?Selection rule and exclusion evidence
Blank priceProvider missing marker or collection/transformation failure?Original value and findings
Nonfinite/text valueParse failure or provider error representation?Error category and reason for deferral
Volume violationExpected 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:

QuestionRequired evidence/ruleStatus here
Missing trading-day rowsApplicable market/product calendar and periodNot checked
Rows outside listing/trading lifeProduct validity periodsNot checked
Cross-asset date mismatchAsset ranges and alignment policyNot checked
Whether a large move is erroneousCorporate actions, adjustment definitions, other evidenceNot checked
Historical availabilityHistorical publication/revision recordsNot checked
Price correctnessIndependent comparison dataNot 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.

CheckResult
Issue categories and row numbers in nine synthetic rowsExpected results matched
Blocking invalid inputQUALITY_FAILED
Valid synthetic inputPassed
Empty inputRejected with EMPTY_INPUT
Missing required columnsRejected with SCHEMA_ERROR
Impossible date or date without separatorsDetected
Zero price, negative infinity, special NaN, volume NaNDetected as value errors
Original input before/after inspectionUnchanged

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:

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:

  1. Which source and definitions will be used?
  2. Which checks ran, what did they find, and what remains unchecked?
  3. 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.

To: [email protected]

Open email draft

If no email app opens, copy these details into your usual email service.

Contact information