通达信LC1文件结构解析指南

文件结构解析

  1. 文件头(32字节)

    • 前4字节:文件标识(固定为0x0E
    • 后续28字节:保留字段(通常为0x00
  2. K线记录(每笔40字节)

    • 时间戳(4字节):小端序整型,需转换为时间格式
    • 开盘价(4字节):小端序浮点数
    • 最高价(4字节):小端序浮点数
    • 最低价(4字节):小端序浮点数
    • 收盘价(4字节):小端序浮点数
    • 成交量(4字节):小端序整型
    • 成交额(8字节):小端序双精度浮点数
    • 预留字段(8字节)

Python解析代码

python 复制代码
import struct
import datetime

def read_lc1_file(file_path):
    data = []
    with open(file_path, 'rb') as f:
        # 跳过文件头
        f.read(32)
        
        # 逐条读取K线记录
        while True:
            chunk = f.read(40)
            if not chunk:
                break
            
            # 解析二进制数据
            timestamp, open_price, high, low, close, volume, turnover, _ = struct.unpack('<Iffffd8x', chunk)
            
            # 转换时间戳(通达信时间戳为自1990-01-01的秒数)
            dt = datetime.datetime(1990, 1, 1) + datetime.timedelta(seconds=timestamp)
            
            data.append({
                'datetime': dt,
                'open': open_price,
                'high': high,
                'low': low,
                'close': close,
                'volume': int(volume),
                'turnover': turnover
            })
    return data

# 示例调用
kline_data = read_lc1_file('path/to/data.lc1')

关键说明

  1. 字节序 :所有字段均为小端序<符号在struct.unpack中指定)
  2. 时间戳转换: $$ \text{时间} = \text{1990-01-01} + \text{时间戳(秒)} $$
  3. 精度处理:成交量需转为整数(原始数据为浮点存储的整数)

输出数据结构

返回结果为字典列表,每条记录包含:

python 复制代码
{
    'datetime': datetime.datetime(2023, 5, 17, 10, 30),  # 时间
    'open': 15.23,  # 开盘价
    'high': 15.45,  # 最高价
    'low': 15.20,   # 最低价
    'close': 15.40, # 收盘价
    'volume': 51200, # 成交量(手)
    'turnover': 785920.0  # 成交额(元)
}

注意事项

  • 不同版本的通达信可能存在细微格式差异,建议先验证文件头标识。
  • 成交额字段(turnover)为双精度浮点数,可精确表示较大数值。
相关推荐
花酒锄作田11 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪15 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽16 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战16 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama