Skip to content

Instantly share code, notes, and snippets.

@paduel
Created July 4, 2019 15:11
Show Gist options
  • Save paduel/44513e5373ad88ec1d7b71e03bd90603 to your computer and use it in GitHub Desktop.
Save paduel/44513e5373ad88ec1d7b71e03bd90603 to your computer and use it in GitHub Desktop.
Importar archivos .hst de Metatrader en Python
def read_hst(filename):
from pandas import DataFrame, to_datetime
from struct import unpack, calcsize, iter_unpack
bint = open(filename, 'rb').read()
head = unpack('<i64s12siiii', bint[:96])
version = head[0]
symbol = head[2].decode("utf-8").split('\x00')[0]
start = 148
if version == 401:
fmt = '<qddddqfq'
columns = ['datetime', 'open', 'high', 'low',
'close', 'volume', 'spread', 'real_volume']
elif version == 400:
fmt = '<iddddd'
columns = ['datetime', 'open', 'high', 'low', 'close', 'volume']
else:
print('El archivo no es una versión conocida de hst de MetaTrader')
return
size = calcsize(fmt)
df = DataFrame.from_records([bar for bar in iter_unpack(fmt, bint[start:])],
columns=columns,
index='datetime')
df.name = symbol
df.index = to_datetime(df.index, unit='s')
return df
@paduel
Copy link
Author

paduel commented Jul 4, 2019

La función debe incluirse en un Jupyter notebook o bien en el código de un script de Python 3.X.

Para usarlo pasar a la función el nombre (ruta) del fichero .hst, por ejemplo:

df = read_hst('NZDUSD1440.hst')

y la variable df recibirá un dataframe de Pandas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment