Commit Graph
129 Commits
Author SHA1 Message Date
Justin Gu d904ae7af6 docs(web): update README with serve CLI, docs URL, and install instructions 2026-06-12 03:35:26 +08:00
Justin Gu 0e74752701 fix(web): validate market/category input — support lowercase, reject invalid with 400
Root cause: _market_from_str/_market/_category in routers used bare
MarketEnum[key]/Market[key] without .upper() or try/except, so
lowercase or invalid values (sz, ZZZ) threw uncaught KeyError → 500.

Fix: extract shared convert.py with market_from_str/category_from_str
that do .upper() + ValueError on invalid input.  All 4 routers updated.
4 regression tests added for case-insensitive and invalid input.
2026-06-12 03:26:29 +08:00
Justin Gu 9d7a9161f7 fix(web): remove TYPE_CHECKING guard for AsyncTdxClient in deps.py
The typing.cast(AsyncTdxClient, ...) evaluated AsyncTdxClient at
runtime, but the import was gated behind TYPE_CHECKING, causing
NameError in production.  Direct import is safe here — web module
already depends on easy_tdx core.
2026-06-12 03:21:39 +08:00
Justin Gu 54dd65ed85 feat(web): add Web API docs to README, bump version to 1.10.0 2026-06-12 03:10:01 +08:00
Justin Gu eb8a7a5675 feat(web): add FastAPI app factory, all routers, CLI serve command, and tests
- App factory with lifespan management and CORS middleware
- Market router: security list, quotes, market stat, fund-flow
- Bars router: kline, index kline, minute, transaction
- Finance router: xdxr, finance, company info, financial records
- Block router: block file parsing
- Chanlun router: POST /chanlun/analyze
- Realtime router: WebSocket /ws/realtime/{symbol}
- CLI: easy-tdx serve command
- 16 unit tests, all passing offline (no network)
2026-06-12 03:08:12 +08:00
Justin Gu 9dc70566a5 feat(web): add Pydantic schemas and error handling 2026-06-12 03:02:04 +08:00
Justin Gu 7f44ba1d06 feat(web): scaffold web API module with [web] optional dependency 2026-06-12 03:00:49 +08:00
GitHubandClaude Opus 4.8 fd03e2a334 fix: ruff format compliance for CI
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 22:56:23 +08:00
GitHubandClaude Opus 4.8 e290ea3f21 feat: add board N-day change ranking (v1.9.10)
- Add get_board_change_ranking() to MacClient and AsyncMacClient
- Add 'board-change-ranking' CLI command (--type/--date/--days/--top/--asc)
- Calculate N-day price change from board index K-lines directly
- Default to listing all boards; --top N to truncate
- 12 unit tests covering calculation, edges, sorting

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 17:40:51 +08:00
Justin Gu 786c7e3619 fix: remove unused type: ignore comments for mypy strict 2026-06-11 04:30:39 +08:00
Justin Gu c25570eb86 fix: mypy strict — type annotate co_filename in _get_strategy_file 2026-06-11 04:27:54 +08:00
Justin Gu c9ed57e66d fix: parallel scan pickle bug — pass strategy file path instead of class to child processes 2026-06-11 04:24:09 +08:00
Justin Gu ddcb9d4425 release: v1.9.8 — CI fixes (ruff .pyi exclude + pytest-asyncio + lint) 2026-06-11 04:11:01 +08:00
Justin Gu bd373b9c3c fix: exclude .pyi from ruff + fix unused variable in test 2026-06-11 04:06:52 +08:00
Justin Gu 193d1b0d82 fix: add pytest-asyncio dependency for async realtime tests 2026-06-11 04:03:00 +08:00
Justin Gu 15cc7680c4 release: v1.9.7 — CLI全量集成(workers/cache/chanlun-level/portfolio/multi-level)+ bugfix 2026-06-11 03:57:48 +08:00
Justin Gu d2f4cb126e release: v1.9.6 — Devin AI 12项改进全量落地 2026-06-11 02:40:31 +08:00
Justin Gu 92edc189bb feat: realtime event-driven market data push framework
- Add EventBus for async publish/subscribe market events
- Add MarketEvent dataclass with tick/bar/signal/error types
- Add RealtimeStrategy base class with on_tick/on_bar callbacks
- Add emit_signal() for strategy-to-engine signal publishing
- Support per-symbol and global subscriptions
- API skeleton: transport-level subscription TBD
- Add 10 tests covering events, bus, and strategy
2026-06-11 02:34:00 +08:00
Justin Gu 9c39ad054d feat: multi-stock portfolio backtest engine
- Add PortfolioBacktestEngine for shared-capital multi-stock backtesting
- Support equal allocation mode (total_cash / N per stock)
- Individual BacktestEngine per stock with allocated capital
- Aggregate performance via capital-weighted returns
- Add StockData, PortfolioResult data classes
- Add 4 tests: basic run, equal allocation, empty stocks, serialization
2026-06-11 02:31:43 +08:00
Justin Gu fa5bd2d44d feat: add MyTT.pyi type stubs, enable strict mypy
- Create type stub file for 50+ MyTT indicator functions
- Covers all 31 functions used in the project + common utilities
- Remove mypy disallow_untyped_defs/calls override for MyTT
- MyTT now covered by strict mypy via .pyi stubs
2026-06-11 02:29:47 +08:00
Justin Gu f4dc28c5d2 feat: add append_klines for incremental chanlun analysis
- Store previous DataFrame in ChanlunAnalyser after process_klines
- Add append_klines(df_new) to concatenate and recompute
- Handles datetime deduplication automatically
- Raises RuntimeError if called before initial process_klines
- Add 2 tests: append + recompute, error without init
2026-06-11 02:25:42 +08:00
Justin Gu 6d74c2e5eb feat: enhance multi-level chanlun analysis with trend/overlap/divergence
- Add trend_direction detection (up/down/None) via consecutive bi analysis
- Add bi_overlap detection for consolidation identification
- Add divergence_possible check (2+ ZS + diminishing amplitude)
- Return type changed from dict[str, int] to dict[str, Any]
- Backward compatible: all original fields preserved
- Extract 3 helper functions for clean separation of concerns
2026-06-11 02:22:31 +08:00
Justin Gu ec8d21b7e2 feat: incremental scanning with mtime-based cache
- Add cache_file param to SignalScanner for persistent scan cache
- Cache stores {filepath: {mtime, result}} as JSON
- On rescan, skip files with unchanged mtime (reuse cached results)
- Files with changed mtime are rescanned and cache updated
- Add 3 tests: cache reuse, no-cache full scan, cache invalidation
2026-06-11 02:17:52 +08:00
Justin Gu b7e0f17842 feat: concurrent scanning with ProcessPoolExecutor
- Add workers param to SignalScanner.scan() (default=0 for serial)
- workers=2+ uses ProcessPoolExecutor for parallel .day file processing
- Extract _scan_one_file as top-level function for pickle compatibility
- Results identical between serial and parallel modes
- Add 4 tests with synthetic .day file fixtures
2026-06-11 02:09:10 +08:00
Justin Gu af005d9fe4 feat: auto-bridge chanlun analysis into backtest strategies
- Add chanlun_level param to BacktestEngine constructor
- When set, auto-create ChanlunAnalyser and compute ChanlunResult
- Manual chanlun_result in run() takes priority over auto-compute
- Update Strategy.chanlun type to Any (accepts ChanlunResult or dict)
- Add 2 tests: auto-bridge and manual override priority
2026-06-11 01:56:59 +08:00
Justin Gu 815b3ddf7c feat: implement stop-loss/take-profit execution in backtest engine
- Track SL/TP conditions from BUY signals in _generate_signals loop
- Check active conditions against each bar's high/low price range
- Auto-generate SELL signal at trigger price when condition is met
- Modify OrderSimulator to respect signal.price for direct execution
  (previously signal.price was stored but never used in execution)
