From Zero to One: Building Your First US Stock Quant Strategy

The first quantitative strategy is rarely impressive because the signal is sophisticated. It is impressive because the entire pipeline works: data arrives, signals are generated, orders are simulated, and results are displayed without hidden assumptions.

That pipeline matters because a moving-average rule can look profitable in a chart and fail once execution timing, transaction costs, and data alignment enter the experiment. The beginner’s real task is not to discover alpha immediately. It is to build a system that tells the truth about a simple rule.

For programmers who have never worked with quantitative trading, this article walks through the first version of a complete workflow: acquiring US equity data, calculating a moving-average signal, running a historical backtest, and visualizing equity curves. The implementation uses Python and keeps the model intentionally simple so that every assumption remains visible.

1. What “Your First Strategy” Should Actually Do

A useful first strategy has four properties:

  1. It has a clear rule. For example, a fast moving average crosses above a slow moving average.
  2. It uses data you can inspect. Every candle should have a timestamp, open, high, low, and close.
  3. It makes decisions in chronological order. The model must never use a future bar to make a decision in the past.
  4. It includes a cost assumption. A backtest without transaction costs is usually an optimistic spreadsheet.

The strategy in this article uses:

  • A 20-session simple moving average, or SMA.
  • A 60-session simple moving average.
  • A long position when the fast SMA is above the slow SMA.
  • A cash position when the fast SMA is not above the slow SMA.
  • Signals executed on the next available bar.
  • A 0.05% transaction-cost assumption per position change.
  • A buy-and-hold benchmark.

This is not intended to be an investment recommendation or a claim that moving-average crossovers are inherently profitable. It is a controlled starting point for learning how a research idea becomes a testable system.

2. The Data Problem Comes Before the Strategy Problem

A backtest is only as trustworthy as its input data. In particular, a timestamp mistake can turn a nonexistent trading opportunity into an apparently profitable one.

The following example illustrates the problem:

Assumed price bar Signal available at Execution permitted at Problem
Daily close for day (t) Day (t), after close Day (t+1), at open Correct for a daily strategy
Daily close for day (t) Day (t+1), at open Day (t), at open Look-ahead bias
Intraday bar timestamp Bar close Same timestamp Possible timestamp misalignment
Missing session bar Previous close used as today’s close Immediately Incorrect return calculation

For a daily US-equity strategy, a simple rule is usually safer:

Calculate the signal after a bar closes, then execute on the next bar.

That rule avoids the most common version of look-ahead bias. It does not remove every possible issue, but it establishes a sound foundation for later work.

What the first dataset should contain

The initial dataset should contain one row per completed session with:

  • timestamp: the bar timestamp.
  • open: the session opening price.
  • high: the session high.
  • low: the session low.
  • close: the session close.
  • volume: traded volume, if available.

The code below uses the historical kline endpoint because the strategy needs completed daily bars rather than a live candle:

GET https://api.tickdb.ai/v1/market/kline

The API key is read from the TICKDB_API_KEY environment variable. It must not be hardcoded into a script or committed to source control.

3. System Architecture

The complete workflow has four layers:

┌──────────────────────────────────────────────────────────────┐
│ 1. DATA ACQUISITION                                          │
│    Historical US equity kline data                           │
│    Authentication, timeout, retries, rate-limit handling     │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ 2. FEATURE AND SIGNAL ENGINE                                 │
│    SMA(20), SMA(60), crossover state                         │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ 3. BACKTEST ENGINE                                           │
│    Next-bar execution, transaction costs, equity curve       │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ 4. VISUALIZATION AND REVIEW                                  │
│    Price, moving averages, drawdown, metrics, benchmark       │
└──────────────────────────────────────────────────────────────┘

The separation matters. When the result looks wrong, you can inspect each layer independently instead of changing the strategy, data loader, and chart code at the same time.

4. Install the Development Environment

Use Python 3.10 or later. Create a virtual environment and install the required packages:

python -m venv .venv
source .venv/bin/activate
pip install requests pandas numpy matplotlib

On Windows, activate the environment with:

.venv\Scripts\Activate.ps1

Set the API key in the current shell:

