Export Python Stock Candles to CSV Without Losing the Query Context

TickDB Research ·

Stock candles with their context

A stock candle CSV is easy to download and surprisingly easy to misread a week later. A file called AAPL.csv cannot tell you whether its bars are daily or minute, adjusted or raw, or whether the API returned the whole window. Export two files together: the candles as CSV and a manifest recording the request, the series actually returned, and the exact CSV bytes.

Record the request and the response separately

The request describes what you intended to download. Keep the full symbol, asset type, interval, price adjustment, limit and any requested time bounds. Store a UTC time for the capture, and don't send the API key to the browser or include it in the manifest.

The response says what you actually received. TickDB's Candlestick Data endpoint returns the applied symbol, asset type, interval, and adjustment alongside its bars. Compare these fields with the request before writing the export. If you asked for unadjusted daily bars and received adjusted minute bars, reject the export instead of silently naming it after the requested series.

Export flow from query and response to a CSV and its manifest

Keep uncertainty visible

  • Window: Record row count and the earliest and latest returned labels. A request for ten records returning eight does not prove why two are absent, and a response returning ten does not prove complete coverage.
  • Time: Preserve the original integer millisecond labels in the CSV. Format times separately in the UI. A UTC timestamp does not, by itself, identify an exchange session or an exchange-local trading date.
  • Missing fields: A blank volume is not zero. Ignore neither the missing field nor the distinction when you import the file.
  • Finality: A recent candle can be provisional. If you cannot establish that a bar is final or that the window is complete, keep those states explicit rather than deriving them from row count or retrieval success.

A Python export you can check later

The sample requests ten unadjusted daily AAPL bars and writes a CSV plus a matching JSON manifest. The standard-library example needs a TickDB key in the server environment to make the request. The local checks below use synthetic payloads; they do not establish an account's permissions, the live feed's completeness, or an exchange timetable.

import csv, io, json, hashlib, os
from datetime import datetime, timezone
from urllib.parse import urlencode
from urllib.request import Request, urlopen

ENDPOINT = "https://api.tickdb.ai/v1/market/kline"
QUERY = dict(symbol="AAPL.US", type="stock", interval="1d", adjust="none", limit=10)
FIELDS = ("time", "open", "high", "low", "close", "volume")

def export(payload, query, pulled_at):
    if payload.get("code") != 0:
        raise ValueError("provider returned a business error")
    data = payload["data"]
    applied = {k: data[k] for k in ("symbol", "type", "interval", "adjust")}
    if any(query[k] != v for k, v in applied.items()):
        raise ValueError("response series does not match export request")
    bars = data["klines"]
    times = [row["time"] for row in bars]
    if any(type(t) is not int for t in times) or len(times) != len(set(times)):
        raise ValueError("invalid or duplicate bar timestamps")
    f = io.StringIO(newline="")
    writer = csv.DictWriter(f, fieldnames=FIELDS, lineterminator="\n")
    writer.writeheader()
    for row in sorted(bars, key=lambda r: r["time"]):
        writer.writerow({k: row.get(k) for k in FIELDS})
    content = f.getvalue().encode("utf-8")
    manifest = dict(request=query, applied=applied, queried_at_utc=pulled_at,
                    returned_rows=len(bars), first_ms=min(times, default=None),
                    last_ms=max(times, default=None), completeness="not established",
                    last_bar_finality="not established",
                    sha256=hashlib.sha256(content).hexdigest())
    return content, manifest

if __name__ == "__main__":
    from pathlib import Path
    req = Request(ENDPOINT + "?" + urlencode(QUERY),
                  headers={"X-API-Key": os.environ["TICKDB_API_KEY"]})
    with urlopen(req, timeout=20) as response:
        payload = json.load(response)
    now = datetime.now(timezone.utc).isoformat()
    content, manifest = export(payload, QUERY, now)
    Path("bars.csv").write_bytes(content)
    Path("bars.manifest.json").write_text(json.dumps(manifest, indent=2)+"\n")

Verify the handoff

Treat the two files as a pair. Recompute SHA-256 over the CSV bytes and compare it with the manifest before importing the result. A mismatch means the files no longer correspond; a match proves byte identity, not market-data accuracy. Keep a distinct export ID for each capture in a production downloader rather than overwriting a prior pair.

In the synthetic checks, out-of-order rows are sorted, missing volume stays blank while an explicit zero survives, the row count and digest match, and a different adjustment, different interval or duplicate timestamp is rejected. An empty response exports only the header and records no returned time bounds. It does not assert that the market was closed.

For the downloader in a stock dashboard, the practical rule is simple: export the data and what you know about it, not just what the chart happens to show.

Source checked: TickDB REST API documentation, Candlestick Data and Latest Candlesticks.

7 markets · 42,687 symbols

US stocks
14,386
Hong Kong market
3,353
China stocks, ETFs & bonds
7,576
Forex & metals
1,228
Indices
13,960
Futures
1,172
Crypto
1,012
11/24/2026

Related articles

Day Trading vs Settlement: Same-Day US Stock Trades Do Not Mean T+0 Settlement

Can you buy and sell a US stock on the same day, and does that mean it settles immediately? Same-day trading can be possible under applicable account rules, but most ordinary US stock transactions use T+1 settlement. Keeping trade date, expected settlement date and confirmed settlement status separate prevents a trading interface from presenting an executed sale as already settled cash.

TickDB Research ·

Yahoo Finance API Migration: Align Your Existing Data Before Switching Stock APIs

For financial product owners evaluating a replacement for a Yahoo Finance or yfinance prototype, a migration decision needs more than a successful request. This guide explains adjustment and date differences, compares old and new records, and connects findings to existing features. It includes an offline Python comparison tool, a browser-readable report, and an acceptance worksheet. A clearly labelled synthetic example demonstrates the decision process; the existing TickDB live sample is presented separately.

TickDB Research ·

Free Stock APIs: What to Check Before Moving From Research to an App

For product leads turning a research prototype into a market dashboard, choosing a free stock API takes more than getting a successful response. Using a 20-stock watchlist refreshed every ten seconds, this guide separates data access, request budgets, streaming limits and permitted use. It draws on official documentation for AKShare, Alpha Vantage, Twelve Data and TickDB, adds a recorded TickDB MCP query, and provides a practical decision worksheet and runnable Python quota calculator.

TickDB Research ·

The Complete Stock API Guide: 44 Global and China-Market Options

Bloomberg, LSEG, FactSet, Massive, Alpha Vantage, Databento, Wind, Tushare, and AKShare address very different data needs. This guide organizes 44 providers, platforms, and tools into ten categories, then maps them to investment research, backtesting, alerts, financial apps, AI workflows, and trading integrations. Use it to build a shortlist, understand access requirements, and test a realistic sample. It includes a complete Python example, downloadable-data workflows, and reusable requirements and acceptance checklists.

TickDB Research ·

Using a Stock API: Why Quote Displays and Research Exports Need Different Rules

For financial product managers building a stock page with a quote display and historical export, connecting the API is only part of the task. This guide explains how snapshots, price bars, and CSV files differ, why a record's timestamp does not establish when its final value was available, and how to turn saved TickDB responses into a timestamped static quote card and a date-filtered research CSV. A runnable Python example makes the output rules inspectable.

TickDB Research ·