stock:getPrice

Get the price of a stock

Published July 5, 2025
Documentation

Overview

Retrieves real-time stock price data for a given stock ticker symbol. This task fetches current market data from Yahoo Finance API and returns the stock price along with timestamp information. It also sets metadata and metrics for tracking purposes.

Implementation

The task executes the following workflow:

  1. Price Fetching: Calls the fetchStockPrice boundary function with the ticker to retrieve current market data from Yahoo Finance API
  2. Metadata Recording: Sets environment metadata as 'sample-script' and records the queried ticker symbol
  3. Metrics Tracking: Records metrics with type 'stock', name 'price', and the retrieved price value for monitoring purposes
  4. Response Formation: Constructs and returns a structured response containing the ticker, price, and current timestamp
Source Code
// TASK: getPrice
// Run this task with:
// forge task:run stock:getPrice --ticker AAPL
// forge task:run stock:getPrice --ticker VOO

import { createTask } from '@forgehive/task'
import { Schema } from '@forgehive/schema'

const schema = new Schema({
  ticker: Schema.string()
})

const name = 'stock:getPrice'
const description = 'Get the price of a stock'

const boundaries = {
  fetchStockPrice: async (ticker: string): Promise<{price:number}> => {
    const url = `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}`
    const response = await fetch(url)

    if (!response.ok) {
      throw new Error(`Failed to fetch stock price for ${ticker}: ${response.statusText}`)
    }

    const data = await response.json()
    const price = data.chart.result[0].meta.regularMarketPrice
    return {price}
  }
}

export const getPrice = createTask({
  name,
  description,
  schema,
  boundaries,
  fn: async function ({ ticker }, { fetchStockPrice, setMetadata, setMetrics }): Promise<{ ticker: string, price: number, date: string }> {
    const { price } = await fetchStockPrice(ticker as string)

    setMetadata('environment', 'sample-script')
    setMetadata('ticker', ticker)
    setMetrics({ type: 'stock', name: 'price', value: price })

    return {
      ticker,
      price,
      date: new Date().toISOString()
    }
  }
})