Metadata-Version: 2.4
Name: smt16-quantkit
Version: 0.3.0
Summary: Read-only quantitative investment research toolkit
License-Expression: Apache-2.0
Project-URL: Repository, https://github.com/smt16/quant-kit
Requires-Python: <3.15,>=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: exchange-calendars<5,>=4.5
Requires-Dist: numpy>=1.26
Requires-Dist: pandas>=2.1
Requires-Dist: scipy>=1.11
Requires-Dist: statsmodels>=0.14
Requires-Dist: duckdb>=1.1
Requires-Dist: pyarrow>=16.0
Requires-Dist: python-dotenv<2,>=1.0
Provides-Extra: advanced
Requires-Dist: arch>=6.3; extra == "advanced"
Requires-Dist: hmmlearn>=0.3; extra == "advanced"
Requires-Dist: scikit-learn>=1.4; extra == "advanced"
Provides-Extra: test
Requires-Dist: pytest>=8.0; extra == "test"
Requires-Dist: mcp==1.30.0; extra == "test"
Requires-Dist: jsonschema<5,>=4.23; extra == "test"
Provides-Extra: mcp
Requires-Dist: mcp==1.30.0; extra == "mcp"
Requires-Dist: jsonschema<5,>=4.23; extra == "mcp"
Dynamic: license-file

# US Quantitative Research Toolkit

A read-only research platform for US-listed equities and ETFs. It keeps a diversified, long-horizon **core** portfolio separate from the aggressive swing and medium-term **opportunistic** research sleeve. It does not submit, modify, or cancel orders, transfer funds, choose position sizes, or require capital to be deployed.

## Package structure

Implementation code is grouped by responsibility:

```text
quantkit/
├── core/          configuration, contracts, sessions, artifacts
├── market/        data validation, providers, storage, universes
├── research/      indicators, models, risk, backtests, reports
├── application/   workflows, services, runtime, operations
├── integrations/  external-system adapters and protocol clients
└── cli/           command-line entry points
```

Imports use these grouped packages directly, making architectural dependencies
explicit and keeping the package root uncluttered.

## What is included

- Explicit CSV/FMP provider selection, validated configuration and reproducible offline inputs.
- OHLCV validation, data-quality diagnostics, incremental Parquet storage, and a DuckDB provenance catalog.
- Momentum, relative strength, ATR, breakouts, Bollinger Bands, beta/correlation, and volume anomaly diagnostics.
- Historical VaR/CVaR, maximum drawdown, downside deviation, stress scenarios, and descriptive volatility-clustering output.
- Transparent swing and medium-term scanner components with liquidity eligibility checks.
- Next-bar long/cash momentum backtest, net costs, turnover, drawdown, Sharpe, Sortino, win/loss, profit-factor, and buy-and-hold comparison helpers.
- Portfolio allocation and correlation-overlap analysis that preserves core and opportunistic sleeves.
- Structured JSON daily research reports that preserve missing evidence instead of inventing targets or probabilities.
- A versioned external portfolio-snapshot contract and standalone daily runner, with no brokerage client or trading operations.

## Install

For local credentials, copy `.env.example` to `.env` and fill in `FMP_API_KEY`.
The command-line application loads `.env` from the working directory, or the file
specified by `--env-file /absolute/path/to/.env`. Existing process environment
variables take precedence. A missing file is allowed; providers validate their
required credentials when instantiated. Importing the reusable library does not
load environment files. For notebooks or another application, load the file
explicitly with `dotenv.load_dotenv(override=False)` before creating a provider.

Keep secrets in `.env` or scheduler environment variables; ordinary settings stay
in JSON configuration. `.env` and its variants are ignored by git, while
`.env.example` contains only empty placeholders. `SEC_USER_AGENT` is reserved for
the future SEC adapter. Scheduled jobs should inject credentials through their
environment or pass an explicit `--env-file` path. Never put keys in arguments,
configuration JSON, reports, or logs.

Supported Python versions: **3.11–3.14**. Use uv 0.13.6 with the committed cross-platform lock:

```bash
uv sync --locked --extra test --extra mcp
uv run --locked --extra test --extra mcp python -m pytest -q
uv pip check
```

`pyproject.toml` is the dependency source of truth; `uv.lock` pins exact versions.
Regenerate the lock deliberately with `uv lock` after changing dependencies.
CI rejects stale locks. For optional models use `uv sync --locked --extra test --extra mcp --extra advanced`.

A conventional unlocked installation remains available with `pip install '.[test,mcp]'`.
Add the `advanced` extra for optional research models.

## Data format

One CSV per symbol, e.g. `data/AAPL.csv`, with columns:

`date, open, high, low, close, volume`

`adjusted_close` is accepted when supplied by the source. Dates are exchange-session labels stored as timezone-naive midnight dates. Timezone-tagged midnight labels retain their written date. Intraday timestamps, invalid dates, duplicate sessions, non-finite or nonpositive prices, non-finite or negative volume, and inconsistent OHLC ranges are rejected with diagnostics. Prices must be adjusted consistently for splits/dividends if total-return analysis is intended. This toolkit does not synthesize adjusted OHLC from one adjusted-close column.

## Quick start

```python
from quantkit.market.data import load_ohlcv
from quantkit.research.scanner import score_universe

symbols = ["AAPL", "MSFT", "NVDA", "SPY", "QQQ"]
prices = {s: load_ohlcv(f"data/{s}.csv") for s in symbols}
report = score_universe(prices, benchmark=prices["SPY"])
print(report.to_string(index=False))
```

## Run the daily research workflow

For reproducible offline CSV runs, put `AAPL.csv`, `SPY.csv` and other configured symbols
in `data/source`, then run:

```bash
uv run --locked python -m quantkit --config examples/config.example.json
```

For FMP, copy `examples/config.fmp.example.json` to `config.fmp.json`, set `FMP_API_KEY`
in the process environment or a local `.env`, then run:

```bash
uv run --locked python -m quantkit --config config.fmp.json
```

Use the explicit `universe` list to configure your symbols; the example list is small.
The budget defaults support approximately 500 unique symbols, including a deduplicated benchmark.
There is no automatic constituent selection or subscription purchase.

`--provider {local_csv,fmp}`, `--csv-directory`, and `--storage-directory` override
corresponding JSON settings (`data_provider`, `csv_directory`, `data_directory`).
Defaults are CSV and separate `data/market/local_csv` / `data/market/fmp` storage roots.
CSV requires an existing source directory; FMP does not require CSV files.
Mixed-source or untracked storage is rejected before ingestion/ranking: use a new directory.
Existing data is never automatically converted or deleted.

The command incrementally updates Parquet and DuckDB, then writes a JSON report.
`run_status` and process exit codes are `complete`/0, `degraded`/2, and `blocked`/1.
An invalid benchmark blocks rankings and regime calculations. Individual failures and
exclusions remain visible. Reports include safe `provider_diagnostics` and structured
provider failure codes, request/retry/cache counts, requested dates and local usage.

`--as-of 2026-10-30T22:00:00Z` requests an explicit historical cutoff. Only complete,
aligned and current exchange sessions qualify. `exchange_calendar` defaults to XNYS;
`publication_delay_minutes` defaults to 60, a configurable assumption rather than an
FMP delivery guarantee. Holidays, early closes and daylight saving are calendar based.
`max_data_age_days` is deprecated and ignored.

FMP owns its transport retries (two by default); `update_retries` applies only to
providers that do not manage retries. Permanent errors are not retried. Account-wide
authentication or hard-quota failures stop further updates; independently eligible
stored data can still appear in a degraded report. Empty results are successful
responses but never make stale data eligible. Full FMP configuration, budgets and
opt-in live checks are documented in [FMP.md](docs/FMP.md).

Run locking, unique artifacts, atomic publication and a session-aware due check are implemented. Live scheduling and notification delivery require verification in the existing Scout runtime.

## Data provenance and limitations

The DuckDB catalog records source, retrieval time, adjustment flag, timezone, licensing note, date range, and storage path. It is a local reproducibility aid, not proof that a source permits redistribution. The daily FMP scanner uses only price history. Immutable revisions, overlapping corrections and corporate-action-triggered reconciliation are implemented. Dated membership and licensed look-through inputs are supported, with coverage gaps disclosed. Optional shortlist evidence enrichment preserves sources and timestamps.

## Important interpretation rules

1. Scanner scores are screening aids, not calibrated probabilities or buy signals.
2. Z-scores are descriptive. A large deviation can reflect new information rather than mispricing.
3. Historical correlations and betas are unstable and regime-dependent.
4. GARCH/HMM/Kalman/cointegration models require diagnostics, adequate data and out-of-sample validation. Optional advanced packages are not silently substituted when unavailable.
5. Backtests are illustrative. Add survivorship-bias-free universes, point-in-time fundamentals, corporate actions, realistic borrow/financing, market impact, delisted securities, rules for ambiguous intraday stop/target touches, and walk-forward parameter selection before relying on results.
6. Never infer a probability of profit from a backtest win rate alone.
7. This package does not choose position size and does not connect to order placement.

## Research models and validation

`quantkit.research.models` provides diagnostics-first functions for cointegration, HAC factor regression, Benjamini-Hochberg multiple-testing correction, bootstrap Monte Carlo scenarios, dynamic Kalman hedge ratios, and optional HMM state estimates. GARCH remains optional in `quantkit.research.regimes`. Their outputs are research diagnostics, not recommendations; functions return insufficient-data results or require optional packages when their assumptions cannot be met.