- SL/TP activates on bar AFTER BUY signal (consistent with next_open)
- Stop-loss checked before take-profit (conservative for holder)
- Add 4 tests: SL trigger, TP trigger, no-trigger, priority over manual sell
2026-06-11 01:53:11 +08:00
Justin Gu 06b2617ebc fix: CI coverage enforcement, real avg_holding_days, vectorize _datetime_to_int
- Add --cov and --cov-fail-under=50 to CI pytest command
- Replace hardcoded avg_holding_days=5.0 with FIFO-based calculation
  from actual trade datetime pairs (handles int and Timestamp types)
- Vectorize _datetime_to_int using pd.to_datetime().strftime()
  instead of Python for-loop (~100-200x faster on large arrays)
- Add 3 new test cases: weighted holding days, no datetime fallback,
  only-buys edge case
2026-06-11 01:44:39 +08:00
GitHubandClaude Opus 4.8 b4f63c85a6 feat: add OBV trend strategy (v1.9.5)
- New obv_trend.py strategy: OBV energy flow trend following
- Entry: OBV > MAOBV*1.02 buffer + MAOBV 20-bar uptrend confirmed
- Exit: OBV drops below MAOBV
- Tunable params: maobv_period(30), maobv_lookback(20), obv_buffer(0.02)
- Update README changelog and strategy table
- Bump version to 1.9.5

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 18:53:06 +08:00
GitHubandClaude Opus 4.8 79c6fcee0e fix: remove unused type: ignore comments in analyser.py
Use 'row_any: Any = row' pattern to avoid arg-type mismatch between
local (pandas-stubs) and CI (bare pandas) environments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 15:12:38 +08:00
GitHubandClaude Opus 4.8 4dfd18050e fix: resolve all CI mypy (265→0) and ruff (26→0) errors
- pyproject.toml: add mypy overrides for pandas/tabulate/matplotlib stubs,
  disable strict checking for vendored MyTT library
