Metadata-Version: 2.4
Name: tqx-cli
Version: 0.2.2
Summary: TQX QUBE 港股/美股因子分析与策略回测 CLI
Author: PandaAI
License: MIT
Project-URL: Homepage, https://www.tqx.trade
Keywords: tqx,pandaai,factor,backtest,quant,cli,港股,美股
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
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 :: Office/Business :: Financial :: Investment
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28
Requires-Dist: pyyaml>=6.0

# tqx-cli

`tqx-cli` 是 TQX QUBE 的港股、美股因子研究与策略回测命令行工具。

QUBE 是 TQX 网站的子应用：

- 生产 Web：`https://www.tqx.trade/agent_quant/`
- 生产 API：`https://www.tqx.trade/pandaApi/agent_quant/api`
- 测试 Web：`http://192.168.xxxx/agent_quant/`
- 测试 API：`http://192.168.xxxx/pandaApi/agent_quant/api`

登录仍复用 TQX 的 `/tqxApi/auth/login` 和 `/tqxApi/user/info`。因子、策略和回测命令使用 QUBE API，不再创建 QuantFlow JSON 工作流。

## 安装

要求 Python 3.10 或更高版本。

```powershell
python -m pip install --upgrade "tqx-cli>=0.2.0"
python -m tqx_cli.cli --version
tqx-cli --version
tqx-cli --help
```

必须确认版本为 `0.2.0` 或更高版本。`0.1.x` 是旧 QuantFlow Workflow CLI，使用其中的
`factor_create` 或 `strategy_create` 会创建到旧工作流页面，不得用于 QUBE。

如果 PyPI 尚未提供 `0.2.0`，从本仓库的 `tqx_cli` 子目录安装 QUBE 版本：

```powershell
python -m pip uninstall -y tqx-cli
python -m pip install --upgrade "tqx-cli @ git+https://cnb.cool/liangyunzhijing/clis.git@main#subdirectory=tqx_cli"
python -m tqx_cli.cli --version
tqx-cli --version
```

两个版本命令必须都成功、均为 `0.2.0` 或更高版本且版本号一致。否则当前 PATH 可能仍指向其他 Python
环境中的旧 `tqx-cli`。版本检查没有通过时，不要执行任何创建或运行命令。

源码调试：

```powershell
cd C:\PythonAIProject\clis\tqx_cli
python -m pip install -e .
python cli.py --help
```

`tqx-cli ...` 和 `python cli.py ...` 使用相同入口。前者要求当前 Python 环境已经安装本项目。

## 环境设置

默认使用生产站点，无需设置环境变量：

```powershell
$env:TQX_SITE_URL = "https://www.tqx.trade"
```

切换测试环境时设置测试站点根地址，不要附加 `/agent_quant/` 或 `/pandaApi`：

```powershell
$env:TQX_SITE_URL = "http://192.168.xxxx"
```

CLI 自动派生：

```text
TQX 登录：<TQX_SITE_URL>/tqxApi/...
QUBE API：<TQX_SITE_URL>/pandaApi/agent_quant/api/...
```

每个站点使用独立登录会话，默认保存到 `~/.tqx/config.yaml`。切换环境后需要在该环境登录一次。

## 登录

推荐交互式输入密码：

```powershell
tqx-cli login --email user@example.com
```

也可以显式提供密码，但命令可能进入终端历史：

```powershell
tqx-cli login --email user@example.com --password xxxx
```