`long_bracket_backtest` uses next-bar entries, costs, slippage, optional stop, target, signal exit, and maximum holding-period conditions. Daily bars cannot establish the intraday order in which a stop and target both trade, so the simulator takes the conservative stop result. `walk_forward_evaluate` requires parameter selection on each earlier training period and evaluates it only on subsequent test periods.

## Validation and testing

Run the test suite after installing dependencies:

```bash
python -m pytest -q
```

The audit, implementation status, planned follow-up phases, and setup blockers are recorded in [AUDIT.md](docs/AUDIT.md).

## Daily Trade Scout integration

The analytical engine now includes a read-only **stdio MCP server**, a bounded **Scout MCP client**, versioned schemas, and release automation for the proposed `smt16-quantkit` distribution. The import remains `quantkit`; CLI entry points are `quantkit-mcp`, `quantkit-scout` and `quantkit-ops`.

Version **0.3.0 is prepared for the first production release**, but no verified PyPI upload or production Scheduled-task activation is claimed here. The existing public `quantkit` distribution is a different project. Pushes to `master` run the verified release workflow and publish only when the exact `smt16-quantkit` version is absent from PyPI. This implementation preserves the existing Daily Trade Scout task pending an actual published-artifact verification.

See [MCP and runner setup](docs/MCP.md), [execution assumptions](docs/EXECUTION.md), [data/research operations](docs/DATA_AND_RESEARCH.md), [release procedure](docs/RELEASING.md), and [implementation status and human actions](docs/IMPLEMENTATION_STATUS.md).

`quantkit-mcp --config /absolute/path/config.json` exposes eight strict research tools, including idempotent validated snapshot supply. `quantkit-scout --config /absolute/path/config.json --portfolio-snapshot /private/path/snapshot.json` collects a timestamped development report through MCP. Production requires an exact verified PyPI release, a release receipt and a locked consumer environment. Configure provider secrets through the environment; the MCP server does not load `.env` implicitly.

The daily research workflow should:

- retrieve fresh data and timestamp it;
- validate missing observations, corporate actions and liquidity;
- run the scanner and risk diagnostics;
- validate any strategy out of sample / walk-forward;
- corroborate signals with fundamentals, catalysts and news;
- show target and invalidation levels as scenarios, not certainties;
- report price movement in % and dollars per share;
- leave allocation and every order decision to the user.

Broker connectivity belongs to the external runner. Quant-kit accepts only the strict `portfolio_snapshot.v1` analysis contract; it contains no broker gateway, account authentication, order-placement, order-change, order-cancellation or funds-transfer capability. Core, opportunistic and unclassified sleeves must be supplied explicitly and are never inferred.

## Strict daily eligibility and historical cutoffs

The daily pipeline requires a complete trailing window of `max(min_history_days, 253)` exchange sessions for both benchmark and symbols. Bars must end on the expected session and share exactly the same dates. Missing sessions are not filled. New listings, stale data and missing/invalid bars are excluded; low-liquidity symbols remain excluded. Cached data after an update failure is usable only if it independently passes these checks, and the run is marked degraded.

Reports include `run_status` (`complete`, `degraded`, or `blocked`), `expected_session`, calendar/delay settings, exclusions, failures and per-symbol quality diagnostics. The CLI returns 0 for complete, 2 for degraded and 1 for blocked or configuration/runtime errors. Non-finite diagnostic values are JSON null. A complete run may legitimately have no candidates. Existing scanner calculation helpers remain available independently; strict calendar eligibility is enforced by the daily pipeline.

Use a timezone-aware historical cutoff when needed:

```bash
python -m quantkit --config examples/config.example.json --csv-directory data/source --storage-directory data/market --as-of 2026-10-30T22:00:00Z
```

Research timestamps are normalized to UTC; naive timestamps are rejected. Provider requests end on the expected session. Stored observations after that session are counted and excluded from analysis without deleting them. Empty incremental responses do not overwrite stored data, and already-covered date ranges do not contact the provider. Ingestion diagnostics are stored in the existing DuckDB quality JSON; failed validations retain raw diagnostics in report failures.

Cutoffs prevent later-bar leakage, but do not reconstruct historical vendor revisions, historical publication availability, or point-in-time universe membership. Locally captured immutable revisions now support exact saved-input replay; historical availability before the first snapshot remains unknown. The single XNYS schedule is intended for regular US equity/ETF sessions, not extended hours or multi-exchange global scanning. The 60-minute buffer is a configurable initial assumption, not a verified FMP delivery guarantee.
