Introduction
In today’s digital world, having access to real-time stock data is essential for making informed investment decisions.
With the help of APIs, we can easily fetch and display live stock prices. This tutorial will show you how to write a simple
Go program to track and display stock prices using a public API.
Objective
The objective of this tutorial is to teach you how to:
- Use a public stock price API to fetch live stock data
- Parse JSON data in Go
- Display real-time stock prices on the console
Code Example
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type StockPrice struct {
Symbol string `json:"symbol"`
Company string `json:"companyName"`
Price float64 `json:"latestPrice"`
Currency string `json:"currency"`
}
func getStockPrice(symbol string) (StockPrice, error) {
url := fmt.Sprintf("https://cloud.iexapis.com/stable/stock/%s/quote?token=YOUR_API_KEY", symbol)
resp, err := http.Get(url)
if err != nil {
return StockPrice{}, err
}
defer resp.Body.Close()
var stock StockPrice
if err := json.NewDecoder(resp.Body).Decode(&stock); err != nil {
return StockPrice{}, err
}
return stock, nil
}
func main() {
var symbol string
fmt.Println("Enter stock symbol (e.g., AAPL for Apple):")
fmt.Scanln(&symbol)
stock, err := getStockPrice(symbol)
if err != nil {
log.Fatalf("Error fetching stock price: %v", err)
}
fmt.Printf("Stock Symbol: %s\n", stock.Symbol)
fmt.Printf("Company: %s\n", stock.Company)
fmt.Printf("Price: %.2f %s\n", stock.Price, stock.Currency)
}
Explanation of the Program Structure
The Go program is simple and efficient for tracking and displaying stock prices. Here is a breakdown of its structure:
- Imports: The program imports necessary Go packages like
net/http
for making HTTP requests,encoding/json
for parsing JSON data, andfmt
for formatting and printing output. - StockPrice struct: This struct defines the fields that will hold stock data such as
symbol
,companyName
,latestPrice
, andcurrency
. - getStockPrice function: This function takes a stock symbol as input, constructs an API request, and fetches the stock data from the API. It returns the data as a
StockPrice
object. - main function: The program prompts the user to enter a stock symbol (e.g., AAPL for Apple), fetches the stock price using the
getStockPrice
function, and then displays the result.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from Go Downloads.
- Sign up for an API key from IEX Cloud or any other stock price API provider. Replace
YOUR_API_KEY
in the code with your actual API key. - Save the code to a file named
stock_tracker.go
. - Open your terminal and navigate to the folder where you saved the file.
- Run the program using the following command:
go run stock_tracker.go
- Enter a stock symbol when prompted, and the program will display the latest stock price for that symbol.