我的代码如下所示:
import requests
import re
import mechanize
import urllib
import json
htmltext = urllib.urlopen("https://www.binance.com/api/v1/klines?symbol=BCDBTC&interval=4h")
data = json.load(htmltext)
current_price= data[len(data)-1][4]
last_prices= (data[len(data)-2][4],data[len(data)-3][4],data[len(data)-4][4],data[len(data)-5][4],data[len(data)-6][4])
last_volumes= (data[len(data)-2][5],data[len(data)-3][5],data[len(data)-4][5],data[len(data)-5][5],data[len(data)-6][5])
current_volume= data[len(data)-1][5]
print current_price
print last_prices
if current_price > last_prices:
print "the current price is greater than the last 5"
print current_volume
print last_volumes
if current_volume > last_volumes:
print "the current volume is higher than the last 5"
但我的输出是这样的:
0.00495600
(u'0.00492500', u'0.00366300', u'0.00332800', u'0.00333800', u'0.00308000')
the current price is greater than the last 5
938.01000000
(u'29687.32500000', u'14740.03800000', u'9366.77400000', u'10324.83200000', u'44953.53400000')
the current volume is higher than the last 5
这里的问题是当前的音量肯定不会比最后的音量大5但是它仍然会打印出来
我从这里抓取数据 https://www.binance.com/tradeDetail.html?symbol=BCD_BTC
答案 0 :(得分:1)
首先,您的数据并非全部转换为数字,其中许多都是字符串格式。要将它们全部转换为浮点数,您可以使用以下公式:
data = [[float(x) for x in row] for row in data]
接下来,在if语句中,您将数字与一系列数字进行比较。你想要的是将这个数字与序列中最大的数字进行比较:
if current_price > max(last_prices):
print "the current price is greater than the last 5"
全部放在一起:
# code to obtain data is the same
PRICE = 4
VOLUME = 5
LAST_ROW = -1
data = [[float(x) for x in row] for row in data]
current_price = data[LAST_ROW][PRICE]
current_volume = data[LAST_ROW][VOLUME]
last_prices = tuple(row[PRICE] for row in data[-6:-1])
last_volumes = tuple(row[VOLUME] for row in data[-6:-1])
print 'current_price =', current_price
print 'current_volume =', current_volume
print 'last_prices =', last_prices
print 'last_volumes =', last_volumes
if current_price > max(last_prices):
print "the current price is greater than the last 5"
if current_volume > max(last_volumes):
print "the current volume is higher than the last 5"