-- V6__Add_Market_Time_Series.sql
-- Canonical PostgreSQL daily series for point-in-time factor calculations.

CREATE SCHEMA IF NOT EXISTS quantengine;

CREATE TABLE IF NOT EXISTS quantengine.price_history_daily (
    ticker TEXT NOT NULL,
    trade_date DATE NOT NULL,
    open NUMERIC NOT NULL,
    high NUMERIC NOT NULL,
    low NUMERIC NOT NULL,
    close NUMERIC NOT NULL,
    volume BIGINT NOT NULL,
    source TEXT NOT NULL,
    collected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    provenance JSONB NOT NULL DEFAULT '{}'::jsonb,
    PRIMARY KEY (ticker, trade_date),
    CONSTRAINT price_history_daily_ohlc_order CHECK (high >= low AND high >= open AND high >= close AND low <= open AND low <= close),
    CONSTRAINT price_history_daily_volume_nonnegative CHECK (volume >= 0)
);

CREATE INDEX IF NOT EXISTS idx_price_history_daily_date
    ON quantengine.price_history_daily (trade_date DESC, ticker);

CREATE TABLE IF NOT EXISTS quantengine.macro_history_daily (
    symbol TEXT NOT NULL,
    trade_date DATE NOT NULL,
    value NUMERIC NOT NULL,
    source TEXT NOT NULL,
    collected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    provenance JSONB NOT NULL DEFAULT '{}'::jsonb,
    PRIMARY KEY (symbol, trade_date)
);

CREATE INDEX IF NOT EXISTS idx_macro_history_daily_date
    ON quantengine.macro_history_daily (trade_date DESC, symbol);
