我是Python初学者。我一直在尝试使用IEX API获取一系列日期的开盘价。
我的json值显示:
{'AAPL': {'2017-02-09': {'open': 129.1019, 'high': 129.8815, 'low': 128.5821, 'close': 129.8569, 'volume': 28349859.0}, '2017-02-10': {'open': 129.8962, 'high': 130.3669, 'low': 129.4941, 'close': 129.5628, 'volume': 20065458.0}, '2017-02-13': {'open': 130.5042, 'high': 131.2299, 'low': 130.1806, 'close': 130.7101, 'volume': 23035421.0}}}
如果我只想显示所有日期的“开盘”价格,我该怎么做?
我一直在搜索列表和字典,但找不到任何有用的信息...
from iexfinance import get_historical_data
from datetime import datetime
import json
start = datetime(2017, 2, 9)
end = datetime(2017, 2, 13)
f = get_historical_data("AAPL", start, end, output_format='json')
json_string = json.dumps(f)
json_read = json.loads(json_string)
print(json_read)
答案 0 :(得分:1)
iexfinance
module you are using可以为您提供更方便的格式:Pandas data frame:
df = get_historical_data("AAPL", start, end, output_format='pandas')
print(df.open)
数据按日期编制索引,因此df.open
列是按日期划分的熊猫Series
开头值:</ p>
>>> from iexfinance import get_historical_data
>>> from datetime import datetime
>>> start = datetime(2017, 2, 9)
>>> end = datetime(2017, 2, 13)
>>> df = get_historical_data("AAPL", start, end, output_format='pandas')
>>> print(df.open)
date
2017-02-09 129.1019
2017-02-10 129.8962
2017-02-13 130.5042
Name: open, dtype: float64
>>> for open in df.open:
... print(open)
...
129.1019
129.8962
130.5042
当您使用json
格式时,该模块会生成一个 Python字典,无需转换为JSON并再次返回。该格式适用于JSON序列化,但您无需跳过这些麻烦。当然,开发人员对格式名称的选择令人困惑。
要对字典执行相同的操作,只需循环遍历'AAPL'
所引用字典的所有项目;键是日期,并且值是更多字典,每列都有一个键:
f = get_historical_data("AAPL", start, end)
for date, date_entry in f['AAPL'].items():
print(date, date_entry['open'])
这将为您提供dictionary-defined order中的条目;您可能要先按键排序:
for date, date_entry in sorted(f['AAPL'].items(), key=lambda kv: kv[0]):
print(date, date_entry['open'])
答案 1 :(得分:0)
您在寻找这样的东西吗?
for day in json_reads['AAPL']:
print("{0}: {1}".format(day, json_reads['AAPL'][day]['open']))
尽管编码过多,您仍可能会看到一般的词典访问思想。
答案 2 :(得分:0)
请尝试以下操作:
def find_open(stock):
for k,v in stock.items():
if k == 'open':
print(stock[k])
elif isinstance(v, dict):
find_open(v)
find_open({'AAPL':{'2017-02-09':{'open':129.1019,'high':129.8815,'low':128.5821,'close':129.8569,'volume':28349859.0} ,'2017-02-10':{'open':129.8962,'high':130.3669,'low':129.4941,'close':129.5628,'volume':20065458.0},'2017-02-13':{ '打开':130.5042,'高':131.2299,'低':130.1806,'收盘':130.7101,'交易量:23035421.0}}))