Another skill I needed for my “morning greeter” program was a way to get stock quotes for multiple companies at a time. Similar to getting news, there are many sources on the internet for getting this information. A popular website for getting stock quotes is Yahoo Finance which also happens to provide a webservice the fits my needs exactly. It allows querying multiple ticker symbols in a single request and can return the data in JSON format.
Here’s a simple Python function that takes a list of ticker symbol strings and returns the URL for getting the stock quotes as JSON data.
For example, you can get the URL for Apple, Facebook, and Netflix using the list:
['AAPL', 'FB', 'NFLX']
Which will return the URL string: http://finance.yahoo.com/webservice/v1/symbols/APPL,FB,NFLX/quote?format=json&view=detail
An HTTP GET request will return a response like this:
Once we have the data, we need to parse it and convert it into speech-friendly text for Alexa.
First, we need to send an HTTP GET and parse the JSON data.
Note: I access the Python dictionary keys directly in the code snippets below, which can raise KeyError exceptions if the data is not exactly as expected. Use try/except block(s) as appropriate in your final code.
Inside the for loop, I’ll extract the info that I want:
Name of the company
Is the stock up/down?
What’s the price?
The name of the company can contain some extra text that’s not needed. Some simple string replacement is done to clean it up:
The change percentage is a positive/negative floating point number, but it’s returned as a string. The code below will translate the +/- into text and do some type conversion, rounding, and cleanup:
And finally, parse the price and put everything together: