I want to obtain financial data.
The Jupyter Notebook for this little project is found here.
Yahoo Finance API
According to “Alternative to Google Finance API” from stackoverflow, financial information can be obtained through the Yahoo Finance API.
Note: the Google Finance API is depricated.
Using this API, you can generate a CSV by a simple API call:
# generate and save a CSV for AAPL, GOOG and MSFT
http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk
You can also use the Yahoo Finance webservice to return XML or JSON:
# All stock quotes in XML
http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote
# All stock quotes in JSON
http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json
Furthermore, you can also use the Yahoo Query Language for obtaining data.
Making a webservice request
import requests
import json
# Make simple API call
# return results in JSON format
url = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
response = requests.get(url)
# Load JSON string as JSON object
j = json.loads(response.content)
# Extract data and print the first entry
stock = [i['resource']['fields'] for i in j['list']['resources']]
stock[1]
[{'name': 'USD/KRW',
'price': '1116.109985',
'symbol': 'KRW=X',
'ts': '1495284995',
'type': 'currency',
'utctime': '2017-05-20T12:56:35+0000',
'volume': '0'}]
The yahoo-finance
Python package
In addition to calling a request, there is a python package (yahoo-finance
) which provide functions to get stock data from Yahoo Finance.
import yahoo_finance
# Get information about the Yahoo stock
yahoo = yahoo_finance.Share('YHOO')
print(yahoo.get_open())
print(yahoo.get_price())
print(yahoo.get_trade_datetime())
50.03
50.18
2017-05-19 20:00:00 UTC+0000
# Refresh and get new prices
yahoo.refresh()
print(yahoo.get_price())
print(yahoo.get_trade_datetime())
50.18
2017-05-19 20:00:00 UTC+0000
Issues in getting historical data
While working through the examples, the yahoo.get_historical('2014-04-25', '2014-04-29')
function returns a YQLResponseMalformedError: Response malformed.
error. Searching this error online, the Financial Hacker (2017) wrote:
The Yahoo Finance API is dead. Without prior announcement, Yahoo has abandoned their only remaining service that was clearly ahead of the competition.
The link to this bug report (“issue”) is found here. But for now, not all functionality is lost.