export TICKDB_API_KEY="your_api_key_here"

For a persistent local development setup, add the key to a .env file or your operating system’s environment-variable configuration. Do not place the key in the repository. A .gitignore entry like the following protects against accidental commits:

.env
.venv/
__pycache__/
*.csv
*.png

5. Production-Style Historical Data Downloader

The downloader below includes the resilience features that matter before the project grows:

  • Environment-variable authentication.
  • A timeout on every HTTP request.
  • Exponential backoff with jitter.
  • Rate-limit handling using error code 3001 and Retry-After.
  • A clear failure when the API key is missing.
  • A parser that accepts either a list or a common dictionary-based response shape.

Save the file as download_data.py:

import os
import random
import time
from typing import Any

import requests

API_BASE = "https://api.tickdb.ai/v1"
API_KEY = os.environ.get("TICKDB_API_KEY")

if not API_KEY:
    raise RuntimeError(
        "TICKDB_API_KEY is missing. "
        "Set it in the environment before running this script."
    )

HEADERS = {
    "X-API-Key": API_KEY,
    "Accept": "application/json",
}


def retry_after_seconds(response: requests.Response, fallback: int = 5) -> int:
    """Read the server's retry delay, falling back to a safe default."""
    value = response.headers.get("Retry-After", fallback)
    try:
        return max(1, int(float(value)))
    except (TypeError, ValueError):
        return fallback


def request_with_retries(
    method: str,
    url: str,
    *,
    params: dict[str, Any] | None = None,
    timeout: tuple[float, float] = (3.05, 20),
    max_attempts: int = 5,
) -> dict[str, Any]:
    """Send a request with timeout, backoff, jitter, and rate-limit handling."""
    for attempt in range(max_attempts):
        try:
            response = requests.request(
                method,
                url,
                headers=HEADERS,
                params=params,
                timeout=timeout,
            )
        except requests.Timeout:
            if attempt == max_attempts - 1:
                raise
            delay = min(2 ** attempt, 30)
            jitter = random.uniform(0, delay * 0.1)
            time.sleep(delay + jitter)
            continue
        except requests.RequestException:
            if attempt == max_attempts - 1:
                raise
            delay = min(2 ** attempt, 30)
            jitter = random.uniform(0, delay * 0.1)
            time.sleep(delay + jitter)
            continue

        if response.status_code == 429:
            if attempt == max_attempts - 1:
                raise RuntimeError("Rate limit remained active after retries.")
            time.sleep(retry_after_seconds(response))
            continue

        response.raise_for_status()

        try:
            payload = response.json()
        except ValueError as exc:
            raise RuntimeError("The API returned a non-JSON response.") from exc

        code = payload.get("code", 0)
        if code == 0:
            return payload

        if code in (1001, 1002):
            raise ValueError(
                "Invalid or missing API key. Check TICKDB_API_KEY."
            )

        if code == 2002:
            raise KeyError(
                "Symbol not found. Verify the symbol through the available-symbols endpoint."
            )

        if code == 3001:
            if attempt == max_attempts - 1:
                raise RuntimeError("Rate limit remained active after retries.")
            time.sleep(retry_after_seconds(response))
            continue

        raise RuntimeError(
            f"Unexpected TickDB error {code}: {payload.get('message', 'unknown error')}"
        )

    raise RuntimeError("Request failed after the maximum number of attempts.")


def extract_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:
    """Extract candle rows from common response containers."""
    data = payload.get("data", payload)

    if isinstance(data, list):
        return data

    if isinstance(data, dict):
        for key in ("klines", "candles", "items", "list", "records"):
            rows = data.get(key)
            if isinstance(rows, list):
                return rows

    raise ValueError(
        "Could not locate candle rows in the API response. "
        "Inspect one response before changing the parser."
    )


def download_daily_klines(symbol: str, limit: int = 5000) -> list[dict[str, Any]]:
    """Download completed daily candles for a US equity symbol."""
    payload = request_with_retries(
        "GET",
        f"{API_BASE}/market/kline",
        params={
            "symbol": symbol,
            "interval": "1d",
            "limit": limit,
        },
    )
    return extract_rows(payload)


if __name__ == "__main__":
    symbol = "AAPL.US"
    rows = download_daily_klines(symbol)

    if not rows:
        raise RuntimeError("The API returned no candle rows.")

    print(f"Downloaded {len(rows)} candles for {symbol}")
    print(rows[0])

Run it with:

python download_data.py

The parser is intentionally conservative. If the API response changes shape, the script fails with an explicit error rather than silently producing an empty or incorrectly aligned dataset.

A note on request frequency

The retry logic is designed for a research workload, not high-frequency trading. For a production HFT system, use an asynchronous HTTP client and a dedicated WebSocket ingestion layer. For a daily backtest, a bounded retry policy is more appropriate than aggressive polling.

6. Normalize the Data Before Calculating Indicators

Raw API data may use different field names or timestamp formats than the columns you want in your research model. Normalize once, then calculate indicators on the normalized frame.

Save this as prepare_data.py:

import pandas as pd

from download_data import download_daily_klines


COLUMN_ALIASES = {
    "timestamp": "timestamp",
    "time": "timestamp",
    "date": "timestamp",
    "datetime": "timestamp",
    "open": "open",
    "o": "open",
    "high": "high",
    "h": "high",
    "low": "low",
    "l": "low",
    "close": "close",
    "c": "close",
    "volume": "volume",
    "vol": "volume",
    "v": "volume",
}


def normalize_rows(rows: list[dict]) -> pd.DataFrame:
    """Normalize API candle fields into a stable research schema."""
    if not rows:
        raise ValueError("No rows were provided.")

    frame = pd.DataFrame(rows)

    frame = frame.rename(
        columns={
            column: COLUMN_ALIASES[column.lower()]
            for column in frame.columns
            if column.lower() in COLUMN_ALIASES
        }
    )

    required = {"timestamp", "open", "high", "low", "close"}
    missing = required.difference(frame.columns)
    if missing:
        raise ValueError(
            f"Missing required columns: {sorted(missing)}. "
            f"Available columns: {list(frame.columns)}"
        )

    frame["timestamp"] = pd.to_datetime(frame["timestamp"], utc=True)
    frame["timestamp"] = frame["timestamp"].dt.tz_localize(None)

    for column in ("open", "high", "low", "close"):
        frame[column] = pd.to_numeric(frame[column], errors="raise")

    if "volume" in frame.columns:
        frame["volume"] = pd.to_numeric(frame["volume"], errors="coerce")

    frame = frame.sort_values("timestamp").drop_duplicates("timestamp")
    frame = frame.set_index("timestamp")

    return frame[["open", "high", "low", "close"] + (
        ["volume"] if "volume" in frame.columns else []
    )]


def load_market_data(symbol: str = "AAPL.US") -> pd.DataFrame:
    """Download and normalize daily data for one US equity."""
    rows = download_daily_klines(symbol)
    return normalize_rows(rows)


if __name__ == "__main__":
    data = load_market_data()
    print(data.head())
    print(data.tail())
    print(f"Rows: {len(data)}")

Check the output before proceeding. In particular, verify:

  • The first and last timestamps belong to plausible trading sessions.
  • The rows are sorted in ascending timestamp order.
  • Prices are positive and internally consistent.
  • The data does not contain an obvious future period.
  • Missing values have been handled deliberately.

7. Implement the Moving-Average Strategy

The signal rule is straightforward:

  • Compute sma_fast, the 20-session simple moving average.
  • Compute sma_slow, the 60-session simple moving average.
  • Set the desired position to 1 when sma_fast > sma_slow.
  • Set the desired position to 0 otherwise.
  • Shift the position by one bar before calculating returns.

The shift is the most important implementation detail. A signal calculated from the close of bar (t) cannot also be executed at the close of bar (t) unless the strategy explicitly models that possibility.

Save the code as strategy.py:

import pandas as pd


def add_sma_signals(
    data: pd.DataFrame,
    fast_window: int = 20,
    slow_window: int = 60,
) -> pd.DataFrame:
    """Add moving averages and a next-bar position signal."""
    if fast_window >= slow_window:
        raise ValueError("fast_window must be smaller than slow_window.")
    if len(data) < slow_window + 1:
        raise ValueError(
            f"At least {slow_window + 1} rows are required, "
            f"but only {len(data)} were provided."
        )

    result = data.copy()

    result["sma_fast"] = result["close"].rolling(fast_window).mean()
    result["sma_slow"] = result["close"].rolling(slow_window).mean()

    result["desired_position"] = (
        result["sma_fast"] > result["sma_slow"]
    ).astype(float)

    # A signal calculated at the close of t becomes tradable on t+1.
    result["position"] = result["desired_position"].shift(1).fillna(0.0)

    return result


def calculate_strategy_returns(
    data: pd.DataFrame,
    transaction_cost: float = 0.0005,
) -> pd.DataFrame:
    """Calculate daily returns using the shifted strategy position."""
    result = data.copy()

    result["market_return"] = result["close"].pct_change().fillna(0.0)
    result["strategy_gross_return"] = (
        result["position"] * result["market_return"]
    )

    result["position_change"] = result["position"].diff().abs().fillna(
        result["position"].abs()
    )
    result["transaction_cost"] = (
        result["position_change"] * transaction_cost
    )
    result["strategy_net_return"] = (
        result["strategy_gross_return"] - result["transaction_cost"]
    )

    return result

The cost model charges the configured percentage whenever the absolute position changes. It does not yet model bid-ask spread, market impact, commissions, taxes, borrow costs, or partial fills. Those limitations matter when comparing the result with live execution.

8. Build the Backtest Engine

A backtest should make every assumption visible. The engine below calculates:

  • Strategy net returns.
  • Buy-and-hold returns.
  • Total return.
  • Annualized return.
  • Annualized volatility.
  • Sharpe ratio.
  • Sortino ratio.
  • Maximum drawdown.
  • Maximum drawdown duration.
  • Win rate.
  • Profit factor.
  • Number of trades.
  • Buy-and-hold benchmark metrics.

Save it as backtest.py:

from dataclasses import dataclass

import numpy as np
import pandas as pd

from prepare_data import load_market_data
from strategy import add_sma_signals, calculate_strategy_returns


TRADING_DAYS = 252
RISK_FREE_RATE = 0.0


@dataclass
class PerformanceMetrics:
    total_return: float
    annualized_return: float
    annualized_volatility: float
    sharpe_ratio: float
    sortino_ratio: float
    max_drawdown: float
    max_drawdown_duration: int
    win_rate: float
    profit_factor: float
    number_of_trades: int

    def as_dict(self) -> dict[str, float | int]:
        return {
            "total_return": self.total_return,
            "annualized_return": self.annualized_return,
            "annualized_volatility": self.annualized_volatility,
            "sharpe_ratio": self.sharpe_ratio,
            "sortino_ratio": self.sortino_ratio,
            "max_drawdown": self.max_drawdown,
            "max_drawdown_duration": self.max_drawdown_duration,
            "win_rate": self.win_rate,
            "profit_factor": self.profit_factor,
            "number_of_trades": self.number_of_trades,
        }


def drawdown_duration(drawdown: pd.Series) -> int:
    """Return the longest number of consecutive underwater periods."""
    longest = 0
    current = 0

    for value in drawdown:
        if value < 0:
            current += 1
            longest = max(longest, current)
        else:
            current = 0

    return longest


