[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-2249":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":24,"hasPages":22,"topics":25,"createdAt":10,"pushedAt":10,"updatedAt":26,"readmeContent":27,"aiSummary":28,"trendingCount":16,"starSnapshotCount":16,"syncStatus":15,"lastSyncTime":29,"discoverSource":30},2249,"nepse-quant-terminal","nlethetech\u002Fnepse-quant-terminal","nlethetech","Terminal-based NEPSE quant trading dashboard with paper trading, backtesting, analytics, and AI agent support.","https:\u002F\u002Fnepsequant.com",null,"Python",161,84,3,2,0,4,9,50,12,5.79,false,"main",true,[],"2026-06-12 02:00:39","#NEPSE Quant Terminal\n\nA terminal-based quantitative trading dashboard for the Nepal Stock Exchange (NEPSE), built with [Textual](https:\u002F\u002Ftextual.textualize.io\u002F). Runs entirely in your terminal — no browser, no electron, no cloud dependency.\n\n**Paper trading only.** This terminal simulates trades locally. It does not connect to any broker API.\n\n---\n\n## What It Does\n\n- **Paper Trading** — full paper portfolio with buy\u002Fsell order book, P&L tracking, NAV history, and multi-account support. Seed from your MeroShare holdings CSV or start blank.\n- **Auto Trading Engine** — assigns a quantitative strategy to each account. The engine runs in the background, generates signals every 5 trading days, and manages entries\u002Fexits automatically (holding periods, stop losses, trailing stops, regime filters).\n- **Backtesting** — walk-forward validated backtests on 6+ years of NEPSE price data. Ships with C5 baseline: **+88% OOS return, Sharpe 2.2** vs. NEPSE +27%.\n- **Market Dashboard** — live quotes, 52-week highs\u002Flows, top movers, sector heatmap, volume signals.\n- **Portfolio Analytics** — unrealized\u002Frealized P&L, sector concentration, holding age buckets, max drawdown, alpha vs. NEPSE benchmark.\n- **Gold Hedge Overlay** — tracks gold\u002Fsilver regime (risk-on \u002F neutral \u002F risk-off) and adjusts capital deployment accordingly.\n- **AI Agent** — on-demand analysis of your portfolio positions and signal shortlist. Defaults to a local Ollama model, with Gemma 4 MLX or Claude CLI available as optional backends.\n- **Paper Agent Graph** — cleaned evidence-gated research, debate, risk, and portfolio decision workflow for paper execution only.\n- **Strategy Builder** — create, backtest, and assign custom strategies. Each account runs its own strategy independently.\n- **Statistical Validation** — walk-forward OOS testing, Monte Carlo, CSCV\u002FPBO overfitting detection, deflated Sharpe ratio, random baseline percentile.\n- **MeroShare Import** — seed any account directly from your MeroShare \"My Shares Values.csv\" export.\n\n---\n\n## Architecture\n\n### Paper Agent Workflow\n\nThe public agent workflow is evidence-gated, checkpointed, and restricted to paper execution. The implementation in `backend\u002Fnepse_agents\u002F` does not include live order routing, credentials, or execution integrations.\n\n![NEPSE Quant Terminal paper agent architecture](docs\u002Fassets\u002Fnepse-agent-architecture.png)\n\n```\n┌─────────────────────────────────────────────────────┐\n│                   Textual TUI                       │\n│  dashboard_tui.py  ·  9 tabs  ·  keyboard-driven    │\n└──────────┬──────────────────────┬───────────────────┘\n           │                      │\n    ┌──────▼──────┐      ┌────────▼────────┐\n    │  Market     │      │  Trading Engine │\n    │  Data Layer │      │  (per account)  │\n    │  nepse_data │      │  tui_trading_   │\n    │  .db        │      │  engine.py      │\n    └──────┬──────┘      └────────┬────────┘\n           │                      │\n    ┌──────▼──────────────────────▼────────┐\n    │          Signal Engine               │\n    │  simple_backtest.py                  │\n    │  volume · quality · low_vol ·        │\n    │  mean_reversion · xsec_momentum ·    │\n    │  quarterly_fundamental · satellite   │\n    └──────────────────────────────────────┘\n```\n\n### Components\n\n| Component | File | What it does |\n|---|---|---|\n| TUI | `apps\u002Ftui\u002Fdashboard_tui.py` | All UI — 9 tabs, keyboard shortcuts, paper order book |\n| Trading Engine | `backend\u002Ftrading\u002Ftui_trading_engine.py` | Per-account auto-trading loop, regime filter, stop logic |\n| Paper Trader | `backend\u002Ftrading\u002Fpaper_trader.py` | Manual buy\u002Fsell execution, portfolio persistence |\n| Signal Engine | `backend\u002Fbacktesting\u002Fsimple_backtest.py` | All signal generation and backtest runner |\n| Strategy Registry | `backend\u002Ftrading\u002Fstrategy_registry.py` | Load, save, assign strategies per account |\n| Market Data | `backend\u002Fmarket\u002F` | Price DB queries, quote scraping, 52wk calculations |\n| Validation | `validation\u002F` | Walk-forward, Monte Carlo, CSCV, DSR, random baseline |\n| Gold Hedge | `backend\u002Fquant_pro\u002Fgold_hedge.py` | Gold\u002Fsilver regime detection → capital deployment % |\n| AI Agent | `backend\u002Fagents\u002Fagent_analyst.py` | Ollama-first portfolio and signal analysis |\n| Paper Agent Graph | `backend\u002Fnepse_agents\u002F` | Evidence-gated research\u002Fdebate\u002Frisk\u002Fportfolio workflow; paper-only |\n| NEPSE Calendar | `nepse_calendar.py` | Sun–Thu trading days, public holidays, trading day counter |\n\n---\n\n## How Paper Trading Works\n\nEach account has its own directory under `data\u002Fruntime\u002Faccounts\u002Faccount_N\u002F` containing:\n\n```\npaper_portfolio.csv      # open positions\npaper_trade_log.csv      # all executed trades\npaper_nav_log.csv        # daily NAV history\npaper_state.json         # cash balance + runtime state\ntui_paper_*              # engine auto-trade files\nwatchlist.json           # symbols to track\n```\n\n**Manual trading** (Order tab) writes to `paper_portfolio.csv`.\n**Auto-trading** (engine) writes to `tui_paper_trade_log.csv` and reconciles with the manual portfolio on display.\n\nThe Trade History tab merges both sources and deduplicates by `(Date, Action, Symbol, Shares, Price)`.\n\n---\n\n## How the Signal Engine Works\n\nSignals are generated per trading date using price + fundamental data from `nepse_data.db`. Each signal scores symbols 0.0–1.0. Signals are combined with regime-dependent weights:\n\n```\nBull market  → xsec_momentum weight ×1.1, all others ×1.0\nBear market  → capital preservation mode (fewer positions)\nNeutral      → standard weights\n```\n\nRegime is detected via a 60-day rolling NEPSE return: bear below threshold, bull above 0, neutral in between.\n\nThe engine runs a **5-trading-day signal cycle** — signals fire every 5 days, not daily, avoiding overtrading and matching NEPSE's lower liquidity.\n\n### Available Signals\n\n| Signal | Logic |\n|---|---|\n| `volume` | Volume breakout above 20-day average with price confirmation |\n| `quality` | ROE + debt-to-equity + earnings stability composite |\n| `low_vol` | Low 60-day realized volatility with positive momentum |\n| `mean_reversion` | RSI oversold + distance below 52-week high |\n| `xsec_momentum` | Cross-sectional 6m-minus-1m momentum (skip last month) |\n| `quarterly_fundamental` | EPS growth + revenue growth from quarterly filings |\n| `satellite_hydro` | Hydropower generation signals from WECS rainfall data |\n\n---\n\n## How Backtesting Works\n\n```python\nfrom backend.backtesting.simple_backtest import run_backtest\n\nresults = run_backtest(\n    signal_types=[\"volume\", \"quality\", \"low_vol\", \"mean_reversion\",\n                  \"xsec_momentum\", \"quarterly_fundamental\"],\n    holding_days=40,\n    max_positions=5,\n    stop_loss_pct=0.12,\n    trailing_stop_pct=0.15,\n    use_regime_filter=True,\n    initial_capital=1_000_000,\n)\n```\n\nWalk-forward validation splits 6+ years of history into rolling train\u002Ftest windows and stitches OOS equity:\n\n```bash\npython -m validation.run_all --fast\n```\n\nOutputs: OOS equity curve, Sharpe, max drawdown, CSCV\u002FPBO score, deflated Sharpe ratio, random baseline percentile.\n\n---\n\n## How the Auto-Trading Engine Works\n\nWhen the TUI starts, one `TUITradingEngine` per account starts in a background daemon thread. Each engine:\n\n1. Loads its account's strategy config (signal types, holding days, stop params)\n2. Every 5 trading days: generates signals → ranks → buys top N symbols up to `max_positions`\n3. Every day: checks exits — trailing stop, stop loss, or holding period expiry\n4. Writes trades to `tui_paper_trade_log.csv` for that account\n5. Persists state so it survives TUI restarts\n\nCapital deployment adjusts by the gold hedge regime:\n- **Risk-off** → 90% of capital deployed\n- **Neutral** → 97%\n- **Risk-on** → 100%\n\n---\n\n## How Strategies Work\n\nA strategy is a JSON config in `data\u002Fstrategy_registry\u002F`:\n\n```json\n{\n  \"id\": \"my_strategy\",\n  \"name\": \"My Strategy\",\n  \"config\": {\n    \"signal_types\": [\"volume\", \"quality\", \"xsec_momentum\"],\n    \"holding_days\": 40,\n    \"max_positions\": 5,\n    \"stop_loss_pct\": 0.12,\n    \"trailing_stop_pct\": 0.15,\n    \"use_regime_filter\": true,\n    \"regime_max_positions\": {\"bull\": 5, \"neutral\": 4, \"bear\": 1},\n    \"sector_limit\": 0.35\n  }\n}\n```\n\nCreate strategies in the **Strategies tab** → press **N NEW**, configure signals with the toggle buttons, set parameters, press **SAVE**. Assign to any account with **→ ACTIVE ACCT**.\n\n---\n\n## Adding Custom Signals\n\nImplement a function in `backend\u002Fbacktesting\u002Fsimple_backtest.py`:\n\n```python\ndef generate_my_signal_at_date(\n    symbols: list[str],\n    date: str,\n    prices_df: pd.DataFrame,\n) -> list[dict]:\n    # Return list of {\"symbol\": str, \"score\": float 0-1, \"reason\": str}\n    ...\n```\n\nRegister it in the `SIGNAL_MAP` dict inside `run_backtest()` and add `\"my_signal\"` to any strategy's `signal_types`.\n\n---\n\n## Setup\n\n### Easy launch for nontechnical users\n\nAfter downloading or cloning the repo, use the double-click launcher for your OS:\n\n- macOS: `Nepse Quant Terminal.app` or `Launch Quant Terminal.command`\n- Windows: `Launch Quant Terminal.bat`\n\nThe launcher creates `.venv`, installs dependencies, downloads the bundled market database if missing, runs preflight, and starts the TUI.\n\nSee [`docs\u002FEASY_LAUNCH.md`](docs\u002FEASY_LAUNCH.md) for troubleshooting notes and macOS security prompt handling.\n\n### Requirements\n\n- Python 3.10–3.13 (recommended: 3.12) — Python 3.14+ is **not yet supported** (numba and the nepse package both cap at `\u003C3.14`)\n- macOS, Linux, or native Windows PowerShell. WSL\u002Fcontainer remains useful for scheduled production-style runs, but is not required for dashboard, backtests, or paper autopilot.\n\n### Installation\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fnlethetech\u002Fnepse-quant-terminal\ncd nepse-quant-terminal\npip install -r requirements.txt\n```\n\nNative Windows PowerShell:\n\n```powershell\ngit clone https:\u002F\u002Fgithub.com\u002Fnlethetech\u002Fnepse-quant-terminal\ncd nepse-quant-terminal\npy -3.12 -m venv .venv\n.\\.venv\\Scripts\\Activate.ps1\npython -m pip install -U pip\npython -m pip install -r requirements.txt\npython -m scripts.ops.windows_preflight\n```\n\n### Database\n\nRun the setup script — it downloads the pre-built database (~13 MB) from the GitHub release automatically:\n\n```bash\npython setup_data.py\n```\n\nTakes under a minute. You get 456K rows of OHLCV history for all NEPSE symbols, quarterly earnings, corporate actions, and benchmark history — enough for the signal engine, backtests, and charts to work immediately.\n\n> **Important:** The bundled database is a snapshot. For accurate signals and backtests you must keep it up to date with fresh scraped data. The pre-built DB covers history through the release date — anything after that requires running the scraper.\n\n**Scrape fresh data yourself (recommended for production use):**\n```bash\npython setup_data.py --scrape           # full historical scrape from Merolagani (~30–60 min)\npython setup_data.py --scrape --days 90 # last 90 days only (~5 min)\n```\n\n**Daily incremental update** — run this after market close each day to keep data current:\n```bash\npython scripts\u002Fingestion\u002Fdeterministic_daily_ingestion.py\n```\n\n> The signal engine (volume breakout, momentum, quarterly fundamental, etc.) relies on recent price history. Stale data = stale signals. Set up a daily cron job or run the ingestion script manually each evening.\n\n### Run\n\n```bash\npython -m apps.tui.dashboard_tui\n```\n\nOn Windows PowerShell, run the same command after activating `.venv`:\n\n```powershell\npython -m apps.tui.dashboard_tui\n```\n\nPaper strategy autopilot is broker-free. Manual orders and strategy orders use the same account-scoped paper execution service, fill from latest market quotes, write visible rejected\u002Ffilled order history, and persist the canonical files under `data\u002Fruntime\u002Faccounts\u002Faccount_N\u002F`.\n\n---\n\n## AI Agent Setup\n\nThe Agents tab provides on-demand equity analysis of your signal shortlist and portfolio. Ollama is the default backend; Gemma 4 MLX and Claude CLI are optional.\n\n### Option 1 — Ollama (recommended, any hardware)\n\nOllama runs any open-source model locally via a simple REST server. No Apple Silicon required.\n\n**Step 1 — Install Ollama**\n```bash\n# macOS\nbrew install ollama\n\n# Linux\ncurl -fsSL https:\u002F\u002Follama.com\u002Finstall.sh | sh\n```\n\n**Step 2 — Pull a model**\n\nPick one based on your available RAM:\n\n| Model | RAM | Command | Notes |\n|---|---|---|---|\n| `llama3` | 8 GB | `ollama pull llama3` | Good all-rounder |\n| `mistral` | 8 GB | `ollama pull mistral` | Fast, sharp reasoning |\n| `phi3` | 4 GB | `ollama pull phi3` | Runs on low-end hardware |\n| `qwen2` | 8 GB | `ollama pull qwen2` | Strong on structured output |\n| `llama3:70b` | 40 GB | `ollama pull llama3:70b` | Best quality, high-end only |\n\n**Step 3 — Start the Ollama server**\n```bash\nollama serve\n# Runs at http:\u002F\u002Flocalhost:11434 by default\n```\n\n**Step 4 — Optional: change the default model**\n\nThe terminal defaults to:\n\n```json\n{\n  \"selected_preset\": \"ollama\",\n  \"backend\": \"ollama\",\n  \"model\": \"llama3\",\n  \"ollama_host\": \"http:\u002F\u002Flocalhost:11434\"\n}\n```\n\n`data\u002Fruntime\u002Fagents\u002Factive_agent.json` is created automatically on first run. To use a different Ollama model, either use the Agents tab command box:\n\n```text\n\u002Fagent ollama gemma4:e2b\n```\n\nor edit `data\u002Fruntime\u002Fagents\u002Factive_agent.json`:\n\n```json\n{\n  \"selected_preset\": \"ollama\",\n  \"backend\": \"ollama\",\n  \"model\": \"mistral\",\n  \"ollama_host\": \"http:\u002F\u002Flocalhost:11434\"\n}\n```\n\nYou can also keep the current backend and only change its model:\n\n```text\n\u002Fmodel mistral\n```\n\n**Step 5 — Run the terminal**\n```bash\npython -m apps.tui.dashboard_tui\n```\n\nOpen the Agents tab and hit **Analyze** — the agent will pull your current shortlist and return a structured bull\u002Fbear breakdown per stock.\n\n---\n\n### Option 2 — Gemma 4 MLX (Apple Silicon only)\n\nRuns Gemma 4 directly in-process via MLX. No server needed — faster response on M-series chips.\n\n```bash\npip install mlx-vlm\n# Model (~3 GB) downloads automatically on first use\n```\n\nTo use this backend, run this in the Agents tab command box or set the same preset in `data\u002Fruntime\u002Fagents\u002Factive_agent.json`:\n\n```text\n\u002Fagent gemma4_mlx\n```\n\n---\n\n### Option 3 — Claude CLI\n\nClaude is optional and never used as the default fallback.\n\n```bash\n# Install Claude Code CLI\nnpm install -g @anthropic-ai\u002Fclaude-code   # or via brew\n\n# Authenticate\nclaude login\n```\n\nThen set `active_agent.json` backend to `\"claude\"`, or switch from the TUI:\n\n```text\n\u002Fagent claude\n```\n\n---\n\n### Switching backends at runtime\n\nAll three backends are hot-swappable without restarting the terminal. In the Agents tab chat box:\n\n```text\n\u002Fagent\n\u002Fagent list\n\u002Fagent ollama gemma4:e2b\n\u002Fagent gemma4_mlx\n\u002Fagent claude\n\u002Fmodel qwen2\n```\n\nThe setting persists to `data\u002Fruntime\u002Fagents\u002Factive_agent.json`.\n\n---\n\n## Keyboard Shortcuts\n\n| Key | Action |\n|---|---|\n| `1`–`9` | Switch tabs |\n| `R` | Refresh market data |\n| `B` | Buy (paper) |\n| `S` | Sell (paper) |\n| `N` | New account |\n| `A` | Activate account |\n| `W` | Sync watchlist |\n| `H` | Help \u002F shortcuts |\n| `Q` | Quit |\n\n---\n\n## Project Structure\n\n```\nnepse-quant-terminal\u002F\n├── apps\u002Ftui\u002F\n│   ├── dashboard_tui.py        # Main TUI application\n│   └── dashboard_tui.tcss      # Textual CSS styles\n├── backend\u002F\n│   ├── trading\u002F\n│   │   ├── paper_trader.py         # Manual paper order execution\n│   │   ├── live_trader.py          # Portfolio persistence utilities\n│   │   ├── tui_trading_engine.py   # Per-account auto-trading engine\n│   │   └── strategy_registry.py    # Strategy load\u002Fsave\u002Fassign\n│   ├── backtesting\u002F\n│   │   └── simple_backtest.py      # Signal engine + backtest runner\n│   ├── market\u002F                     # Market data, quotes, scraping\n│   ├── agents\u002F                     # AI agent (Ollama \u002F Gemma MLX \u002F Claude)\n│   └── quant_pro\u002F\n│       ├── gold_hedge.py           # Gold regime overlay\n│       ├── satellite_data.py       # Hydropower signal data\n│       ├── regime_detection.py     # Market regime classifier\n│       └── paths.py                # Project path utilities\n├── configs\u002F\n│   └── long_term.py            # Default strategy parameters\n├── data\u002F\n│   └── strategy_registry\u002F      # Strategy JSON configs\n├── validation\u002F                 # Statistical validation suite\n│   ├── walk_forward.py\n│   ├── monte_carlo.py\n│   ├── cscv_pbo.py\n│   ├── statistical_tests.py\n│   └── run_all.py\n├── nepse_calendar.py           # NEPSE trading calendar (Sun–Thu)\n└── requirements.txt\n```\n\n---\n\n## Notes\n\n- **Paper trading only.** No broker API. All trades are simulated locally.\n- NEPSE trades **Sunday–Thursday**. The calendar module handles all public holidays.\n- Holding periods are in **trading days**, not calendar days. 40 trading days ≈ 8 NEPSE weeks.\n- The backtest includes realistic transaction costs: SEBON levy, broker commission, DP charges.\n- The gold hedge module uses Nepal Rastra Bank gold price data — no external API required.\n\n---\n\n## License\n\nMIT\n","NEPSE Quant Terminal 是一个基于终端的尼泊尔证券交易所（NEPSE）量化交易仪表盘，支持模拟交易、回测分析及AI代理功能。该项目采用Python编写，并使用Textual库构建用户界面，完全在本地终端运行，无需依赖浏览器或云端服务。其核心功能包括完整的纸面交易组合管理、自动交易引擎、基于六年以上历史数据的回测试验、市场实时监控面板、投资组合分析工具以及策略构建器等。特别适合于希望在不连接任何经纪商API的情况下进行量化策略研究与测试的投资者和开发者。此外，通过集成AI助手，用户还可以获得对自己持仓情况的深度分析建议。","2026-06-11 02:49:05","CREATED_QUERY"]