179 Commits
Author SHA1 Message Date
GitHubandClaude Opus 4.8 371915a5f9 feat(backtest): add BacktestEngine with vectorized execution pipeline
- Implement BacktestEngine orchestrator with 4-step pipeline:
  1. Signal generation (Strategy)
  2. Order simulation (OrderSimulator)
  3. Portfolio tracking (PortfolioTracker)
  4. Performance analysis (PerformanceAnalyzer)
- Support both strategy class and instance initialization
- Add PnL calculation for sell trades
- Add JSON serialization with numpy/timestamp support
- Include comprehensive test coverage (12 tests, all passing)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:11:20 +08:00
GitHubandClaude Opus 4.8 94fabccef8 feat(backtest): add PerformanceAnalyzer with 19 metrics
- Implement PerformanceAnalyzer class with compute() method
- Calculate 19 performance metrics: total_return, annual_return, max_drawdown,
  max_dd_duration, sharpe, sortino, calmar, trade statistics, and volatility
- Handle edge cases: empty data, no negative returns (sortino=999), no drawdown (calmar=999)
- Add 20 comprehensive unit tests covering all metrics
- Type annotations use NDArray pattern for mypy strict compliance
- All tests pass, mypy and ruff checks clean

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 18:05:33 +08:00
GitHubandClaude Opus 4.8 a2aa319803 feat(backtest): add PortfolioTracker with equity curve and drawdown
- Pre-allocate numpy arrays for performance (cash, position, avg_price)
- apply_trades() processes buys/sells with commission and slippage
- equity_curve returns DataFrame with drawdown calculation
- positions returns DataFrame with market value and unrealized PnL
- 12 unit tests covering all scenarios

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 17:55:24 +08:00
GitHubandClaude Opus 4.8 16dc2e7da9 feat(backtest): add OrderSimulator with 5 execution modes and reject policy
- Implement OrderSimulator class for order matching simulation
- Support 5 execution modes: next_open, next_close, this_close, worst, best
- Support 3 position modes: full, fixed, percent
- Support 2 reject policies: reduce (partial fill), skip (reject)
- Implement fee model: commission (min 5 CNY), stamp tax (0.1% sell only), slippage
- Add future_leak_warning flag for this_close mode
- Handle both int and datetime column types in DataFrame
- Add comprehensive test suite with 24 test cases covering all modes

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 17:52:31 +08:00
GitHubandClaude Opus 4.8 687851fc67 feat(backtest): add Strategy base class with DataProxy and crossover
- Add _SeriesAccessor for relative indexed data access ([0] current, [-1] previous)
- Add StrategyDataProxy for efficient DataFrame column access via numpy arrays
- Add crossover() function for golden cross detection (fast line crosses above slow line)
- Add Strategy abstract base class with:
  - init() for indicator registration via self.I()
  - next() for signal generation via buy()/sell()
  - Internal engine hooks (_bind_data, _call_init, _set_bar_index, etc.)
- All code is mypy strict compliant with full type annotations
- 25 unit tests covering all components

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 16:53:57 +08:00
GitHubandClaude Opus 4.8 f37b75ea42 feat(backtest): add core data types (Signal/Trade/Position/BacktestResult)
- Add Signal dataclass for trading signals with optional price/stop_loss/take_profit
- Add Trade dataclass for executed trades with commission/slippage/pnl/rejected
- Add Position dataclass for position snapshots (long/short/flat)
- Add BacktestResult dataclass with to_dict()/to_json()/summary() methods
- Add comprehensive unit tests (13 test cases, 100% pass)
- All code passes mypy strict, ruff lint+format checks

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 16:43:44 +08:00
GitHubandClaude Opus 4.8 8d68e9c094 docs: add backtest engine design spec
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 16:05:17 +08:00
Justin Gu 112ba7849f fix: chanlun bi algorithm stuck in fractal trap during sustained trends
Fix find_bis() greedy algorithm terminating early when dense alternating
fractals cause gap=0 for every opposite-type fractal. The root cause was
blindly replacing start_fx with more extreme same-type fractals, pushing
right_kline_index forward and making subsequent gaps permanently 0.

Solution: add pending_opposite guard — when an opposite-type fractal fails
the gap check, freeze start_fx replacement until a valid bi is formed.

