> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reportify.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 计算因子数据

> 计算指定股票的因子数据

计算指定股票的因子数据，支持技术因子和基本面因子，公式使用麦语言语法（兼容通达信/同花顺）。

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.reportify.cn/v1/quant/factors/compute \
    -H "Authorization: Bearer <token>" \
    -H "Content-Type: application/json" \
    -d '{
      "market": "cn",
      "symbols": ["000001", "000002"],
      "formula": "RSI(14)",
      "start_date": "2026-01-01",
      "end_date": "2026-01-10"
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.reportify.cn/v1/quant/factors/compute",
      headers={"Authorization": "Bearer <token>"},
      json={
          "market": "cn",
          "symbols": ["000001", "000002"],
          "formula": "RSI(14)",
          "start_date": "2026-01-01",
          "end_date": "2026-01-10"
      }
  )
  print(response.json())
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch('https://api.reportify.cn/v1/quant/factors/compute', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer <token>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      market: 'cn',
      symbols: ['000001', '000002'],
      formula: 'RSI(14)',
      start_date: '2026-01-01',
      end_date: '2026-01-10'
    })
  });
  ```
</CodeGroup>

## 请求参数

<ParamField body="market" type="string" default="cn">
  股票市场：`cn`（A股）, `hk`（港股）, `us`（美股）
</ParamField>

<ParamField body="symbols" type="string[]" required>
  股票代码列表
</ParamField>

<ParamField body="formula" type="string" required>
  因子公式
</ParamField>

<ParamField body="start_date" type="string">
  开始日期，格式：`YYYY-MM-DD`（默认：3 个月前）
</ParamField>

<ParamField body="end_date" type="string">
  结束日期，格式：`YYYY-MM-DD`（默认：今天）
</ParamField>

## 公式示例

### 技术因子

| 公式                                              | 类型 | 描述           |
| ----------------------------------------------- | -- | ------------ |
| `RSI(14)`                                       | 数值 | RSI 指标值      |
| `MACD().dif`                                    | 数值 | MACD DIF 线   |
| `CLOSE > MA(CLOSE, 20)`                         | 布尔 | 收盘价高于 20 日均线 |
| `(CLOSE - MA(CLOSE, 20)) / MA(CLOSE, 20) * 100` | 数值 | 偏离 MA20 的百分比 |

### 基本面因子

| 公式                          | 类型 | 描述          |
| --------------------------- | -- | ----------- |
| `PE()`                      | 数值 | 市盈率         |
| `PE_TTM()`                  | 数值 | 市盈率（TTM）    |
| `PB()`                      | 数值 | 市净率         |
| `ROE()`                     | 数值 | 净资产收益率      |
| `ROA()`                     | 数值 | 总资产收益率      |
| `INCOME.net_profit`         | 数值 | 利润表 - 净利润   |
| `BALANCESHEET.total_assets` | 数值 | 资产负债表 - 总资产 |
| `PE() < 20`                 | 布尔 | 市盈率小于 20    |
| `ROE() > 0.15`              | 布尔 | ROE 大于 15%  |

## 运算符

| 类型  | 运算符                              | 示例                                              |
| --- | -------------------------------- | ----------------------------------------------- |
| 比较  | `>`, `<`, `>=`, `<=`, `==`, `!=` | `CLOSE > MA(CLOSE, 20)`                         |
| 逻辑与 | `&` 或 `AND`                      | `(RSI(14) < 30) & (CLOSE > MA(CLOSE, 20))`      |
| 逻辑或 | `\|` 或 `OR`                      | `(RSI(14) < 30) \| (RSI(14) > 70)`              |
| 逻辑非 | `~` 或 `NOT`                      | `NOT (CLOSE > MA(CLOSE, 20))`                   |
| 算术  | `+`, `-`, `*`, `/`               | `(CLOSE - MA(CLOSE, 20)) / MA(CLOSE, 20) * 100` |

## 支持的变量

| 变量       | 别名         | 描述  |
| -------- | ---------- | --- |
| `CLOSE`  | `C`        | 收盘价 |
| `OPEN`   | `O`        | 开盘价 |
| `HIGH`   | `H`        | 最高价 |
| `LOW`    | `L`        | 最低价 |
| `VOLUME` | `V`, `VOL` | 成交量 |
| `AMOUNT` | -          | 成交额 |

## 支持的函数

| 级别          | 函数                                                                                  |
| ----------- | ----------------------------------------------------------------------------------- |
| Level 0     | `MA`, `EMA`, `SMA`, `REF`, `HHV`, `LLV`, `STD`, `SUM`, `ABS`, `MAX`, `MIN`, `IF`... |
| Level 1     | `CROSS`, `CROSSDOWN`, `COUNT`, `EVERY`, `EXIST`, `BARSLAST`...                      |
| Level 2 技术  | `RSI`, `MACD`, `BOLL`, `KDJ`, `WR`, `ATR`, `CCI`, `BIAS`, `PSY`...                  |
| Level 2 基本面 | `PE()`, `PB()`, `PS()`, `ROE()`, `ROA()`, `EPS()`, `BPS()`, `CURRENT_RATIO()`...    |

## 响应参数

<ResponseField name="datas" type="array">
  因子数据列表，包含 symbol、date 和因子值
</ResponseField>

<ResponseField name="metadata" type="object">
  计算元数据
</ResponseField>

## 响应示例

### 数值因子

```json theme={null}
{
  "datas": [
    {
      "symbol": "000001",
      "date": "2026-01-10",
      "value": 58.32
    },
    {
      "symbol": "000001",
      "date": "2026-01-09",
      "value": 56.78
    }
  ],
  "metadata": {
    "formula": "RSI(14)",
    "market": "cn",
    "count": 2
  }
}
```

### 布尔因子

```json theme={null}
{
  "datas": [
    {
      "symbol": "000001",
      "date": "2026-01-10",
      "value": true
    },
    {
      "symbol": "000002",
      "date": "2026-01-10",
      "value": false
    }
  ],
  "metadata": {
    "formula": "CLOSE > MA(CLOSE, 20)",
    "market": "cn",
    "count": 2
  }
}
```

### 基本面因子

```json theme={null}
{
  "datas": [
    {
      "symbol": "000001",
      "date": "2026-01-10",
      "value": 8.52
    },
    {
      "symbol": "600519",
      "date": "2026-01-10",
      "value": 28.65
    }
  ],
  "metadata": {
    "formula": "PE_TTM()",
    "market": "cn",
    "count": 2
  }
}
```

### MACD DIF 线

```json theme={null}
{
  "datas": [
    {
      "symbol": "000001",
      "date": "2026-01-10",
      "value": 0.125
    },
    {
      "symbol": "000001",
      "date": "2026-01-09",
      "value": 0.118
    }
  ],
  "metadata": {
    "formula": "MACD().dif",
    "market": "cn",
    "count": 2
  }
}
```


## OpenAPI

````yaml POST /v1/quant/factors/compute
openapi: 3.1.0
info:
  title: Reportify API
  version: 1.0.0
  description: API documentation for Reportify's document management and search services.
servers:
  - url: https://api.reportify.cn
    description: Production server
security:
  - BearerAuth: []
paths:
  /v1/quant/factors/compute:
    post:
      tags:
        - openapi-quant
      summary: Compute factor values
      description: >
        Compute factor values for given symbols and date range.


        The formula uses Mai-language syntax compatible with
        TongDaXin/TongHuaShun.


        **Variables vs Functions:**

        - Variables (no parentheses): `CLOSE`, `OPEN`, `HIGH`, `LOW`, `VOLUME`,
        `AMOUNT` (aliases: `C`, `O`, `H`, `L`, `V`, `VOL`)

        - Functions (with parentheses): `MA(CLOSE, 20)`, `RSI(14)`, `PE()`,
        `ROE()`, etc.

        - Rule: Technical indicators and fundamental factors are functions, need
        `()`


        **Technical Factor Examples:**

        - `RSI(14)` - RSI indicator with period 14

        - `MACD().dif` - MACD DIF line

        - `CLOSE > MA(CLOSE, 20)` - Close above 20-day MA (boolean)

        - `(CLOSE - MA(CLOSE, 20)) / MA(CLOSE, 20) * 100` - Deviation from MA20
        in percent


        **Fundamental Factor Examples (all need parentheses):**

        - `PE()` - Price to Earnings ratio

        - `PE_TTM()` - P/E ratio (TTM)

        - `PB()` - Price to Book ratio

        - `ROE()` - Return on Equity

        - `ROA()` - Return on Assets

        - `INCOME.net_profit` - Net profit from income statement (data accessor)

        - `BALANCESHEET.total_assets` - Total assets from balance sheet (data
        accessor)

        - `PE() < 20` - Stocks with P/E less than 20

        - `ROE() > 0.15` - Stocks with ROE greater than 15%


        **Supported Operators:**

        - Comparison: `>`, `<`, `>=`, `<=`, `==`, `!=`

        - Logical: `&` or `AND`, `|` or `OR`, `~` or `NOT` (case-insensitive)

        - Arithmetic: `+`, `-`, `*`, `/`

        - **Important: expressions on both sides of logical operators
        (`&`/`|`/`AND`/`OR`) must be wrapped in parentheses `()`**


        **Supported Variables (no parentheses):**

        - `CLOSE`, `C` - Close price

        - `OPEN`, `O` - Open price

        - `HIGH`, `H` - High price

        - `LOW`, `L` - Low price

        - `VOLUME`, `V`, `VOL` - Volume

        - `AMOUNT` - Amount




        **Supported Functions (TongDaXin style: col first, n second):**

        - Level 0: MA(col, n), EMA(col, n), SMA(col, n, m), REF(col, n),
        HHV(col, n), LLV(col, n), STD(col, n), SUM(col, n), ABS(), MAX(), MIN(),
        IF()...

        - Level 1: CROSS(), CROSSDOWN(), COUNT(), EVERY(), EXIST(),
        BARSLAST()...

        - Level 2 Technical: RSI(), MACD(), BOLL(), KDJ(), WR(), ATR(), CCI(),
        BIAS(), PSY()...

        - Level 2 Fundamental: PE(), PB(), PS(), ROE(), ROA(), EPS(), BPS(),
        CURRENT_RATIO()...
      operationId: factors_compute
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FactorComputeInput'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FactorComputeOutput'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - BearerAuth: []
components:
  schemas:
    FactorComputeInput:
      type: object
      required:
        - symbols
        - formula
      properties:
        market:
          $ref: '#/components/schemas/StockMarket'
          description: Stock market
          default: cn
        symbols:
          type: array
          title: Symbols
          description: Stock code list, e.g., ["600519", "000001"] for CN market (required)
          items:
            type: string
        formula:
          type: string
          title: Formula
          description: Factor formula (required)
        start_date:
          anyOf:
            - type: string
              format: date
            - type: 'null'
          title: Start Date
          description: 'Start date (optional, default: 3 months ago)'
        end_date:
          anyOf:
            - type: string
              format: date
            - type: 'null'
          title: End Date
          description: 'End date (optional, default: today)'
      title: FactorComputeInput
      description: Input for factor computation.
    FactorComputeOutput:
      type: object
      required:
        - datas
        - metadata
      properties:
        datas:
          type: array
          title: Datas
          description: >-
            Factor data list with symbol, date, name, close, factor_value, and
            indicators
          items:
            type: object
            required:
              - date
              - symbol
            properties:
              date:
                type: string
                format: date
                description: Data date
              symbol:
                type: string
                description: Stock code
              name:
                type: string
                description: Stock name (Chinese)
              name_en:
                type: string
                description: Stock name (English)
              close:
                type: number
                description: Close price
              factor_value:
                anyOf:
                  - type: number
                  - type: boolean
                  - type: 'null'
                description: Main formula result value
              indicators:
                type: object
                additionalProperties: true
                description: Intermediate indicator values from formula
        metadata:
          type: object
          required:
            - formula
            - start_date
            - end_date
            - total_rows
            - fields
            - indicators
          properties:
            formula:
              type: string
              description: The formula used
            start_date:
              type: string
              format: date
              description: Start date
            end_date:
              type: string
              format: date
              description: End date
            total_rows:
              type: integer
              description: Total number of rows
            fields:
              type: array
              items:
                type: string
              description: List of output field names
            indicators:
              type: array
              items:
                type: string
              description: List of indicator formulas
      title: FactorComputeOutput
      description: Output for factor computation.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    StockMarket:
      type: string
      enum:
        - cn
        - hk
        - us
        - global
      title: StockMarket
      description: Stock market identifier
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: Enter your Bearer token

````