def calculate_metrics(
    returns: pd.Series,
    position: pd.Series,
) -> PerformanceMetrics:
    """Calculate performance statistics for a daily return series."""
    clean_returns = returns.dropna()
    clean_position = position.reindex(clean_returns.index).fillna(0.0)

    if clean_returns.empty:
        raise ValueError("The return series is empty.")

    equity = (1.0 + clean_returns).cumprod()
    drawdown = equity / equity.cummax() - 1.0

    total_return = float(equity.iloc[-1] - 1.0)
    annualized_return = float(
        (1.0 + total_return) ** (TRADING_DAYS / len(clean_returns)) - 1.0
    )
    annualized_volatility = float(
        clean_returns.std(ddof=1) * np.sqrt(TRADING_DAYS)
    )

    if annualized_volatility == 0:
        sharpe_ratio = 0.0
    else:
        sharpe_ratio = float(
            (annualized_return - RISK_FREE_RATE) / annualized_volatility
        )

    downside_returns = clean_returns[clean_returns < 0]
    downside_deviation = float(
        downside_returns.std(ddof=1) * np.sqrt(TRADING_DAYS)
    ) if len(downside_returns) > 1 else 0.0

    sortino_ratio = (
        float((annualized_return - RISK_FREE_RATE) / downside_deviation)
        if downside_deviation > 0
        else 0.0
    )

    active_returns = clean_returns[clean_position != 0]
    wins = active_returns[active_returns > 0]
    losses = active_returns[active_returns < 0]

    win_rate = float((active_returns > 0).mean()) if len(active_returns) else 0.0

    if losses.empty or abs(losses.sum()) == 0:
        profit_factor = (
            float("inf") if wins.sum() > 0 else 0.0
        )
    else:
        profit_factor = float(wins.sum() / abs(losses.sum()))

    position_changes = clean_position.diff().abs()
    number_of_trades = int(position_changes.gt(0).sum())

    return PerformanceMetrics(
        total_return=total_return,
        annualized_return=annualized_return,
        annualized_volatility=annualized_volatility,
        sharpe_ratio=sharpe_ratio,
        sortino_ratio=sortino_ratio,
        max_drawdown=float(drawdown.min()),
        max_drawdown_duration=drawdown_duration(drawdown),
        win_rate=win_rate,
        profit_factor=profit_factor,
        number_of_trades=number_of_trades,
    )


def run_backtest(
    data: pd.DataFrame,
    fast_window: int = 20,
    slow_window: int = 60,
    transaction_cost: float = 0.0005,
) -> tuple[pd.DataFrame, PerformanceMetrics, PerformanceMetrics]:
    """Run the moving-average strategy and the buy-and-hold benchmark."""
    enriched = add_sma_signals(data, fast_window, slow_window)
    enriched = calculate_strategy_returns(
        enriched,
        transaction_cost=transaction_cost,
    )

    strategy_metrics = calculate_metrics(
        enriched["strategy_net_return"],
        enriched["position"],
    )

    benchmark_position = pd.Series(1.0, index=enriched.index)
    benchmark_metrics = calculate_metrics(
        enriched["market_return"],
        benchmark_position,
    )

    return enriched, strategy_metrics, benchmark_metrics


if __name__ == "__main__":
    market_data = load_market_data(symbol="AAPL.US")
    results, strategy, benchmark = run_backtest(market_data)

    print("\nStrategy metrics")
    for key, value in strategy.as_dict().items():
        print(f"{key:28}: {value}")

    print("\nBuy-and-hold benchmark")
    for key, value in benchmark.as_dict().items():
        print(f"{key:28}: {value}")

Run the complete example with:

python backtest.py

The output is more important than the sophistication of the strategy. It tells you whether your implementation is internally consistent and gives you a baseline for later experiments.

9. Visualize the Strategy

Visualization is part of the research process, not decoration. A chart can reveal that the strategy enters during a sharp decline, that costs dominate the result, or that the equity curve is concentrated in a single trade.

Save the following as visualize.py:

import matplotlib.pyplot as plt

from backtest import run_backtest
from prepare_data import load_market_data


