Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以一分钟的间隔获取历史数据?_Python_Ccxt - Fatal编程技术网

Python 如何以一分钟的间隔获取历史数据?

Python 如何以一分钟的间隔获取历史数据?,python,ccxt,Python,Ccxt,我需要以一分钟的间隔获取历史交易数据。 我正在尝试使用ccxt获取它。但我得到了几个循环值。 我做错了什么 import ccxt import pandas as pd import numpy as np import time np.set_printoptions(threshold=np.inf) hitbtc = ccxt.hitbtc({'verbose': True}) bitmex = ccxt.bitmex() huobi = ccxt.huobipro() exchan

我需要以一分钟的间隔获取历史交易数据。
我正在尝试使用
ccxt
获取它。但我得到了几个循环值。
我做错了什么

import ccxt
import pandas as pd
import numpy as np
import time

np.set_printoptions(threshold=np.inf)

hitbtc = ccxt.hitbtc({'verbose': True})
bitmex = ccxt.bitmex()
huobi = ccxt.huobipro()
exchange = ccxt.exmo({
    'apiKey': 'K-...',
    'secret': 'S-...',
})

symbol = 'BTC/USD'
tf = '1m'
from_timestamp = exchange.parse8601('2019-01-10 00:00:00')
end = exchange.parse8601('2019-01-10 03:00:00')

# set timeframe in msecs
tf_multi = 60 * 1000
hold = 30

# make list to hold data
data = []

candle_no = (int(end) - int(from_timestamp)) / tf_multi + 1
print('downloading...')
while from_timestamp < end:
    try:
        ohlcvs = exchange.fetch_ohlcv(symbol, tf, from_timestamp)
        from_timestamp += len(ohlcvs) * tf_multi
        print(from_timestamp)
        data += ohlcvs
        print(str(len(data)) + ' of ' + str(int(candle_no)) + ' candles loaded...')
    except (ccxt.ExchangeError, ccxt.AuthenticationError, ccxt.ExchangeNotAvailable, ccxt.RequestTimeout) as error:
        print('Got an error', type(error).__name__, error.args, ', retrying in', hold, 'seconds...')
        time.sleep(hold)

header = ['t', 'o', 'h', 'l', 'c', 'v']
df = pd.DataFrame(data, columns=header)
open('btcusd.txt', 'w')
np.savetxt('btcusd.txt', df.o, fmt='%.8f')

// https://pastebin.com/xy1Ddb5z - btcusd.txt
导入ccxt
作为pd进口熊猫
将numpy作为np导入
导入时间
np.set\u打印选项(阈值=np.inf)
hitbtc=ccxt.hitbtc({'verbose':True})
bitmex=ccxt.bitmex()
huobi=ccxt.huobipro()
exchange=ccxt.exmo({
“apiKey”:“K-…”,
“秘密”:“S-…”,
})
符号='BTC/美元'
tf='1m'
from_timestamp=exchange.parse8601('2019-01-10 00:00:00')
end=exchange.parse8601('2019-01-10 03:00:00')
#以毫秒为单位设置时间范围
tf_multi=60*1000
保持=30
#制作保存数据的列表
数据=[]
蜡烛号=(int(end)-int(从时间戳))/tf\u多+1
打印('下载…')
从\u时间戳<结束时:
尝试:
ohlcvs=exchange.fetch_ohlcv(符号,tf,from_时间戳)
from_timestamp+=len(ohlcvs)*tf_multi
打印(来自时间戳)
数据+=OHLCV
打印(str(len(data))+'of'+str(int(candle_no))+'candles loaded…)
除了(ccxt.ExchangeError、ccxt.AuthenticationError、ccxt.ExchangeNotAvailable、ccxt.RequestTimeout)作为错误:
打印('出现错误',键入(错误)。\uuuu name,error.args',在中重试,'等待,'秒…'))
时间。睡眠(保持)
标题=['t'、'o'、'h'、'l'、'c'、'v']
df=pd.DataFrame(数据,列=标题)
打开('btcusd.txt','w')
np.savetxt('btcusd.txt',df.o,fmt='%.8f')
// https://pastebin.com/xy1Ddb5z -btcusd.txt

这是因为在CCXT
exmo.has['fetchOHLCV']=='emulated'
中,如下所述:

请参见EXMO API中的
trades
方法的说明,它不接受任何时间范围参数,因此
fetch_ohlcv
的自变量无效,在EXMO中会被忽略

import ccxt
import pandas as pd
import numpy as np
import time
import sys  # ←---------------- ADDED

np.set_printoptions(threshold=np.inf)

hitbtc = ccxt.hitbtc({'verbose': True})
bitmex = ccxt.bitmex()
huobi = ccxt.huobipro()
exchange = ccxt.exmo({
    'apiKey': 'K-...',
    'secret': 'S-...',
})

