[python]解析通达信盘后数据获取历史日线数据

转自:http://bbs.pinggu.org/forum.php?mod=viewthread&tid=4804415&page=1

平时我们在做 离线的模型 回溯测试时候,需要历史的k线数据。
可是通达信 的日线数据如下:
日线数据在

通达信的安装目录: vipdoc\sh\lday 下面

本地的通达信 是没有开放api和外部的 自己的交易回溯测试 工具或框架 进行交互的。

虽然 我们也可以 通过 sina 的api ,或者 yahoo,或者 juhe聚合数据,或者 wind 或者 tushare (http://tushare.org/index.html),或者 通联金融大数据 等 网络的api接口 获取 股票的 历史K线数据, 但是网络的开销总是会比较耗时一些。

其实可以通过 Python来 解析 通达信 的这些 day 文件的数据,变成 我们熟悉的csv格式的数据。

#!/usr/bin/python    
def exactStock(fileName, code):  
    ofile = open(fileName,'rb')  
    buf=ofile.read()  
    ofile.close()  
    num=len(buf)  
    no=num/32  
    b=0  
    e=32  
    items = list()   
    for i in range(int(no)):  
        a=unpack('IIIIIfII',buf[b:e])  
        year = int(a[0]/10000);  
        m = int((a[0]%10000)/100);  
        month = str(m);  
        if m <10 :  
            month = "0" + month;  
        d = (a[0]%10000)%100;  
        day=str(d);  
        if d< 10 :  
            day = "0" + str(d);  
        dd = str(year)+"-"+month+"-"+day  
        openPrice = a[1]/100.0  
        high = a[2]/100.0  
        low =  a[3]/100.0  
        close = a[4]/100.0  
        amount = a[5]/10.0  
        vol = a[6]  
        unused = a[7]  
        if i == 0 :  
            preClose = close  
        ratio = round((close - preClose)/preClose*100, 2)  
        preClose = close  
        item=[code, dd, str(openPrice), str(high), str(low), str(close), str(ratio), str(amount), str(vol)]  
        items.append(item)  
        b=b+32  
        e=e+32  

    return items  

exactStock('E:\\new_tdx\\vipdoc\\sh\\lday\\sh000001.day',"000001") 

然后调用 这个方法,就可以把day文件变成csv文件,方便pandas来处理。

(在调用这个py文件前, 先在通达信的 软件 菜单里面 ,把通达信的 历史日K线数据都下载到本地,一次即可下载整个市场所有股票品种的数据。。)

批量处理的,请参考下面脚本
这里写图片描述
调用示例:
pathdir=’/vipdoc/sh/lday’
targetDir=’/python_data_gupiao/sh/lday’
listfile=os.listdir(pathdir)
for f in listfile:
day2csv_data(pathdir,f,targetDir)

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值