Metadata-Version: 2.4
Name: kronos-finance
Version: 0.1.0
Summary: Pythonic wrapper around the Kronos foundation model for OHLCV forecasting across any market
Author-email: lordxmen2k <lordxmen2k@users.noreply.github.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/lordxmen2k/kronos-finance
Project-URL: Repository, https://github.com/lordxmen2k/kronos-finance
Project-URL: Issues, https://github.com/lordxmen2k/kronos-finance/issues
Project-URL: Changelog, https://github.com/lordxmen2k/kronos-finance/blob/main/CHANGELOG.md
Project-URL: Citation, https://github.com/lordxmen2k/kronos-finance#citation
Keywords: kronos,finance,ohlcv,forecasting,foundation-model,time-series,quant
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: numpy>=1.26
Requires-Dist: pandas>=2.2
Requires-Dist: einops>=0.8.1
Requires-Dist: huggingface_hub>=0.33.1
Requires-Dist: safetensors>=0.6.2
Requires-Dist: tqdm>=4.67.1
Requires-Dist: matplotlib>=3.9.3
Provides-Extra: cn
Requires-Dist: akshare>=1.18.0; extra == "cn"
Provides-Extra: global
Requires-Dist: yfinance>=0.2.60; extra == "global"
Provides-Extra: crypto
Requires-Dist: ccxt>=4.0.0; extra == "crypto"
Provides-Extra: qlib
Requires-Dist: pyqlib>=0.9.7; extra == "qlib"
Provides-Extra: ui
Requires-Dist: flask>=2.3; extra == "ui"
Requires-Dist: flask-cors>=4.0; extra == "ui"
Requires-Dist: plotly>=5.17; extra == "ui"
Provides-Extra: analysis
Requires-Dist: pandas-ta>=0.3.14b; extra == "analysis"
Requires-Dist: quantstats>=0.0.62; extra == "analysis"
Provides-Extra: finetune
Requires-Dist: pyqlib>=0.9.7; extra == "finetune"
Requires-Dist: pyyaml>=6.0; extra == "finetune"
Requires-Dist: comet-ml>=3.0; extra == "finetune"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.11; extra == "dev"
Requires-Dist: pre-commit>=4.0; extra == "dev"
Requires-Dist: ipython>=8.0; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest-playwright>=0.5; extra == "test"
Requires-Dist: playwright>=1.47; extra == "test"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Provides-Extra: all
Requires-Dist: akshare>=1.18.0; extra == "all"
Requires-Dist: yfinance>=0.2.60; extra == "all"
Requires-Dist: ccxt>=4.0.0; extra == "all"
Requires-Dist: pyqlib>=0.9.7; extra == "all"
Requires-Dist: flask>=2.3; extra == "all"
Requires-Dist: flask-cors>=4.0; extra == "all"
Requires-Dist: plotly>=5.17; extra == "all"
Requires-Dist: pandas-ta>=0.3.14b; extra == "all"
Requires-Dist: quantstats>=0.0.62; extra == "all"
Requires-Dist: pyyaml>=6.0; extra == "all"
Requires-Dist: comet-ml>=3.0; extra == "all"
Dynamic: license-file

# kronos-finance

[![](https://img.shields.io/pypi/v/kronos-finance.svg)](https://pypi.org/project/kronos-finance/)
[![](https://img.shields.io/pypi/pyversions/kronos-finance.svg)](https://pypi.org/project/kronos-finance/)
[![](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
[![](https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-blue.svg)](#)

> Pythonic wrapper around the Kronos foundation model for OHLCV forecasting across any market.

## Built on Kronos

Kronos is the first open-source foundation model for financial candlesticks (K-lines),
by the [NeoQuasar team](https://github.com/shiyu-coder/Kronos), accepted at AAAI 2026,
MIT-licensed.

This package (`kronos-finance`) is a **wrapper** that turns the upstream research codebase
into a pip-installable library with a CLI, a dashboard, multi-source data loaders, and
comprehensive tests. All model code comes from the original project — see the
[Citation](#citation) section.

- Original repo: <https://github.com/shiyu-coder/Kronos>
- Paper: <https://arxiv.org/abs/2508.02739>
- Model zoo on HuggingFace: <https://huggingface.co/NeoQuasar>

## Use a virtual environment (recommended)

A virtual environment keeps your system Python clean and avoids the
`error: externally-managed-environment` (PEP 668) error on Ubuntu 23.04+,
macOS Homebrew Python, and Fedora 39+.

```bash
python -m venv .venv
source .venv/bin/activate          # macOS / Linux
# .venv\Scripts\activate           # Windows PowerShell
```

Every install command below assumes you've activated a venv first.

## Installation

```bash
pip install kronos-finance                       # core (CPU, ~400MB incl. PyTorch)
pip install kronos-finance[cn]                   # + AKShare for Chinese A-shares
pip install kronos-finance[global]               # + yfinance for global equities
pip install kronos-finance[crypto]               # + CCXT for crypto exchanges
pip install kronos-finance[qlib]                 # + Qlib for CN finetune data
pip install kronos-finance[ui]                   # + Flask + Plotly for the dashboard
pip install kronos-finance[analysis]             # + pandas-ta + quantstats
pip install kronos-finance[all]                  # everything above
```

Verify the install:

```bash
kronos --version
```

## Quickstart (60 seconds)

```python
from kronos_finance import load_kronos
from kronos_finance.data import load_ohlcv
import pandas as pd

df = load_ohlcv("AAPL", period="2y", interval="1d")
wrapper = load_kronos(model_id="small")
y_ts = pd.date_range(df["timestamps"].iloc[-1], periods=31, freq="1D")[1:]
pred = wrapper.predict(
    df=df[["open", "high", "low", "close", "volume", "amount"]].tail(400),
    x_timestamp=df["timestamps"].tail(400), y_timestamp=y_ts, pred_len=30,
)
print(pred.head())
```

## Features

- One-line predict on any market — US equities, CN A-shares, crypto, HK, JP, EU.
- Multi-source loaders — AKShare, yfinance, CCXT, Qlib, local CSV.
- Ticker auto-detection — type `"600519"` and AKShare is picked; type `"BTC/USDT"` and
  CCXT is picked.
- Bundled ticker catalog + user-extendable `~/.kronos/tickers.json`.
- CLI: `kronos predict`, `kronos backtest`, `kronos ui`, `kronos tickers`.
- Flask dashboard with candlestick chart, autocomplete, model selector, indicator overlay.
- Optional indicators (RSI, MACD, BBands) and HTML tearsheets (quantstats).
- 12 runnable examples + comprehensive docs + a 35-term glossary.

## How to predict any ticker in the world

| Market | Ticker format | Source | Install extra |
|---|---|---|---|
| US equity | `AAPL`, `MSFT`, `NVDA` | yfinance | `[global]` |
| US ETF | `SPY`, `QQQ`, `IWM` | yfinance | `[global]` |
| US index | `^GSPC`, `^DJI`, `^IXIC` | yfinance | `[global]` |
| CN A-share | `600519`, `000001`, `002594` | AKShare | `[cn]` |
| CN index | `000300`, `000905` | AKShare | `[cn]` |
| Crypto pair | `BTC/USDT`, `ETH/USDT` | CCXT (Binance default) | `[crypto]` |
| HK stock | `0700.HK`, `9988.HK` | yfinance | `[global]` |
| JP stock | `7203.T`, `6758.T` | yfinance | `[global]` |
| EU stock | `ASML.AS`, `SAP.DE` | yfinance | `[global]` |
| Local CSV | path to `.csv` | `csv_path=` | (core) |

The `source="auto"` default routes the ticker to the right loader based on its shape.

## CLI reference

```bash
kronos predict TICKER [--source auto] [--model small] [--interval 1d]
                     [--pred-len 30] [--lookback 400] [--export forecast.csv]
                     [--device cpu]
kronos batch TICKERS_FILE [--output ./out] [--model small] [--pred-len 30]
kronos backtest TICKER [--period 1y] [--interval 1d] [--source auto]
                      [--export tearsheet.html]
kronos ui [--host 127.0.0.1] [--port 5000] [--debug]
kronos tickers list
kronos tickers search QUERY [--market cn|us|crypto|...]
kronos tickers add SYMBOL NAME SOURCE [--exchange binance]
kronos --version
kronos --help
```

Examples:

```bash
kronos predict 600519 --source akshare
kronos predict BTC/USDT --source ccxt --exchange binance
```

Exit codes: `0` ok, `1` generic error, `2` usage error, `130` SIGINT (clean Ctrl+C).

## Python API

```python
from kronos_finance import load_kronos          # model
from kronos_finance.data import load_ohlcv       # data fetchers
from kronos_finance.tickers import catalog, search, add_user_ticker
from kronos_finance.analysis import (
    enrich_with_indicators, forecast_to_returns, make_tearsheet,
)
from kronos_finance import (                      # errors
    KronosFinanceError, TickerNotFoundError,
    DataSourceError, ModelLoadError, PredictionError, CatalogError,
)
```

Full reference: [`docs/API.md`](docs/API.md).

## Dashboard

Launch with `kronos ui` (default `http://127.0.0.1:5000`):

- Ticker input with autocomplete from the bundled + user catalog.
- Candlestick chart with historical in green/red and forecast in blue/purple.
- Model selector (mini / small / base with parameter counts).
- Source + interval pickers.
- Indicator overlay (RSI / MACD / BBands).
- Recent predictions history with CSV export.
- Dark / light theme toggle.

Full tour: [`docs/DASHBOARD.md`](docs/DASHBOARD.md).

## Examples

Twelve runnable examples in [`examples/`](examples/). Each starts with the venv setup
reminder. See [`examples/README.md`](examples/README.md).

## Troubleshooting

The most common pitfalls — full list in [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md):

- **`error: externally-managed-environment`** — you're trying to `pip install` into
  system Python. Use a venv (see the section at the top of this README).
- **Model download stalls / 401 from HuggingFace** — set `HF_TOKEN` or run
  `huggingface-cli login`.
- **CUDA version mismatch** — install PyTorch from the matching CUDA index URL.
- **yfinance rate limit** — switch to `auto` source or add `period=` to limit.
- **AKShare returns empty** — the ticker may have delisted. Try yfinance with
  `600519.SS`.
- **Playwright browser missing** — `playwright install --with-deps chromium`.
- **`max_context` exceeded** — reduce `lookback` or use `Kronos-mini` (2048 context).
- **Tz-aware timestamp warning** — convert to UTC and drop the tz before passing in.
- **PermissionError on Windows** — run your terminal as Administrator or use a venv.

## How it works

```
Ticker (e.g. "AAPL")
    │
    ▼  load_ohlcv() auto-detects source -> yfinance
pd.DataFrame [timestamps, open, high, low, close, volume, amount]
    │
    ▼  load_kronos() downloads Kronos-small from HuggingFace
KronosWrapper (model + tokenizer + predictor)
    │
    ▼  wrapper.predict() runs autoregressive Transformer
pd.DataFrame [predicted OHLCV]
    │
    ▼  analysis: indicators + backtest -> HTML tearsheet
```

## Performance & limits

| Setting | Default | Cap | Note |
|---|---|---|---|
| `pred_len` | 30 | 1000 (CLI), no cap in API | Larger = slower inference |
| `lookback` | 400 | 512 (small/base/large), 2048 (mini) | Auto-truncated |
| `sample_count` | 1 | 20 | Quantile bands need >1 |
| Memory (CPU, small) | ~1GB | — | +500MB for base |
| Memory (CUDA, base) | ~2GB VRAM | — | RTX 3060+ recommended |
| Latency (CPU, 30-step, 1 ticker) | ~5s | — | ~1s on CUDA |

## Development

```bash
git clone https://github.com/lordxmen2k/kronos-finance.git
cd kronos-finance
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev,test,ui]"
pytest                         # unit + CLI tests
ruff check src/                # lint
```

See [`docs/CONTRIBUTING.md`](docs/CONTRIBUTING.md).

## Citation

If you use this in research, please cite the original Kronos paper:

```bibtex
@inproceedings{kronos2026,
  title  = {Kronos: A Foundation Model for the Language of Financial Markets},
  author = {Shi, Yu and others},
  booktitle = {AAAI},
  year   = {2026},
}
```

And this wrapper:

```bibtex
@software{kronos_finance,
  author = {lordxmen2k},
  title  = {kronos-finance: A Python wrapper for Kronos},
  year   = {2026},
  url    = {https://github.com/lordxmen2k/kronos-finance}
}
```

## License

MIT — see [`LICENSE`](LICENSE) for the full text. The original Kronos project is also
MIT; see `src/kronos_finance/_vendor/LICENSE_KRONOS` for the vendored upstream license.

## Acknowledgements

- The [NeoQuasar team](https://github.com/shiyu-coder/Kronos) for the Kronos
  foundation model.
- [HuggingFace](https://huggingface.co/) for model hosting.
- [AKShare](https://github.com/akfamily/akshare), [yfinance](https://github.com/ranaroussi/yfinance),
  [CCXT](https://github.com/ccxt/ccxt), [Qlib](https://github.com/microsoft/qlib) — the
  data layer.
- [pandas-ta](https://github.com/twopirllc/pandas-ta), [quantstats](https://github.com/ranaroussi/quantstats) — analysis.
- [Plotly](https://plotly.com/), [Flask](https://flask.palletsprojects.com/) — the dashboard.

## Glossary

See [`docs/INSTALL.md#glossary`](docs/INSTALL.md#glossary) for the full 35-term glossary.
A quick index of the most important ones:

- **OHLCV** — Open, High, Low, Close, Volume. The five columns Kronos expects.
- **K-line** — Chinese term for candlestick; same thing.
- **Context length / max_context** — maximum past bars the model can see (512 for
  small/base/large; 2048 for mini).
- **AR / autoregressive** — generates outputs one step at a time.
- **Tokenizer** — converts continuous OHLCV to discrete tokens before the Transformer.
- **Sample count** — number of forecast paths to draw; more = smoother quantile band.
- **Tearsheet** — one-page performance report; quantstats generates HTML.
- **Nucleus sampling (top-p)** — sampling from smallest token set whose cumulative prob ≥ p.
- **Temperature (T)** — sampling temperature; T<1 conservative, T>1 exploratory.
- **Quantile band** — uncertainty interval drawn when `sample_count > 1`.
- **PEP 668** — Python spec marking system Python as externally managed; use venv.
- **Twine** — `twine upload dist/*` publishes to PyPI.
- **Wheel (.whl)** — built distribution format.