- Affects: sustained up/down trends with dense fractals (e.g. high-price stocks)
- 600519: 114 bi (ending 04-28) -> 142 bi (ending 05-27)
- 601088: 131 bi -> 147 bi (end date unchanged)
- New regression test: test_fractal_trap_regression
- Bump version to 1.7.1
2026-06-08 03:08:12 +08:00
Justin Gu fd4a1233b4 feat: add chanlun (ChanLun) technical analysis module, bump to v1.7.0
- New chanlun/ subpackage: K-line merge, fractal, bi/xianduan/zhongshu/mmd/beichi
- New 'easy-tdx chanlun' CLI command with JSON/table output
- MACD calculation (pure numpy, no extra dependencies)
- Multi-level analysis (MultiLevelAnalyser)
- Pipeline: DataFrame -> merge -> fractal -> bi -> zhongshu -> xd -> mmd -> beichi
- 49 offline unit tests covering all calculation steps
- Detailed README docs with output explanation
- Bump version: pyproject.toml 1.6.1 -> 1.7.0, cli 1.5.0 -> 1.7.0
2026-06-07 23:29:52 +08:00
Justin Gu d01b11fa74 feat: add offline data write-back and sync commands, bump to v1.6.0
- Add write_daily.py: encode/append daily bars to .day files
- Add write_ex_daily.py: encode/append extended market daily bars
- Add write_min_bar.py: encode/append minute bars (.5/.lc1/.lc5)
- Add sync-daily CLI: sync single stock with pagination support
- Add sync-all CLI: one-command sync for all SH/SZ .day files
- Update README with sync commands and Python write API docs
- 50 new unit tests covering encode round-trip, append dedup, edge cases
- Bump version 1.5.0 -> 1.6.0
2026-06-07 21:13:49 +08:00
GitHubandClaude Opus 4.7 bcddf5a052 feat: add technical indicator calculation (30 indicators via MyTT), bump to 1.4.0
Integrate MyTT library to provide 30 technical indicators (MACD, KDJ, RSI,
BOLL, DMI, ATR, etc.) accessible via API and CLI with automatic EMA warm-up.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 16:05:40 +08:00
GitHubandClaude Opus 4.7 4820b4a049 feat: v1.1.0 - MAC protocol, CLI tool, extended markets, unified client
- Add MacClient/AsyncMacClient with full MAC protocol support (quotes, kline
  with adjustment, tick charts, transactions, boards, capital flow, auction,
  unusual, symbol info, server info)
- Add MacExClient/AsyncMacExClient for extended markets (HK, US, futures)
- Add UnifiedTdxClient auto-routing between A-share and extended markets
- Add `easy-tdx` CLI tool with JSON default output, Agent-friendly
- Add field bitmap protocol for custom quote field selection
- Fix quote-list missing fields (default to BASIC+VOLUME preset)
- Add config.py with centralized host management and auto-discovery
- Add 50+ examples covering all APIs (01-20)
- Rewrite README with CLI-first, Agent-friendly documentation
- Bump version to 1.1.0

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 22:44:45 +08:00
Justin Gu 00825eb24a feat: merge datetime fields in DataFrame output, hide MinuteBar internal fields
- K-line: daily+ periods output 'date' only, minute periods output 'datetime'
- Transactions (tick-by-tick): combine date param + hour/minute into 'datetime'
- XdxrRecord, HistoricalFundFlow: year/month/day merged to 'date'
- MinuteBar: rename unknown_1 to _unknown_1 (hidden from DataFrame)
- MinuteBar: add datetime column computed from bar index (A-share 240-bar pattern)
- get_minute_time_data: use history endpoint only (current-day endpoint broken in pytdx too)
- Update all examples to reflect new DataFrame column names
2026-05-22 04:19:07 +08:00
GitHubandClaude Opus 4.7 50491f9aae feat!: rename project from xmtdx to easy-tdx
- Package directory: src/xmtdx/ -> src/easy_tdx/
- Import path: from easy_tdx import ...
- pip install easy-tdx
- Add LICENSE (MIT) with upstream attribution (pytdx, xmtdx)
- Add NOTICE with detailed attribution
- Update all examples, tests, scripts, docs
- Bump version to 1.0.0

