即使API上的日期不断变化,我能否找到该股票的close
价格?
API:
'Time Series (1min)': {
'2017-12-19 13:01:00':{
'1. open':'196.4100',
'2. high':'196.5075',
'3. low':'196.3800',
'4. close':'196.3800',
'5. volume':'4961'
}
}
Python代码:
print('Grabbing stock price...')
ourl = req.get(url)
im = ourl.json()
return im #return closing price
你几乎已经在你自己的例子中,只需用实际日期替换0
。
im['Time Series (1min)']['2017-12-19 13:01:00']['4. close']
# output '196.3800'
编辑循环:
dict
的事情是,你没有索引dict
,你使用键访问项目。这是拥有一个关键值对的主要目的。或者更准确地说,当你需要索引某些东西时,不要使用dict
。
我建议你使用像pandas
这样的东西。
import pandas as pd
# option 1
df = pd.DataFrame(ourl.json())
df.columns = ['Meta', 'TS'] # save time typing spaces
return df.TS[2]['4. close']
# option 2
df = pd.DataFrame(ourl.json())
return df.iloc[:, 1][2]['4. close']
# output
'196.3800'
这样,每次获取项目时都可以返回单个值,并通过索引返回该值。(部分)
附:你没有告诉我们什么ourl.json()
返回,我假设它在这里返回一个字典。特别是,你想要做的是正确索引,组织字符串声音对我来说有点混乱..因为我们实际上并没有组织一个字符串:)
在不知道时间的情况下提取价格的另一种方法是使用带有urllib.request
包的json
包和一些循环:
import json
import urllib.request
def extract_json(f):
json_decode = json.load(f)
time_series = json_decode['Time Series (1min)']
for data in time_series:
print(time_series[data]['3. low'])
opener = urllib.request.FancyURLopener({})
url = "http://localhost:8092/sample_json.json"
f = opener.open(url)
extract_json(f)
如果服务器上的输入是:
{
"Time Series (1min)": {
"2017-12-19 13:01:00": {
"1. open": "196.4100",
"2. high": "196.5075",
"3. low": "196.3800",
"4. close": "196.3800",
"5. volume": "4961"
}
}
}
运行脚本的结果是:
196.3800
试过这个版本:
3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
使用im.items()
将你的dict转换为tupples。然后使用索引访问元素。
im = {
'Time Series (1min)': {
'2017-12-19 13:01:00': {
'1. open': '196.4100',
'2. high': '196.5075',
'3. low': '196.3800',
'4. close': '196.3800',
'5. volume': '4961'
}
}
}
对于Python 2
print im['Time Series (1min)'].items()[0][1]['4. close'] # prints 196.3800
对于Python 3,这应该改变如下
print(list(a['Time Series (1min)'].items())[0][1]['4. close']) # prints 196.3800
或者你可以循环通过a['Time Series (1min)'].items()
迭代