load stocks in typescript

To load stocks in TypeScript, you can use an API that provides stock market data. One such API is Alpha Vantage (https://www.alphavantage.co/). Here's how you can load stock data using Alpha Vantage API in TypeScript:

  1. First, you need to get an API key by signing up on the Alpha Vantage website.
  2. Use the fetch API to make a GET request to the Alpha Vantage API endpoint, passing in your API key and the stock symbol you want to load data for.
  3. Parse the response JSON and extract the relevant data, such as the latest price, high, and low.
  4. Display the data on the page using DOM manipulation.

Here's an example code snippet:

index.ts
const apiKey = 'your-api-key';
const stockSymbol = 'AAPL';

fetch(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${stockSymbol}&apikey=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    const latestPrice = data['Global Quote']['05. price'];
    const high = data['Global Quote']['03. high'];
    const low = data['Global Quote']['04. low'];
    
    // Display the data on the page using DOM manipulation
    const stockElement = document.querySelector('#stock');
    stockElement.innerHTML = `Latest price: ${latestPrice}<br>High: ${high}<br>Low: ${low}`;
  })
  .catch(error => console.error(error));
640 chars
16 lines

This code fetches the latest stock price, high, and low for Apple (AAPL) using the Alpha Vantage API and displays the data on the page.

Note that you may need to handle errors and edge cases, such as invalid API keys or stock symbols that don't exist. Also, be sure to check the API documentation for any usage limits and restrictions.

gistlibby LogSnag