BREAKING CHANGE: import path changed from `xmtdx` to `easy_tdx`

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 23:21:21 +08:00
GitHubandClaude Opus 4.7 321043f9a5 feat: add professional financial data support via calc server
Add CALC_HOSTS, financial file list/record parsing (codec/financial.py),
new client methods (get_financial_file_list, get_financial_file,
get_financial_records) with async counterparts, and example 09 demo.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:15:42 +08:00
minionszyw 7c085f7537 Normalize xdxr per-share fields 2026-04-22 19:42:34 +08:00
minionszyw 91f6a884d5 Fix security list pre-close decoding 2026-04-22 18:50:07 +08:00
minionszyw 41cb3bfd28 Fix current minute data client path 2026-04-22 18:34:59 +08:00
minionszyw aa3b1ac319 Fix transport and fund flow protocol edge cases 2026-04-22 17:54:13 +08:00
M 4cb48daabb Add live fallbacks for history fund flow and price limits 2026-04-15 21:23:13 +08:00
M 96f14f70bc Fix protocol regressions and clarify experimental APIs 2026-04-15 21:02:26 +08:00
M daaba7dc13 feat: 补全 A 股历史资金流向序列功能
1. 新增命令:实现 GetHistoryFundFlowCmd (0x052d Category 22) 用于拉取历史资金分布。
2. 新增模型:增加 HistoricalFundFlow 结构,支持超大/大/中/小单的双向统计。
3. 客户端 API:TdxClient/AsyncTdxClient 增加 get_history_fund_flow() 接口。
4. 单元测试:在 test_a_share_extensions.py 中增加响应包解析逻辑验证。
5. 文档更新:README.md 同步 API 及数据模型定义。
2026-04-15 15:26:51 +08:00
M 4dabbf6d15 feat: A 股深度数据补全与全市场覆盖方案
1. 全市场覆盖:增加北交所 (Market.BJ) 支持,实现沪深京三市 A 股 100% 物理一致获取。
2. 资金流向:实现 get_fund_flow() 接口,基于 Tick 数据实现超大/大/中/小单加权统计。
3. 行业挂载:实现 tdxhy.cfg 解析,支持全量 A 股列表自动关联通达信/申万行业标签。
4. 市场统计:完善 get_market_stat() 接口,支持获取全 A 股涨跌家数及成交额。
5. 健壮性与测试:补全 a_share_extensions 单元测试,重构心跳测试以消除外部依赖,全量测试 100% 通过。
6. 文档对齐:README.md 同步更新特性、API 列表及数据模型。
2026-04-15 12:57:28 +08:00
M 081f851c6d feat: AsyncTdxClient 增加心跳保活机制
1. 在 AsyncTdxClient 中增加后台心跳任务,默认每 60 秒发送一次请求。
2. 支持在连接成功后自动启动,并在连接关闭时自动停止心跳任务。
3. 增加单元测试 tests/unit/test_heartbeat.py 验证心跳循环与清理逻辑。
2026-04-14 18:11:05 +08:00
M fcd14c1d49 feat: 增加板块信息(block_info)获取与解析功能
1. 核心模型:增加 TdxBlock dataclass。
2. 协议命令:实现 GetBlockInfoMetaCmd 与 GetBlockInfoCmd。
3. 编解码器:增加 codec/block.py,支持 .dat 板块文件二进制解析。
4. 客户端 API:TdxClient 和 AsyncTdxClient 增加 get_block_info(),支持分片拉取。
5. 测试与验证:增加单元测试 tests/unit/test_block_info.py 及实测脚本。
6. 文档更新:README.md 同步 API 及安装说明。
2026-04-14 17:23:54 +08:00
MandClaude Sonnet 4.6 74ae6b6975 fix: xdxr_info 股本字段改用 _decode_volume 解码,单位万股
股本字段(category 2–10 的 panqian_liutong / panhou_liutong /
qian_zongguben / hou_zongguben)与成交量字段使用相同的通达信自定义
4 字节浮点格式;原 float(uint32) 直解差约 374 倍。

改用 _decode_volume 后,最近一条 hou_zongguben(3,330,583.75 万股)
与 FinanceInfo.zong_guben / 10000(3,330,583.75 万股)完全吻合。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 14:38:45 +08:00
minionszyw 16c237d5a0 Harden transport and decode paths 2026-04-11 21:47:08 +08:00
minionszywandClaude Sonnet 4.6 0fa685dbdd feat: 离线 fixture 测试、unknown 字段探测脚本、高可用传输层
- tests/fixtures/:录制 12 条命令真实响应 body(hex),配套 json 预期值
- tests/unit/test_commands_offline.py:13 个离线 pytest,无需网络,验证
  各命令解析正确性及所有已知 bug 修复(#1~#5)
- scripts/probe_unknowns.py:对比 unknown_1/2/3/5~8 与均价、涨停价等假设,
  输出相关性分析报告,供后续字段逆向使用
- transport/sync.py:新增 ping_host()、ping_all()(并发测速)、KNOWN_HOSTS
- client.py:TdxClient.from_best_host() 工厂方法(自动优选最低延迟服务器)、
  TdxClient.ping_all() 静态代理、_execute() 断线自动重连(重试一次)
- 修复 GetTransactionDataCmd.parse_response 多余 skip 参数调用

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 20:33:41 +08:00
minionszywandClaude Sonnet 4.6 283682f6b4 feat: 初始实现 xmtdx —— 从零实现通达信 TCP A 股行情客户端
替代年久失修的 pytdx,修复已知 bug,保留未解字段供逆向分析。

主要内容:
- codec 层:get_price 变长编码、get_volume 自定义浮点、datetime/frame 解析
- transport 层:同步(socket)+ 异步(asyncio)双实现,共用命令层
- 命令层(11 条):security_count/list/quotes/bars、minute_time(今日+历史)、
  transaction(当日+历史)、xdxr_info、finance_info、company_info
- 高层 API:TdxClient + AsyncTdxClient
- 单元测试 26 条,全部通过;真实服务器集成测试覆盖全部命令

修复 pytdx Bug #1–5:xdxr 循环读取错误位置、GBK 截断崩溃、
pre_close 误用 get_volume、逐笔/分时未解字段被丢弃

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 19:55:19 +08:00