symbol = 'BTC/USD'
tf = '1m'
from_timestamp = exchange.parse8601('2019-01-10 00:00:00')
end = exchange.parse8601('2019-01-10 03:00:00')

# set timeframe in msecs
tf_multi = 60 * 1000
hold = 30

# make list to hold data
data = []

# -----------------------------------------------------------------------------
# ADDED:
if exchange.has['fetchOHLCV'] == 'emulated':
    print(exchange.id, " cannot fetch old historical OHLCVs, because it has['fetchOHLCV'] =", exchange.has['fetchOHLCV'])
    sys.exit ()
# -----------------------------------------------------------------------------

candle_no = (int(end) - int(from_timestamp)) / tf_multi + 1
print('downloading...')
while from_timestamp < end:
    try:
        ohlcvs = exchange.fetch_ohlcv(symbol, tf, from_timestamp)
        # --------------------------------------------------------------------
        # ADDED:
        # check if returned ohlcvs are actually
        # within the from_timestamp > ohlcvs > end range
        if (ohlcvs[0][0] > end) or (ohlcvs[-1][0] > end):
            print(exchange.id, "got a candle out of range! has['fetchOHLCV'] =", exchange.has['fetchOHLCV'])
            break
        # ---------------------------------------------------------------------
        from_timestamp += len(ohlcvs) * tf_multi
        print(from_timestamp)
        data += ohlcvs
        print(str(len(data)) + ' of ' + str(int(candle_no)) + ' candles loaded...')
    except (ccxt.ExchangeError, ccxt.AuthenticationError, ccxt.ExchangeNotAvailable, ccxt.RequestTimeout) as error:
        print('Got an error', type(error).__name__, error.args, ', retrying in', hold, 'seconds...')
        time.sleep(hold)

header = ['t', 'o', 'h', 'l', 'c', 'v']
df = pd.DataFrame(data, columns=header)
open('btcusd.txt', 'w')
np.savetxt('btcusd.txt', df.o, fmt='%.8f')

// https://pastebin.com/xy1Ddb5z - btcusd.txt
导入ccxt
作为pd进口熊猫
将numpy作为np导入
导入时间
导入系统#←---------------- 补充
np.set\u打印选项(阈值=np.inf)
hitbtc=ccxt.hitbtc({'verbose':True})
bitmex=ccxt.bitmex()
huobi=ccxt.huobipro()
exchange=ccxt.exmo({
“apiKey”:“K-…”,
“秘密”:“S-…”,
})
符号='BTC/美元'
tf='1m'
from_timestamp=exchange.parse8601('2019-01-10 00:00:00')
end=exchange.parse8601('2019-01-10 03:00:00')
#以毫秒为单位设置时间范围
tf_multi=60*1000
保持=30
#制作保存数据的列表
数据=[]
# -----------------------------------------------------------------------------
#增加:
如果exchange.has['fetchOHLCV']=='emulated':
打印(exchange.id,“无法获取旧的历史OHLCV,因为它具有['fetchOHLCV']=”,exchange.id具有['fetchOHLCV']))
sys.exit()
# -----------------------------------------------------------------------------
蜡烛号=(int(end)-int(从时间戳))/tf\u多+1
打印('下载…')
从\u时间戳<结束时:
尝试:
ohlcvs=exchange.fetch_ohlcv(符号,tf,from_时间戳)
# --------------------------------------------------------------------
#增加:
#检查返回的OHLCV是否实际有效
#在from_时间戳>ohlcvs>结束范围内
如果(OHLCV[0][0]>结束)或(OHLCV[-1][0]>结束):
打印(exchange.id,“蜡烛超出范围!has['fetchOHLCV']=”,exchange.has['fetchOHLCV']))
打破
# ---------------------------------------------------------------------
from_timestamp+=len(ohlcvs)*tf_multi
打印(来自时间戳)
数据+=OHLCV
打印(str(len(data))+'of'+str(int(candle_no))+'candles loaded…)
除了(ccxt.ExchangeError、ccxt.AuthenticationError、ccxt.ExchangeNotAvailable、ccxt.RequestTimeout)作为错误:
打印('出现错误',键入(错误)。\uuuu name,error.args',在中重试,'等待,'秒…'))
时间。睡眠(保持)
标题=['t'、'o'、'h'、'l'、'c'、'v']
df=pd.DataFrame(数据,列=标题)
打开('btcusd.txt','w')
np.savetxt('btcusd.txt',df.o,fmt='%.8f')
// https://pastebin.com/xy1Ddb5z -btcusd.txt

我认为问题在于
fetch\u ohlcv
循环中返回重复的值。
一旦你有了
df
,就用

# Keep only needed rows
df = df[df.Timestamp <= end]
# Delete duplicate rows
df = df.drop_duplicates()
或者,如果将时间戳转换为更可读的格式(例如使用
exchange.iso8601()

df['Close'].plot()
plt.plot(df['Date']._values, df['Close']._values)