转自: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)