下面的代碼應該做的伎倆。首先,它打開一個文件並在lzma中解碼它,然後使用struct解包二進制數據。
import lzma
import struct
import pandas as pd
def bi5_to_df(filename, fmt):
chunk_size = struct.calcsize(fmt)
data = []
with lzma.open(filename) as f:
while True:
chunk = f.read(chunk_size)
if chunk:
data.append(struct.unpack(fmt, chunk))
else:
break
df = pd.DataFrame(data)
return df
最重要的是要知道正確的格式。我搜索了一下,並試圖猜測和'>3i2f'
(或>3I2f
)作品相當不錯。 (這是一個大的endian 3 ints 2浮點數,你的建議是:'i4f'
不會產生明智的浮點數 - 不管是大的還是小的endian。)對於struct
和格式語法,請參閱docs。
df = bi5_to_df('13h_ticks.bi5', '>3i2f')
df.head()
Out[177]:
0 1 2 3 4
0 210 110218 110216 1.87 1.12
1 362 110219 110216 1.00 5.85
2 875 110220 110217 1.00 1.12
3 1408 110220 110218 1.50 1.00
4 1884 110221 110219 3.94 1.00
更新
向bi5_to_df
的輸出與https://github.com/ninety47/dukascopy, 我編譯比較,並從那裏運行test_read_bi5
。輸出的第一行是:
time, bid, bid_vol, ask, ask_vol
2012-Dec-03 01:00:03.581000, 131.945, 1.5, 131.966, 1.5
2012-Dec-03 01:00:05.142000, 131.943, 1.5, 131.964, 1.5
2012-Dec-03 01:00:05.202000, 131.943, 1.5, 131.964, 2.25
2012-Dec-03 01:00:05.321000, 131.944, 1.5, 131.964, 1.5
2012-Dec-03 01:00:05.441000, 131.944, 1.5, 131.964, 1.5
而且bi5_to_df
相同的輸入文件提供:
bi5_to_df('01h_ticks.bi5', '>3I2f').head()
Out[295]:
0 1 2 3 4
0 3581 131966 131945 1.50 1.5
1 5142 131964 131943 1.50 1.5
2 5202 131964 131943 2.25 1.5
3 5321 131964 131944 1.50 1.5
4 5441 131964 131944 1.50 1.5
所以一切都似乎是罰款(ninety47的代碼重新排序列)。
此外,使用'>3I2f'
而不是'>3i2f'
(即unsigned int
而不是int
)可能更準確。
你知道原始數據的格式嗎?例如:每行中有(int,int,int,float,float)? – ptrj
32位整數:自紀元以來的毫秒數,32位浮點數:賣價,32位浮點數:買價,32位浮點數:詢價量,32位浮點數:出價量。這個任務專門有一個C++庫,但我需要從Python開始工作。你可以在https://github看看它。com/ninety47/dukascopy – ajsp
Python 2.7即是。 – ajsp