- config.py: use cast() for dict[str, Any] .get() returns
- beichi.py: widen _calc_bi_force param to BI | XD, import XD
- backtest/cli.py: split combo/single strategy into separate typed variables
- backtest/combo.py: add bool_array() helper for numpy return types
- chanlun/analyser.py: type ignore for pandas row access, fix dict type arg
- unified.py: change fields param from object to Any
- ex/mac_client.py: add type args to list literals
- cli/cmd_offline.py: wrap int market as Market enum before API call
- cli/cmd_chanlun.py: fix dict type arg
- offline/write_*.py: explicit int() cast for struct.unpack returns
- MyTT.py: fix line-too-long comments, UP038 isinstance syntax
- tests: fix E712 (==False → ~mask), E741 (noqa), F841, import sorting
- ruff format applied across codebase

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 15:03:41 +08:00
Justin Gu 5aac7d3a39 chore: add risk disclaimer, CI pipeline, pytest coverage config
- Add risk warning after backtest demo output (survivorship bias, overfitting)
- Add disclaimer section at README end
- Add slippage comment to backtest demo command
- Add CI workflow (test + lint + mypy) for PR/push to main
- Add pytest config with coverage threshold (fail_under=50, current=56%)
2026-06-10 12:43:02 +08:00
Justin Gu 21f71d3701 chore: ignore .omc, .claude, .playwright-mcp directories and remove from tracking 2026-06-10 11:54:08 +08:00
Justin Gu c867297d45 fix: remove hardcoded version in 'version' command (v1.9.4) 2026-06-10 03:40:28 +08:00
Justin Gu 531d0c05bc fix: remove hardcoded version in 'version' command, read from importlib.metadata 2026-06-10 03:39:09 +08:00
Justin Gu 862f713483 feat: add 'run-all' CLI command for batch strategy backtesting (v1.9.3) 2026-06-10 03:24:31 +08:00
Justin Gu a3d6d93122 feat: strategy screener - scan all stocks by signal, rank by backtest performance (v1.9.2)
- Add 'screen' CLI command group with 'scan' and 'rank' subcommands
- scan: offline signal scanning from local .day files, zero network IO
- rank: backtest ranking of scanned signals by sharpe/drawdown/etc
- Two-step workflow: scan outputs JSON, rank reads JSON and evaluates
- Support --universe (all/sh/sz/custom file), --sort, --names
- Support pipe mode: scan ... | rank --from - --table
- New module: src/easy_tdx/screen/{scanner,ranker,cli}.py
- 20 unit tests (offline, no network required)
2026-06-10 03:03:03 +08:00
Justin Gu cb0a8ef6c5 chore: bump version to 1.9.1 2026-06-10 02:14:53 +08:00
Justin Gu 5691bb8432 refactor: screen() reuses run_combination(), single runner across combo sizes
- screen() now calls run_combination() internally, eliminating duplicated
  signal extraction/combination logic
- _run_combo_screen creates one CombinationRunner before the size loop,
  so signal cache is reused across 2-factor and 3-factor screens
