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

# 示例代码

> AlphaFeed Python SDK 实用代码示例

## 日内 VWAP 均线

计算当日成交量加权平均价（VWAP），常用于日内交易判断买卖点：

```python theme={null}
from alphafeed import AlphaFeed

af = AlphaFeed(api_key="your-api-key")

df = af.klines.intraday("600519.SH", to_dataframe=True)
df["vwap"] = (df["amount"].cumsum() / (df["volume"].cumsum() * 100)).round(2)
print(df[["trade_time", "close", "volume", "vwap"]].tail(5).to_string(index=False))
```

```
         trade_time   close  volume    vwap
2026-06-18 14:56:00 1223.50     273 1221.07
2026-06-18 14:57:00 1223.88     261 1221.08
2026-06-18 14:58:00 1223.26       2 1221.08
2026-06-18 14:59:00 1223.26       0 1221.08
2026-06-18 15:00:00 1215.00    1788 1220.89
```

## MA 均线 + MACD 指标

计算均线和 MACD 技术指标：

```python theme={null}
from alphafeed import AlphaFeed

af = AlphaFeed(api_key="your-api-key")

df = af.klines.get("600519.SH", period="1d", count=60, to_dataframe=True)
df["ma5"] = df["close"].rolling(5).mean().round(2)
df["ma20"] = df["close"].rolling(20).mean().round(2)

ema12 = df["close"].ewm(span=12).mean()
ema26 = df["close"].ewm(span=26).mean()
df["dif"] = (ema12 - ema26).round(2)
df["dea"] = df["dif"].ewm(span=9).mean().round(2)
df["macd"] = ((df["dif"] - df["dea"]) * 2).round(2)

print(df[["trade_date", "close", "ma5", "ma20", "dif", "dea", "macd"]].tail(5).to_string(index=False))
```

```
trade_date   close     ma5    ma20    dif    dea  macd
2026-06-12 1291.91 1273.15 1291.66 -22.42 -25.61  6.38
2026-06-15 1271.10 1274.78 1289.06 -21.83 -24.85  6.04
2026-06-16 1255.67 1274.71 1285.63 -22.33 -24.35  4.04
2026-06-17 1240.00 1267.54 1281.88 -23.71 -24.22  1.02
2026-06-18 1215.00 1254.74 1277.08 -26.49 -24.68 -3.62
```

## 涨跌停检测

通过标的信息获取精确涨跌停价（精度 1e-3），再结合五档盘口确认封板状态：

```python theme={null}
from alphafeed import AlphaFeed

af = AlphaFeed(api_key="your-api-key")

# 1. 获取全 A 行情
quotes_df = af.quotes.get(universes=["CN_Stock"], to_dataframe=True)

# 2. 获取标的信息（含今日涨跌停价，SDK 自动分批）
insts = af.instruments.batch(quotes_df["symbol"].tolist())
inst_map = {x["symbol"]: x for x in insts if x.get("ext", {}).get("limit_up") is not None}

# 3. 价格初筛（允许 1e-3 误差）
def match_limit(row, key):
    inst = inst_map.get(row["symbol"])
    if not inst:
        return False
    price = inst["ext"].get(key)
    return price is not None and abs(row["last_price"] - price) < 1e-3

quotes_df["is_limit_up"] = quotes_df.apply(lambda r: match_limit(r, "limit_up"), axis=1)
quotes_df["is_limit_down"] = quotes_df.apply(lambda r: match_limit(r, "limit_down"), axis=1)

up_candidates = quotes_df[quotes_df["is_limit_up"]]
down_candidates = quotes_df[quotes_df["is_limit_down"]]

# 4. 盘口确认：卖1量为0=涨停封板，买1量为0=跌停封板（SDK 自动分批）
depths_up = af.depth.batch(up_candidates["symbol"].tolist())
confirmed_up = [sym for sym, d in depths_up.items() if d["ask_volumes"][0] == 0]

depths_down = af.depth.batch(down_candidates["symbol"].tolist())
confirmed_down = [sym for sym, d in depths_down.items() if d["bid_volumes"][0] == 0]

up_final = up_candidates[up_candidates["symbol"].isin(confirmed_up)]
down_final = down_candidates[down_candidates["symbol"].isin(confirmed_down)]

print(f"涨停封板: {len(up_final)} 只")
print(up_final[["symbol", "ext.name", "last_price"]].head(5).to_string(index=False))
print(f"\n跌停封板: {len(down_final)} 只")
print(down_final[["symbol", "ext.name", "last_price"]].head(5).to_string(index=False))
```

```
涨停封板: 100 只
   symbol ext.name  last_price
301580.SZ      爱迪特       63.17
002159.SZ     三特索道       14.37
002859.SZ     洁美科技       99.73
000889.SZ     中嘉博创        4.02
603956.SH      威派格        4.98

跌停封板: 34 只
   symbol ext.name  last_price
002323.SZ    *ST雅博        1.30
600539.SH     狮头股份       14.44
002568.SZ     百润股份       16.54
600537.SH    *ST亿晶        2.84
601010.SH     ST文峰        1.47
```

## 批量盘口数据

```python theme={null}
from alphafeed import AlphaFeed

af = AlphaFeed(api_key="your-api-key")

result = af.depth.batch(["000001.SZ", "600000.SH"])
for sym, depth in result.items():
    print(f"--- {sym} ---")
    for i in range(5):
        bid = f"买{i+1}: {depth['bid_prices'][i]:>8.2f} x {depth['bid_volumes'][i]:<6}"
        ask = f"卖{i+1}: {depth['ask_prices'][i]:>8.2f} x {depth['ask_volumes'][i]}"
        print(f"  {bid} | {ask}")
```

```
--- 000001.SZ ---
  买1:    10.52 x 19374  | 卖1:    10.53 x 2
  买2:    10.51 x 16237  | 卖2:    10.54 x 430
  买3:    10.50 x 28122  | 卖3:    10.55 x 75
  买4:    10.49 x 4656   | 卖4:    10.56 x 2771
  买5:    10.48 x 3764   | 卖5:    10.57 x 2566
--- 600000.SH ---
  买1:     9.08 x 4661   | 卖1:     9.09 x 7087
  买2:     9.07 x 5576   | 卖2:     9.10 x 1052
  买3:     9.06 x 6301   | 卖3:     9.11 x 2108
  买4:     9.05 x 10340  | 卖4:     9.12 x 1537
  买5:     9.04 x 1074   | 卖5:     9.13 x 3112
```

## 多标的日内分时对比

```python theme={null}
from alphafeed import AlphaFeed

af = AlphaFeed(api_key="your-api-key")

dfs = af.klines.intraday_batch(["600519.SH", "000001.SZ"], to_dataframe=True)
for sym, df in dfs.items():
    print(f"{sym} ({df['name'].iloc[0]}): {len(df)} 条分钟线")
```

```
600519.SH (贵州茅台): 241 条分钟线
000001.SZ (平安银行): 241 条分钟线
```
