1

最近我正在阅读 Quandl 中的一些股票价格数据库,使用 API 调用来提取数据。但我真的对我的例子感到困惑。

import requests

api_url = 'https://www.quandl.com/api/v1/datasets/WIKI/%s.json' % stock
session = requests.Session()
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
raw_data = session.get(api_url)

谁能给我解释一下?

1) 对于 api_url,如果我复制该网页,它会显示 404 未找到。那么如果我想使用其他数据库,我该如何准备这个api_usl呢?'% 库存' 是什么意思?

2)这里的request好像是用来提取数据的,raw_data的格式是什么?我怎么知道列名?如何提取列?

4

1 回答 1

1

要扩展我上面的评论:

  1. % stock是一个字符串格式化操作,用.%s引用的值替换前面的字符串stock。更多细节可以在这里找到
  2. raw_data实际上引用了一个 Response 对象(requests模块的一部分-在此处找到详细信息

扩展您的代码。

import requests
#Set the stock we are interested in, AAPL is Apple stock code
stock = 'AAPL'
#Your code
api_url = 'https://www.quandl.com/api/v1/datasets/WIKI/%s.json' % stock
session = requests.Session()
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
raw_data = session.get(api_url)

# Probably want to check that requests.Response is 200 - OK here 
# to make sure we got the content successfully.

# requests.Response has a function to return json file as python dict
aapl_stock = raw_data.json()
# We can then look at the keys to see what we have access to
aapl_stock.keys()
# column_names Seems to be describing the individual data points
aapl_stock['column_names']
# A big list of data, lets just look at the first ten points...
aapl_stock['data'][0:10]

编辑以回答评论中的问题

所以aapl_stock[column_names]显示DateOpen分别作为第一个和第二个值。这意味着它们对应于位置01数据的每个元素。

因此访问日期使用aapl_stock['data'][0:10][0]前十个项目的日期值)和访问开放使用的值aapl_stock['data'][0:78][1]前 78 个项目的开放值)。

要获取数据集中每个值的列表,其中每个元素都是包含 Date 和 Open 值的列表,您可以添加类似aapl_date_open = aapl_stock['data'][:][0:1].

如果您是 python 新手,我强烈建议您查看列表切片符号,可以在此处找到快速介绍

于 2016-01-29T00:48:50.293 回答