我从REST API获取股票数据,但是API没有提供他们提供的股票列表,所以我的列表和他们的列表是不同的。我通过嵌套循环运行我的请求,并试图弄清楚如何排除KeyError,然后转移到列表中的下一家公司。
for stock in stock_list:
#queryString = "symbols:"+stock+" AND publishedAt:[2021-03-20 TO 2021-04-02]"
queryString = "source.id:sec-api AND symbols:" + stock
payload = {
"type": "filterArticles",
"queryString": queryString,
"from": 0,
"size": 2000
}
print(queryString)
# Format your payload to JSON bytes
jsondata = json.dumps(payload)
jsondataasbytes = jsondata.encode('utf-8')
# Instantiate the request
req = urllib.request.Request(API_ENDPOINT)
# Set the correct HTTP header: Content-Type = application/json
req.add_header('Content-Type', 'application/json; charset=utf-8')
# Set the correct length of your request
req.add_header('Content-Length', len(jsondataasbytes))
# Send the request to the API
response = urllib.request.urlopen(req, jsondataasbytes)
# Read the response
res_body = response.read()
# Transform the response into JSON
assets = json.loads(res_body.decode("utf-8"))
##### parse JSON Array into variables for SQL ######
articles = assets["articles"][0:50]
#print(articles)
for article in articles:
title = (article['title'][0:50])
stock_id =(article['id'][0:50])
date = (article['publishedAt'][0:50])
sources = (article['source'])
name = (sources['name'][0:50])
id = (sources['id'][0:50])
#print(title)
details = (article['details'])
company_name = (details['name'][0:50])
type = (details['type'][0:50])
#print(type)
cik = (details['cik'][0:50])
symbol = (details['ticker'][0:50])
link_sec = (details['linkToHtmlAnnouncement'][0:50])
description = (details['description'][0:50])
try:
cursor.execute("""
INSERT INTO stock_sec (stock_id, title, date, description, link_sec, type, symbol, company_name, cik)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",(stock_id[0:50], title[0:50], date[0:50], description[0:50], link_sec[0:50], type[0:50], symbol[0:50], company_name[0:50], cik[0:50]))
except Exception as e:
print(e)