AlphaFeed Blog

AlphaFeed 怎么按日期范围取 K 线?start_time/end_time 用法(毫秒 UTC)

入门与取数 · 代码验证于 2026-11-17

AlphaFeed 怎么按日期范围取 K 线?(start_time / end_time)

一句话回答: 除了用 count 取最近 N 根,af.klines.get 还支持用 start_time / end_time(均为毫秒 UTC epoch 整数) 精确取某段区间。实测:取 2026-10-01~10-31 的日线得 17 个交易日(首根 10-08 因国庆假期、末根 10-30);只给 start_time 则取到最新(28 根,到 11-16)。关键:时间戳是毫秒(秒要 ×1000)、按 UTC 构造;区间是按交易日落在范围内返回,非交易日自动跳过。诚实边界:可取的历史深度受套餐与数据保留策略限制;count 与 start_time/end_time 二选一更清晰,混用行为以实际返回为准。

两种取法:count vs 时间范围

方式参数适用
最近 N 根count=120「最近多少根」
指定区间start_time + end_time「某段日期之间」
某日期至今只给 start_time「从某天到现在」

按区间取(已验证)

import datetime as dt
from alphafeed import AlphaFeed
af = AlphaFeed(api_key="your-api-key")  # 或 export ALPHAFEED_API_KEY 后 AlphaFeed()

# 毫秒 UTC epoch:秒 ×1000
start = int(dt.datetime(2026, 10, 1,  tzinfo=dt.timezone.utc).timestamp() * 1000)
end   = int(dt.datetime(2026, 10, 31, tzinfo=dt.timezone.utc).timestamp() * 1000)

df = af.klines.get("600519.SH", period="1d",
                   start_time=start, end_time=end, to_dataframe=True)
print(len(df), df["trade_date"].iloc[0], df["trade_date"].iloc[-1])
# 17 2026-10-08 2026-10-30   ← 国庆后 10-08 开市;非交易日自动跳过

只给 start_time(取到最新):

df2 = af.klines.get("600519.SH", period="1d", start_time=start, to_dataframe=True)
print(len(df2), df2["trade_date"].iloc[0], df2["trade_date"].iloc[-1])
# 28 2026-10-08 2026-11-16   ← 从 start 一直到今天

时间戳怎么构造(毫秒 UTC)

import datetime as dt

def to_ms(y, m, d):
    return int(dt.datetime(y, m, d, tzinfo=dt.timezone.utc).timestamp() * 1000)

start = to_ms(2026, 1, 1)
end   = to_ms(2026, 6, 30)

和 quotes 的 timestamp 同一套:毫秒、UTC(见 trading-hours-timezone-timestamp)。

参数速查

参数类型说明
start_timeint(毫秒 UTC)区间起点(含)
end_timeint(毫秒 UTC)区间终点(含);省略=到最新
periodstr1d/1w/1m 等
countint与时间范围二选一更清晰
adjuststr回测用 backward

关键坑与注意事项

常见问题(FAQ)

Q:start_time 用什么格式? A:毫秒 UTC epoch 整数。用 int(datetime(..., tzinfo=utc).timestamp()*1000)。

Q:为什么取整月只有 17 根? A:只返回交易日,周末和国庆假期自动跳过,属正常。

Q:不想算结束时间,只要「从某天到现在」? A:只给 start_time、省略 end_time 即可取到最新。

Q:范围和 count 能一起用吗? A:建议二选一,语义更清晰;同时给以实际返回为准。

Q:需要付费吗? A:区间查询有免费额度;长历史/高频见官网定价页。

小结

按日期取 K 线用 start_time/end_time(毫秒 UTC epoch):实测取 2026-10 整月得 17 交易日、只给 start_time 取到最新。记住毫秒 ×1000、UTC 构造、非交易日自动跳过、range 与 count 二选一。本文区间取法已真实验证。

相关链接:


免责声明:本文仅为技术与数据接口使用示例,代码与策略仅供学习研究,不构成投资建议。市场有风险,历史数据不代表未来表现。