分享

通达信格式及python读取 | Yu Pengyan's Blog

 imelee 2017-09-11

2016-9-3 使用Yahoo的接口也能够获取到数据 https://github.com/lukaszbanasiak/yahoo-finance

通达信网站为券商系统提供交易数据下载,如:上证所有证券日线shlday.zip,深证所有证券日线szlday.zip。shlday.zip下载加压后会得到sh000001.day、sh000002.day等312个独立的数据文件,sh000001.day代表了上证股票000001的所有日线数据。

1.日线数据格式

1-4字节 Date:LongInt; //日期
5-8字节 OPen:LongInt; //开盘*100(元)
9-12字节 High:LongInt; //最高价*100(元)
13-16字节 Low:LongInt; //最低价*100(元)
17-20字节 Close:LongInt; //收盘*100(元)
21-24字节 Amount;//成交额
25-28字节 Volume:LongInt; //Volume 成交量(股)
29-32字节 // Reserved 保留值

2.python程序

本程序代码将给定日线数据文件内容输出到csv文件以供后续程序分析用。

2.1.代码

# -*- coding:utf-8 -*-
import os
import os.path
import struct
import time,datetime
time_original='17/Sep/2012:11:40:00'
time_format=datetime.datetime.strptime(time_original,'%d/%b/%Y:%H:%M:%S')

def stockOutput(path):
    file_object = open('D:\dev\data.csv', 'w+')
    with open(path,"rb") as f:
        while True:
            stock_date = f.read(4)
            stock_open = f.read(4)
            stock_high = f.read(4)
            stock_low= f.read(4)
            stock_close = f.read(4)
            stock_amount = f.read(4)
            stock_vol = f.read(4)
            stock_reservation = f.read(4)

            # date,open,high,low,close,amount,vol,reservation
            if not stock_date:
                break
            stock_date = struct.unpack("l", stock_date)  # 4字节   如20091229
            stock_open = struct.unpack("l", stock_open) #开盘价
            stock_high = struct.unpack("l", stock_high) #最高价
            stock_low= struct.unpack("l", stock_low) #最低价
            stock_close = struct.unpack("l", stock_close) #收盘价
            stock_amount = struct.unpack("l", stock_amount) #成交额
            stock_vol = struct.unpack("l", stock_vol) #成交量
            stock_reservation = struct.unpack("l", stock_reservation) #保留值


            # print "PROCESS:", stock_date[0],stock_open,stock_high,stock_low,stock_close,stock_amount,stock_vol,stock_reservation
            #print "PROCESS:", stock_date[0],stock_close[0]
            date_format=datetime.datetime.strptime(str(stock_date[0]),'%Y%M%d')
            list= "CYBZ,"+date_format.strftime('%Y-%M-%d')+",,"+str(stock_open[0])+","+str(stock_high[0])+","+str(stock_low[0])+","+str(stock_close[0])+","+str(stock_vol[0])+"\r\n"#,stock_high[0],stock_low[0],stock_close[0],stock_vol[0]
            #[股票代码0,日期1,开盘价2,最高价3,最低价4,收盘价5,成交量6]
            file_object.writelines(list)
            #file_object.truncate()
    file_object.close()

stockOutput("D:\\projects\\data\\tdx\\szlday\\sz399006.day")

2.2.说明

  1. 函数 open(path,”rb”) 参数’rb’ 指定只读二进制打开
  2. struct.unpack(“l”, stock_date) 将二进制数据解码为integer类型

3.参考:

  1. 通达信数据格式:http://blog.163.com/da7_1@126/blog/static/1040726782012017856371/
  2. Python使用struct处理二进制:http://www.cnblogs.com/gala/archive/2011/09/22/2184801.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多