Google 一键登录用户需要先前往 [TQX 个人中心](https://www.tqx.trade/hk/personal-center)设置密码，再使用对应邮箱登录 CLI。

查询当前登录用户，调用原 TQX `/tqxApi/user/info`：

```powershell
tqx-cli info
```

查询 TQX 主站钱包余额。该命令独立于 QUBE Library，但共用当前 TQX 登录会话：

```powershell
tqx-cli balance
```

## 命令总览

```text
认证
  login                                                   使用邮箱和密码登录 TQX
  info                                                    查看当前登录用户信息
  balance                                                 查询 TQX 钱包余额

Factor Library
  factor_create                                           创建港股或美股因子定义
  factor_info <factor_id>                                 查看指定因子的定义和参数
  factor_update <factor_id>                               修改指定因子的定义和参数
  factor_list                                             列出 Factor Library 中的因子
  factor_delete <factor_id> [...]                         删除一个或多个因子
  factor_run <factor_id>                                  创建并运行一次因子分析，返回 analysis_id
  factor_stop <analysis_id>                               停止指定的因子分析任务
  factor_result <analysis_id>                             查询指定因子分析任务的状态和结果

Strategy Library
  strategy_create                                         创建港股或美股策略
  strategy_info <strategy_id>                             查看指定策略的代码和参数
  strategy_update <strategy_id>                           修改指定策略的代码和参数
  strategy_list                                           列出 Strategy Library 中的策略
  strategy_delete <strategy_id> [...]                     删除一个或多个策略
  strategy_run <strategy_id>                              启动策略回测，返回 run_id
  strategy_stop <run_id>                                  停止指定的策略回测任务
  strategy_result <run_id>                                查询指定策略回测的状态和结果

Backtests
  backtest_list                                           列出所有回测记录
  backtest_result <run_id>                                查询指定回测记录的完整结果

Competition Management
  competition_account_list                                列出 Competition trading accounts
  competition_account_info <trading_account_id>           查看账户类型、运行模式和状态等信息
  competition_account_result <trading_account_id>         查看账户、持仓、成交、收益曲线和日志
  competition_account_stop <trading_account_id>           退出正在 Monitoring 的账户实例
  competition_account_delete <trading_account_id> [--yes] 删除尚未启动的账户实例；--yes 跳过确认
```

QUBE 不提供通用 Workflow 或 JSON 导入导出接口，因此本版本不包含 `workflow_*` 和 `workflow_export/import`。`balance` 继续使用 TQX 主站钱包接口。

全局参数必须放在子命令前：

```powershell
tqx-cli --json strategy_list --market us
tqx-cli --config .\debug.yaml factor_list --market hk
```

## ID 规则

QUBE ID 都是正整数。

| ID | 来源 | 用途 |
|---|---|---|
| `factor_id` | `factor_create` | 因子查看、修改、运行和删除 |
| `analysis_id` | `factor_run` | 因子分析停止和结果查询 |
| `strategy_id` | `strategy_create` | 策略查看、修改、运行和删除 |
| `run_id` | `strategy_run` | 回测停止和结果查询 |

`factor_stop` 不接收 `factor_id`，`strategy_stop` 不接收 `strategy_id`。

## Factor Library

### 创建因子定义

公式模式：

```powershell
tqx-cli factor_create --market hk `
  --formula "close" `
  --name "港股收盘价因子"

tqx-cli factor_create --market us `
  --formula "volume" `
  --name "美股成交量因子"
```

Python 文件模式：

```powershell
tqx-cli factor_create --market hk `
  --file .\tests\test_factor_anlysis_hk.py `
  --name "港股动量因子"

tqx-cli factor_create --market us `
  --file .\tests\test_factor_anlysis_us.py `
  --name "美股成交量因子"
```

`--formula` 创建 `code_type=formula`；`--code` 和 `--file` 创建 `code_type=python`。多行 Python 推荐使用 `--file`。

QUBE 的 Factor 只保存因子定义，所以 `factor_create` 不再接收分析日期、调仓周期、分组数量和因子方向。这些参数属于每一次分析任务，必须传给 `factor_run`。

### 查看、修改和列出因子

```powershell
tqx-cli factor_info <factor_id>

tqx-cli factor_update <factor_id> `
  --formula "volume/MAX(ref(volume,5),1)" `
  --name "标准化成交量"

tqx-cli factor_list --market all
tqx-cli factor_list --market hk --limit 20 --offset 0
tqx-cli factor_list --market us --keyword "momentum"
```

列表对应 QUBE 页面 Factor Library 的 `All/HK/US`。

### 运行因子分析

```powershell
tqx-cli factor_run <factor_id> `
  --start-date 20260101 `
  --end-date 20260331 `
  --adjustment-cycle 5 `
  --group-number 5 `
  --factor-direction Positive `
  --timeout 1200
```

参数：

| 参数 | QUBE 默认值 | 说明 |
|---|---:|---|
| `--start-date` | QUBE 自动确定 | `YYYYMMDD` 或 `YYYY-MM-DD` |
| `--end-date` | QUBE 自动确定 | 必须晚于开始日期 |
| `--adjustment-cycle` | `5` | 调仓交易日数，必须大于 0 |
| `--group-number` | `5` | 分组数量，`2..20` |
| `--factor-direction` | `Positive` | `Positive/Negative`、`正向/负向`、`1/0` |
| `--timeout` | `600` 秒 | 只限制 CLI 等待，不自动取消任务 |
| `--no-wait` | 关闭 | 提交后立即返回 `analysis_id` |

正向转换为 QUBE `factor_direction=1`，负向转换为 `0`。

异步使用：

```powershell
tqx-cli factor_run <factor_id> --no-wait
tqx-cli factor_result <analysis_id>
tqx-cli factor_stop <analysis_id>
```

`factor_stop` 默认等待最多10秒确认取消。若后端已接受请求但状态尚未更新，返回
`request_accepted=true`、`success=false` 和 `status=STOP_REQUESTED`，不会误报已取消。

### 删除因子

```powershell
tqx-cli factor_delete <factor_id> --yes
tqx-cli factor_delete <factor_id_1> <factor_id_2> --yes
```

## Strategy Library

### 创建策略

```powershell
tqx-cli strategy_create --market hk --file .\tests\hk_ma.py `
  --name "港股均线策略" `
  --start-date 20250101 --end-date 20250331 `
  --frequency 1d

tqx-cli strategy_create --market us --file .\tests\us_ma.py `
  --name "美股均线策略" `
  --start-date 20250101 --end-date 20250331 `
  --frequency 1d `
  --symbols TSLA.NB
```

策略定义和默认回测参数一次写入 QUBE Strategy。默认参数：

| 参数 | 默认值 |
|---|---:|
| `--start-capital` | `10,000,000` |
| `--commission-rate` | `1.0` |
| `--slippage` | `0.0` |
| `--frequency` | `1d` |
| `--symbols` | 不限制，由策略代码决定 |

`1M` 表示一分钟 bar，不是月线。止损、止盈、指标窗口、券池、排序、`top_n` 和调仓逻辑仍写在 Python 策略代码中。

### 查看、修改和列出策略

```powershell
tqx-cli strategy_info <strategy_id>

tqx-cli strategy_update <strategy_id> --file .\tests\us_ma.py `
  --name "美股均线策略 v2" `
  --version-summary "调整均线参数" `
  --start-date 20260101 --end-date 20260331

tqx-cli strategy_list --market all
tqx-cli strategy_list --market hk --limit 20
tqx-cli strategy_list --market us --keyword "momentum"
```

列表对应 QUBE 页面 Strategy Library 的 `All/HK/US`。

修改日期或本次回测日期时，CLI 会保留支持的回测参数，只覆盖明确传入的字段，并过滤服务端返回的
`margin_rate`、`standard_symbol` 等非 CLI 字段和 `null` 值。因此通常不需要为不同回测周期删除重建策略。

### 运行和停止回测

不传参数时使用策略保存的 `params.backtest`：

```powershell
tqx-cli strategy_run <strategy_id> --timeout 1200
```

本次运行覆盖参数：

```powershell
tqx-cli strategy_run <strategy_id> `
  --start-date 20260101 --end-date 20260331 `
  --start-capital 10000000 `
  --commission-rate 1 `
  --slippage 0 `
  --frequency 1d `
  --symbols TSLA.NB AAPL.NB `
  --timeout 1200
```

策略代码中的 `from ... import *` 只能放在模块顶层；函数体内的星号导入会被本地校验拒绝。
`handle_data` 中读取当前 bar 请使用 `data[symbol]` 并处理缺失标的，不要使用 `data.get(symbol)`。

异步使用：

```powershell
tqx-cli strategy_run <strategy_id> --no-wait
tqx-cli strategy_result <run_id>
tqx-cli strategy_stop <run_id>
```

`TIMEOUT` 只结束 CLI 等待，任务仍在 QUBE 运行；使用返回的 `stop_command` 或显式执行 `strategy_stop <run_id>`。

### 删除策略

```powershell
tqx-cli strategy_delete <strategy_id> --yes
```

策略绑定远程仿真盘或关联任务无法取消时，QUBE 可能返回 HTTP 409。CLI 不会自动删除关联业务。

## Backtests

Backtests 对应 QUBE 左侧的 Backtests 页面：

```powershell
tqx-cli backtest_list --market all
tqx-cli backtest_list --market hk
tqx-cli backtest_list --market us --limit 20 --offset 0
```

查询同一个回测结果可以使用任一命令：

```powershell
tqx-cli strategy_result <run_id>
tqx-cli backtest_result <run_id>
```

QUBE 在一个响应中返回 `metrics`、`metric_views`、`equity`、`trades`、`log` 和进度信息，不再使用旧版 `account/position/profit/trade/log` 分段接口。

保存 JSON：

```powershell
tqx-cli backtest_result <run_id> --download .\result\backtest.json
tqx-cli strategy_run <strategy_id> --download .\result\backtest.json --timeout 1200
```

## Competition Management

这些命令对应 TQX Competition Management 页面。`trading_account_id` 可以使用列表返回的 `trading_account_id`、`agent_id`、`account_id` 或非空的 `broker_account_id`。

```powershell
tqx-cli competition_account_list
tqx-cli competition_account_info <trading_account_id>
tqx-cli competition_account_result <trading_account_id> --page-size 100
```

`competition_account_info` 会统一显示：

- `trading_type`：`Live`、`Simulation` 或 `Unknown`
- `run_mode`：例如 `Local`
- `status`：`Not started`、`Monitoring`、`Exited` 或 `Deleted`
- `raw_status`：服务端原始状态

只有 Monitoring 账户可以执行 Exit；只有 Not started 账户可以删除：

```powershell
tqx-cli competition_account_stop <trading_account_id>
tqx-cli competition_account_delete <trading_account_id> --yes
```

## PowerShell 代码输入

推荐直接使用文件：

```powershell
tqx-cli factor_create --market us --file .\factor.py --name "美股因子"
tqx-cli strategy_create --market us --file .\strategy.py --name "美股策略"
```

Windows PowerShell 5 会移除传给原生命令的源码双引号。必须先转义双引号，再将变量作为一个参数传入：

```powershell
$code = (Get-Content -Raw .\factor.py).Replace('"', '\"')
tqx-cli factor_create --market us --code $code --name "美股因子"

$strategyCode = (Get-Content -Raw .\strategy.py).Replace('"', '\"')
tqx-cli strategy_create --market us --code $strategyCode --name "美股策略"
```

以上写法已在 Windows PowerShell 生产环境验证。多行源码仍优先使用 `--file`。不要使用
`--code "$(.\factor.py)"`，该写法会尝试执行文件；也不要直接使用 `--code "$code"`，否则源码中的
双引号可能丢失。公式以负号开头时可使用：

```powershell
tqx-cli factor_create --market us '--formula=-close/ref(close,5)' --name "反向价格因子"
```

## 状态与错误

CLI 统一状态：

- `SUBMITTED`：已提交，尚未等待结果
- `PENDING`：等待算力
- `RUNNING`：执行中
- `SUCCESS`：QUBE 状态为 `done`
- `FAILED`：执行失败
- `CANCELLED`：任务被取消
- `TIMEOUT`：CLI 等待超时，后台任务未自动取消

常见错误：

| 错误 | 处理 |
|---|---|
| `LOGIN_REQUIRED` | 重新执行 `tqx-cli login` |
| `*_QUERY_FAILED` / `404` | 检查是否使用了正确的 QUBE 整数 ID |
| `409` | 检查运行中的任务、关联仿真盘或重复运行 |
| `422` | 检查市场、日期、代码和参数范围 |
| `TIMEOUT` | 使用对应 `analysis_id/run_id` 查询或停止 |

## 开发测试

```powershell
python -m pytest -q
python cli.py --help
```

接口迁移分析见 [QUBE-CLI接口映射.md](./QUBE-CLI接口映射.md)。