def plot_results(data, results):
    """Plot price, signal, equity, and drawdown."""
    figure, axes = plt.subplots(
        3,
        1,
        figsize=(14, 10),
        sharex=True,
        gridspec_kw={"height_ratios": [2, 1, 1]},
    )

    axes[0].plot(results["close"], label="Close", color="#222222")
    axes[0].plot(results["sma_fast"], label="SMA 20", color="#1976d2")
    axes[0].plot(results["sma_slow"], label="SMA 60", color="#d32f2f")
    axes[0].set_title("US Equity Price and Moving Averages")
    axes[0].set_ylabel("Price")
    axes[0].legend(loc="upper left")
    axes[0].grid(alpha=0.25)

    strategy_equity = (1.0 + results["strategy_net_return"]).cumprod()
    benchmark_equity = (1.0 + results["market_return"]).cumprod()

    axes[1].plot(strategy_equity, label="Strategy", color="#1976d2")
    axes[1].plot(benchmark_equity, label="Buy and Hold", color="#777777")
    axes[1].set_title("Equity Curves")
    axes[1].set_ylabel("Growth of $1")
    axes[1].legend(loc="upper left")
    axes[1].grid(alpha=0.25)

    drawdown = strategy_equity / strategy_equity.cummax() - 1.0
    axes[2].fill_between(
        drawdown.index,
        drawdown.values,
        0,
        color="#d32f2f",
        alpha=0.35,
    )
    axes[2].set_title("Strategy Drawdown")
    axes[2].set_ylabel("Drawdown")
    axes[2].grid(alpha=0.25)

    figure.tight_layout()
    figure.savefig("backtest_results.png", dpi=160)
    plt.show()


if __name__ == "__main__":
    data = load_market_data(symbol="AAPL.US")
    results, strategy, benchmark = run_backtest(data)
    plot_results(data, results)

The chart should contain:

  • The price series.
  • Both moving averages.
  • The strategy equity curve.
  • The buy-and-hold benchmark.
  • The strategy drawdown.

A moving-average crossover is easy to describe and easy to accidentally misread. The chart helps verify that the code behaves as the written rule implies.

10. Where the Strategy Can Go Wrong

The first backtest should be treated as a research instrument, not a deployment decision.

Transaction costs may be too small

The example uses a 0.05% cost per position change. That is a research assumption, not a universal market fact. Short-term strategies can be highly sensitive to spread, slippage, and market impact. Test several assumptions rather than hiding the choice inside one backtest.

The backtest may contain only one market regime

A moving-average strategy can perform well during a sustained trend and poorly during a range-bound market. Test multiple periods and compare at least:

  • A bullish period.
  • A bearish period.
  • A high-volatility period.
  • A low-volatility period.
  • A period containing large overnight gaps.

The sample may be too small

One symbol over two years does not provide enough evidence to establish a general edge. Use at least one full market cycle for exploratory work, and consider a broader universe once the basic pipeline is correct.

Survivorship bias changes the universe

Testing only companies that exist today can make historical results look artificially strong. If you expand beyond one symbol, define the universe historically and include delisted securities where possible.

The strategy may be trading an untradeable price

Daily bars do not reveal whether a specific closing price was available for execution. Limit orders, spread costs, halts, and large gaps can all change the result.

The benchmark must use the same period

Buy-and-hold should cover the same dates as the strategy. A benchmark that starts earlier or ends later is not a fair comparison.

11. A Practical Research Log

Keep a short log beside the code. For every experiment, record:

Field Example
Symbol AAPL.US
Date range Actual first and last session dates
Data source Historical daily kline endpoint
Fast window 20 sessions
Slow window 60 sessions
Execution Next bar, close-to-close approximation
Transaction cost 0.05% per position change
Sample size Number of daily bars
Strategy metrics Return, Sharpe, drawdown, win rate, profit factor
Benchmark Buy-and-hold over the same dates
Known limitations No market impact; one symbol; adjusted-price assumptions

The log prevents a common failure mode: remembering a promising result but forgetting which data period, cost assumption, or execution rule produced it.

12. Moving From a Daily Backtest to Real-Time Monitoring

The historical backtest is complete, but it is not connected to a live feed. A production monitoring system needs a different ingestion path.

For US equities, the available depth channel provides L1 order-book data. The data boundary is important: the depth channel is not a complete multi-level US equity order book in the same way it is for some other supported markets. Treat the order-book stream as a monitoring signal, not as a replacement for the historical execution model.

A WebSocket client should include:

  • Authentication through the api_key URL parameter.
  • A periodic ping heartbeat.
  • Exponential backoff with jitter after disconnects.
  • A reconnect limit or circuit-breaker policy.
  • Explicit handling of malformed messages.
  • A clear distinction between a heartbeat response and a market-data message.

