Skip to Content
While25SDK docs
ExamplesApps and panels

Quote recorder: a long-running loop that writes a CSV

Samples the quotes of a few ETFs once a second during regular hours and appends them to a CSV in the workspace, one file per day, with a small panel that shows how many rows it has written. A `run()` loop is the escape hatch for work the decorators do not cover; it checks `alive()` every pass so it stops the moment it is asked to.

Samples the quotes of a few ETFs once a second during regular hours and appends them to a CSV in the workspace, one file per day, with a small panel that shows how many rows it has written. A run() loop is the escape hatch for work the decorators do not cover; it checks alive() every pass so it stops the moment it is asked to.

Shows: run() and while25.alive(), quotes() with None entries, quote as_of and market_open, subscribe() in on_start, a CSV per day in data/, ui.layout(ui.row(ui.metric...)), ui.text.

View on GitHub

apps/quote_recorder.py
"""Quote recorder: a long-running loop that writes a CSV

Samples the quotes of a few ETFs once a second during regular hours and
appends them to a CSV in the workspace, one file per day, with a small panel
that shows how many rows it has written. A `run()` loop is the escape hatch
for work the decorators do not cover; it checks `alive()` every pass so it
stops the moment it is asked to.

Shows: run() and while25.alive(), quotes() with None entries, quote as_of and market_open, subscribe() in on_start, a CSV per day in data/, ui.layout(ui.row(ui.metric...)), ui.text.
"""
import csv
import time
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

import while25
from while25 import App, ui

KEYS = ["EQ:US:SPY", "EQ:US:QQQ", "EQ:US:IWM", "EQ:US:DIA"]
NY = ZoneInfo("America/New_York")
FIELDS = ["sampled_at", "symbol", "ltp", "bid", "ask", "volume", "as_of"]

ui.panel("quote_recorder", "Quote recorder")
ui.layout(ui.row(ui.metric("rows", "Rows written"), ui.metric("missing", "Symbols without data")),
          ui.text("file", "Writing to"))


def rows_for(keys, quotes, sampled_at):
    """CSV rows for one sample; a symbol with no data yet is left out."""
    return [{"sampled_at": sampled_at, "symbol": k, "ltp": q["ltp"], "bid": q["bid"],
             "ask": q["ask"], "volume": q["volume"], "as_of": q["as_of"]}
            for k, q in zip(keys, quotes) if q is not None]


def day_file(day):
    return Path("data/quotes") / f"{day.isoformat()}.csv"


class QuoteRecorder(App):
    id = "quote_recorder"
    label = "Quote recorder"

    def on_start(self, ctx):
        for k in KEYS:
            while25.subscribe(k)

    def run(self, ctx):
        written = 0
        while while25.alive():
            now = datetime.now(NY)
            quotes = while25.quotes(KEYS)
            if any(q and q["market_open"] for q in quotes):
                path = day_file(now.date())
                path.parent.mkdir(parents=True, exist_ok=True)
                new = not path.exists()
                rows = rows_for(KEYS, quotes, now.isoformat(timespec="seconds"))
                with path.open("a", newline="") as f:
                    w = csv.DictWriter(f, fieldnames=FIELDS)
                    if new:
                        w.writeheader()
                    w.writerows(rows)
                written += len(rows)
                while25.ui.push("rows", written)
                while25.ui.push("missing", len(KEYS) - len(rows))
                while25.ui.push("file", str(path))
            time.sleep(1)