[Python Patterns] Get stock info from alphavantage.co

Get stock quotes in your terminal from Alpha Advantage. You will need to sign up for a free API key, then export it as an environment variable.

Get stock quotes in your terminal from Alpha Advantage.  You will need to sign up for a free API key, then export it as an environment variable.

https://www.alphavantage.co/support/#api-key

import os
import requests

def get_stock(_symbol):
    """ GET Stock Price from alphavantage.co """
    API_KEY = os.getenv('ALPHAADVANTAGE_API_KEY')
    url = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={}&apikey={}'.format(_symbol, API_KEY)
    response = requests.get(url)
    res = response.json()
    symbol = res["Global Quote"]["01. symbol"]
    price = res["Global Quote"]["05. price"]
    data = {'symbol': symbol, 'price': price}
    return data

Output:

get_stock('tsla')
{'symbol': 'TSLA', 'price': '429.8000'}

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.