The general structure looks like this:

import asyncio
import json
import os
import random

import websockets


API_KEY = os.environ.get("TICKDB_API_KEY")
WS_URL = "wss://api.tickdb.ai/v1/ws"

if not API_KEY:
    raise RuntimeError("TICKDB_API_KEY is missing.")


async def run_stream():
    """Maintain a resilient WebSocket connection for monitoring."""
    retry = 0

    while True:
        url = f"{WS_URL}?api_key={API_KEY}"

        try:
            async with websockets.connect(
                url,
                ping_interval=20,
                ping_timeout=10,
                close_timeout=5,
                max_queue=1000,
            ) as websocket:
                retry = 0

                await websocket.send(
                    json.dumps({
                        "cmd": "subscribe",
                        "channel": "depth",
                        "symbol": "AAPL.US",
                    })
                )

                while True:
                    try:
                        raw_message = await asyncio.wait_for(
                            websocket.recv(),
                            timeout=40,
                        )
                        message = json.loads(raw_message)

                        if message.get("cmd") == "ping":
                            await websocket.send(
                                json.dumps({"cmd": "pong"})
                            )
                            continue

                        print(message)

                    except asyncio.TimeoutError:
                        # The application-level heartbeat keeps the connection alive.
                        await websocket.send(
                            json.dumps({"cmd": "ping"})
                        )

        except (
            websockets.ConnectionClosed,
            OSError,
            asyncio.TimeoutError,
            json.JSONDecodeError,
        ) as exc:
            retry += 1
            delay = min(2 ** min(retry, 5), 60)
            jitter = random.uniform(0, delay * 0.1)

            print(f"WebSocket disconnected: {exc}. Reconnecting in {delay:.1f}s.")
            await asyncio.sleep(delay + jitter)


if __name__ == "__main__":
    asyncio.run(run_stream())

Treat the endpoint and subscription message as environment-specific integration details. Confirm them against the current API documentation and dashboard before running this against a live account. The important architectural pattern is the control loop: connect, subscribe, heartbeat, parse, recover, and repeat.

For the first learning project, do not mix live execution with the backtest. First record the stream, compare its timestamps with the historical data, and verify that the live signal matches the backtest signal for the same completed bars.

13. The Minimum Backtest Disclosure Checklist

Before presenting any result, record the following:

  • Backtest period.
  • Number of observations.
  • Number of trades.
  • Gross and net-of-cost win rate.
  • Average win and average loss.
  • Profit factor.
  • Sharpe ratio.
  • Sortino ratio.
  • Maximum drawdown.
  • Maximum drawdown duration.
  • Buy-and-hold benchmark.
  • Slippage, spread, commission, and market-impact assumptions.
  • Data adjustments and symbol treatment.
  • Known implementation limitations.

A suitable disclosure is:

Backtest limitations: The results above are based on historical simulation and do not guarantee future performance. The example assumes a fixed 0.05% cost per position change and does not model market impact, partial fills, halts, borrow costs, taxes, or queue position. The sample may be too small to establish statistical significance. Extended out-of-sample validation is required before any live deployment.

Do not publish fabricated metrics. Run the script, save the actual output, and report the exact period and assumptions used.

14. Next Steps

If you are an investor looking for deeper market insight, subscribe to market-data and microstructure analysis focused on measurable market behavior rather than generic trading commentary.

If you want to run this strategy yourself:

  1. Create an API key in the TickDB dashboard.
  2. Set TICKDB_API_KEY in your development environment.
  3. Run python download_data.py.
  4. Inspect the normalized output.
  5. Run python backtest.py.
  6. Run python visualize.py.
  7. Change one assumption at a time and record every result.

If you need 10+ years of historical US equity OHLCV data for broader strategy research, evaluate the Professional or Enterprise data plans for your research requirements.

If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your AI tool’s marketplace.

The first strategy does not need to predict the market perfectly. It needs to make its assumptions explicit, preserve chronological order, include costs, and produce a result that another researcher can reproduce. Once that foundation exists, you can improve the signal, broaden the universe, and add live monitoring without losing the ability to understand where the result came from.

This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.