In this tutorial, we will write a Python program to track and display real-time stock prices using an API. This program will fetch stock data from a financial data provider and display it in an easily readable format.
Objective
The objective of this program is to help you track stock prices using a simple Python script and an API. By fetching real-time data from a financial API, we can display the current price of a given stock symbol and more details about it.
Code Example
import requests
# Function to get stock price from API
def get_stock_price(stock_symbol):
api_key = 'your_api_key_here'
url = f'https://finnhub.io/api/v1/quote?symbol={stock_symbol}&token={api_key}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
current_price = data['c']
high_price = data['h']
low_price = data['l']
open_price = data['o']
print(f"Stock Price for {stock_symbol}:")
print(f"Current Price: ${current_price}")
print(f"High Price: ${high_price}")
print(f"Low Price: ${low_price}")
print(f"Open Price: ${open_price}")
else:
print(f"Failed to retrieve data for {stock_symbol}. Please check the API key or stock symbol.")
# Example usage
if __name__ == '__main__':
stock_symbol = input("Enter the stock symbol (e.g., AAPL for Apple): ").upper()
get_stock_price(stock_symbol)
Program Structure
The program consists of the following parts:
- API Request: The
get_stock_price
function sends a GET request to the Finnhub API with the specified stock symbol. - Response Handling: Upon receiving the response, the program checks if the request was successful (status code 200). It then extracts the relevant stock data such as the current price, high price, low price, and open price.
- User Input: The user is prompted to enter a stock symbol (like “AAPL” for Apple) to get the stock data.
How to Run the Program
- Install the requests library if you don’t have it installed. You can do this by running the following command:
pip install requests
- Sign up for an API key from Finnhub and replace
your_api_key_here
with the actual API key in the code. - Run the Python script by executing the command:
python stock_price_tracker.py
- Enter the stock symbol (e.g., AAPL for Apple) when prompted to see the real-time stock price information.