- Add MAJORITY(2)=AND note to screen() docstring
2026-06-10 02:13:28 +08:00
Justin Gu 1e99feb7c2 feat: multi-factor combo backtest engine (v1.9.0)
- Add backtest/combo.py: CombinationRunner, extract_factor_signals, combine_masks
- Signal merge modes: AND / OR / MAJORITY (majority default)
- CLI: --combo-strategies and --combo-mode for easy-tdx backtest
- run_all_strategies.py: --combo 2 --combo 3 auto-screen best combos
- Fix MyTT MFI/CR divide-by-zero RuntimeWarning
- 14 new unit tests, 328 total passing
2026-06-10 01:37:28 +08:00
GitHubandClaude Opus 4.8 7f1bc645c2 release: v1.8.2 - 5 new strategies, --show chart, 15 total
- New strategies: dmi_trend, cci_breakout, mfi_volume, trix_cross, mtm_momentum
- run_all_strategies.py --show: dual-axis equity curve vs stock price chart
- zhuoyao_momentum strategy (from earlier commit)
- README: updated strategy table (9→15), changelog, demo screenshots
- Bump version to 1.8.2

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 23:17:04 +08:00
GitHubandClaude Opus 4.8 8fcedeb47a feat(strategies): add zhuoyao_momentum strategy + Maotai demo screenshot
- New ZHUOYAO multi-timeframe momentum strategy (strategies/zhuoyao_momentum.py)
- Entry: SHORT>0 + TREND>0 + SHORT>MID (triple resonance)
- Exit: SHORT<0 or TREND<0 (conservative, any triggers sell)
- Add SH600519 Maotai demo screenshot (strategies/demo/4.png)
- Update README with 4th demo screenshot

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 22:59:19 +08:00
GitHub b57d8f4669 feat(backtest): add --show flag for best strategy equity curve chart
- Add --show/--show-chart flag to run_all_strategies.py
- Display dual-axis chart: normalized stock price vs strategy equity curve
- Mark buy/sell points with green/orange triangles
- Auto-detect Chinese fonts (SimHei/YaHei on Windows, PingFang on macOS)
- Fetch stock name via get_stock_quotes for chart title
- Add 3 demo screenshots to README with disclaimer
- Update README with --show usage and visual examples
2026-06-09 22:41:14 +08:00
GitHubandClaude Opus 4.8 b44636207b release: v1.8.1 - single-source version, batch backtest detail output
- Consolidate version to pyproject.toml as single source of truth
- __init__.py, cli/__init__.py, docs/conf.py all read dynamically
- run_all_strategies.py now shows best strategy full trade details
- Update README changelog for 1.8.1

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 22:12:27 +08:00
GitHubandClaude Opus 4.8 b5b5d0dc5b release: v1.8.0 - backtest engine with batch strategy comparison
- Add backtest section to README with CLI usage and run_all_strategies.py demo
- Update all version numbers to 1.8.0 (pyproject.toml, __init__.py, cli/__init__.py, docs/conf.py)
- Fix turtle_breakout strategy: TAQ returns 3 values (UP, MID, DOWN)
- Add run_all_strategies.py batch comparison script
- Update README intro to highlight backtest feature
- Add backtest to CLI command table and architecture tree

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 20:35:38 +08:00
GitHubandClaude Opus 4.8 70c69c8a66 fix(backtest): cli _print_table used wrong key 'sharpe_ratio' instead of 'sharpe'
Performance dict outputs 'sharpe' but _print_table looked up 'sharpe_ratio',
so perf.get('sharpe_ratio', 0) always returned the default 0 regardless of
actual Sharpe value.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 20:02:20 +08:00
GitHubandClaude Opus 4.8 46298e68d7 fix(backtest): max drawdown now correctly measures peak-to-trough percentage
Previous formula was: max(absolute_drawdown) / initial_capital, which
exceeds 100% when the portfolio grows then drops (e.g. from 600k to 300k
on a 100k initial = 300% drawdown, which is nonsensical).

Fixed to use drawdown_pct (drawdown / peak) which is always in [0, 1].
This correctly measures the maximum percentage drop from the highest
equity peak, matching the standard financial definition.

Also added regression test: test_max_drawdown_never_exceeds_100_pct.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 19:00:11 +08:00
GitHubandClaude Opus 4.8 5550702620 fix(strategies): unpack BIAS triple return value in bias_reversal
MyTT.BIAS returns (BIAS6, BIAS12, BIAS24) but the strategy was assigning
all three to a single variable, causing 'array with more than one element'
ValueError when comparing to a scalar threshold.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:56:07 +08:00
GitHubandClaude Opus 4.8 6a6d75f5d5 fix(backtest): strategy position not tracked during signal generation
Root cause: _generate_signals() iterated all bars calling strategy.next()
but never updated _position_size or _cash on the strategy. Strategies
that check self.position['size'] before buy/sell always saw 0, producing
only BUY signals with no SELL — exhausting cash and producing drawdowns
exceeding 100%.

Fix: add _update_strategy_position() that estimates position changes
after each bar's signals using close price. This gives the strategy an
accurate view of its holdings so it can correctly alternate buy/sell.

Regression tests added:
- test_position_aware_buy_sell_alternation: verifies BUY/SELL alternation
- test_position_aware_no_duplicate_buys: no suspicious tiny duplicate buys

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:50:13 +08:00
GitHubandClaude Opus 4.8 f7e1abd873 feat: add 9 demo strategy files for backtest engine
Strategies included:
- ma_cross: MA5/MA20 dual moving average crossover
- expma_cross: EMA12/EMA50 crossover (more responsive)
- macd_cross: MACD golden/death cross
- bollinger_breakout: Bollinger band breakout
- rsi_reversal: RSI overbought/oversold reversal
- kdj_golden: KDJ low golden cross / high death cross
- turtle_breakout: Turtle trading (Donchian channel)
- bias_reversal: BIAS mean reversion
- volume_price: Volume-price confirmation

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:45:01 +08:00
GitHubandClaude Opus 4.8 00b7d75caa docs: add backtest engine usage manual
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:37:58 +08:00