### Install yahoo-finance-api Source: https://github.com/oscarli916/yahoo-finance-api/blob/master/README.md Use 'go get' to add the package to your Go project. ```bash go get github.com/oscarli916/yahoo-finance-api ``` -------------------------------- ### Installation Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Instructions on how to install the yahoo-finance-api package using Go modules. ```APIDOC ## Installation Install the package using Go modules: ```bash go get github.com/oscarli916/yahoo-finance-api ``` ``` -------------------------------- ### Yahoo Finance API Usage Example Source: https://github.com/oscarli916/yahoo-finance-api/blob/master/README.md Demonstrates fetching various financial data points for a given ticker symbol using the yahoo-finance-api package. Ensure proper error handling for each API call. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { t := yfa.NewTicker("AAPL") // get the latest PriceData quote, err := t.Quote() if err != nil { fmt.Println("Error fetching quote:", err) return } fmt.Println(quote.Close) // history data history, err := t.History(yfa.HistoryQuery{Range: "1d", Interval: "1m"}) if err != nil { fmt.Println("Error fetching history:", err) return } fmt.Println(history) // option chain e := t.ExpirationDates() oc := t.OptionChainByExpiration(e[2]) fmt.Println(oc) // Ticker Information info, err := t.GetInfo() if err != nil { fmt.Println("GetInfo returned error:", err) } fmt.Println(info) // Search for symbols results, err := t.Search("AAPL", 10) if err != nil { fmt.Println("Search returned error:", err) } for _, r := range results { fmt.Printf("%s - %s (%s)\n", r.Symbol, r.Name, r.Type) } } ``` -------------------------------- ### Comprehensive Yahoo Finance API Usage Example Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Demonstrates fetching current quote, ticker information, historical data, options data, and searching for related symbols for a given stock ticker. Ensure the 'yfa' package is imported correctly. ```go package main import ( "fmt" "log" "sort" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { // Create ticker for a stock ticker := yfa.NewTicker("AAPL") // 1. Get current quote quote, err := ticker.Quote() if err != nil { log.Printf("Quote error: %v", err) } else { fmt.Printf("=== Current Quote ===\n") fmt.Printf("AAPL: $%.2f (Volume: %d)\n\n", quote.Close, quote.Volume) } // 2. Get ticker info info, err := ticker.Info() if err != nil { log.Printf("Info error: %v", err) } else { fmt.Printf("=== Ticker Info ===\n") fmt.Printf("Name: %s\n", info.LongName) fmt.Printf("Exchange: %s\n", info.ExchangeName) fmt.Printf("Market State: %s\n\n", info.MarketState) } // 3. Get historical data history, err := ticker.History(yfa.HistoryQuery{ Range: "5d", Interval: "1d", }) if err != nil { log.Printf("History error: %v", err) } else { fmt.Printf("=== 5-Day History ===\n") dates := make([]string, 0, len(history)) for d := range history { dates = append(dates, d) } sort.Strings(dates) for _, d := range dates { p := history[d] fmt.Printf("%s: O=%.2f H=%.2f L=%.2f C=%.2f\n", d, p.Open, p.High, p.Low, p.Close) } fmt.Println() } // 4. Get options data expirations := ticker.ExpirationDates() if len(expirations) > 0 { fmt.Printf("=== Options (Expiring %s) ===\n", expirations[0]) options := ticker.OptionChainByExpiration(expirations[0]) fmt.Printf("Calls: %d, Puts: %d\n\n", len(options.Calls), len(options.Puts)) } // 5. Search for related symbols results, err := ticker.Search("Apple", 5) if err != nil { log.Printf("Search error: %v", err) } else { fmt.Printf("=== Related Symbols ===\n") for _, r := range results { fmt.Printf("%s: %s (%s)\n", r.Symbol, r.Name, r.Type) } } } ``` -------------------------------- ### Retrieve Full Options Chain for a Ticker Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Use this function to get all call and put options for a specific ticker across all expiration dates. Requires initializing a ticker object. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("NVDA") optionChain := ticker.OptionChain() fmt.Printf("Options Chain for NVDA:\n") fmt.Printf(" Expiration Date: %s\n", optionChain.ExpirationDate) fmt.Printf(" Has Mini Options: %v\n", optionChain.HasMiniOptions) fmt.Printf(" Total Calls: %d\n", len(optionChain.Calls)) fmt.Printf(" Total Puts: %d\n", len(optionChain.Puts)) // Display first few call options fmt.Printf("\nSample Call Options:\n") for i, call := range optionChain.Calls { if i >= 3 { break } fmt.Printf(" %s - Strike: $%.2f, Last: $%.2f, Bid: $%.2f, Ask: $%.2f, IV: %.2f%%, ITM: %v\n", call.ContractSymbol, call.Strike, call.LastPrice, call.Bid, call.Ask, call.ImpliedVolatility*100, call.InTheMoney) } // Display first few put options fmt.Printf("\nSample Put Options:\n") for i, put := range optionChain.Puts { if i >= 3 { break } fmt.Printf(" %s - Strike: $%.2f, Last: $%.2f, Bid: $%.2f, Ask: $%.2f, IV: %.2f%%, ITM: %v\n", put.ContractSymbol, put.Strike, put.LastPrice, put.Bid, put.Ask, put.ImpliedVolatility*100, put.InTheMoney) } } ``` -------------------------------- ### Fetch Historical Data with Range and Interval Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Use this to get historical stock data for a predefined range (e.g., '1mo') and a specific interval (e.g., '1d'). Ensure the range and interval combination is valid. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("GOOGL") // Option 1: Using Range (predefined time periods) // Valid ranges: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max history1, err := ticker.History(yfa.HistoryQuery{ Range: "1mo", // Last 1 month Interval: "1d", // Daily data }) if err != nil { log.Fatal(err) } fmt.Printf("1-month daily data: %d entries\n", len(history1)) ``` -------------------------------- ### Retrieve Options Chain by Expiration Date Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Fetches the options chain for a specific expiration date. Ensure to call ExpirationDates() first to obtain valid dates. This example demonstrates retrieving and processing call options data. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("AAPL") // First get available expiration dates expirationDates := ticker.ExpirationDates() if len(expirationDates) < 3 { fmt.Println("Not enough expiration dates available") return } // Get options chain for the third expiration date targetDate := expirationDates[2] optionChain := ticker.OptionChainByExpiration(targetDate) fmt.Printf("Options Chain for AAPL expiring %s:\n", optionChain.ExpirationDate) fmt.Printf(" Calls: %d contracts\n", len(optionChain.Calls)) fmt.Printf(" Puts: %d contracts\n", len(optionChain.Puts)) // Find at-the-money options fmt.Printf("\nAt-The-Money Call Options:\n") for _, call := range optionChain.Calls { if call.Strike >= 220 && call.Strike <= 230 { fmt.Printf(" Strike: $%.2f | Last: $%.2f | Bid/Ask: $%.2f/$%.2f | OI: %d | Vol: %d\n", call.Strike, call.LastPrice, call.Bid, call.Ask, call.OpenInterest, call.Volume) } } } ``` -------------------------------- ### Fetch Intraday Historical Data Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Use this to get intraday historical stock data (e.g., '15m' interval) for short ranges (e.g., '5d'). Note that intraday intervals are only supported for short ranges. ```go // Valid intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo // Note: Intraday intervals (1m-90m) only work with short ranges (1d, 5d, 7d) intradayHistory, err := ticker.History(yfa.HistoryQuery{ Range: "5d", Interval: "15m", // 15-minute intervals }) if err != nil { log.Fatal(err) } fmt.Printf("5-day 15-minute data: %d entries\n", len(intradayHistory)) ``` -------------------------------- ### OptionChainByExpiration API Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Retrieves the options chain filtered by a specific expiration date. It's recommended to use ExpirationDates() first to get valid dates before calling this function. ```APIDOC ## GET /api/options/chain/{ticker}/{expirationDate} ### Description Retrieves the options chain for a given stock ticker and expiration date. ### Method GET ### Endpoint `/api/options/chain/{ticker}/{expirationDate}` ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., AAPL). - **expirationDate** (string) - Required - The expiration date in YYYY-MM-DD format. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **ExpirationDate** (string) - The expiration date of the options chain. - **Calls** (array) - An array of call option contracts. - **Strike** (float) - The strike price of the option. - **LastPrice** (float) - The last traded price of the option. - **Bid** (float) - The current bid price. - **Ask** (float) - The current ask price. - **OpenInterest** (integer) - The total number of open contracts. - **Volume** (integer) - The trading volume for the day. - **Puts** (array) - An array of put option contracts (same fields as Calls). #### Response Example { "ExpirationDate": "2024-02-02", "Calls": [ { "Strike": 220.00, "LastPrice": 6.50, "Bid": 6.40, "Ask": 6.60, "OpenInterest": 12500, "Volume": 3200 } ], "Puts": [ { "Strike": 220.00, "LastPrice": 5.00, "Bid": 4.90, "Ask": 5.10, "OpenInterest": 10000, "Volume": 2500 } ] } ``` -------------------------------- ### Search Investment Symbols with Custom Options Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Use SearchWithOptions to find investment symbols with advanced control over search parameters like fuzzy matching and cryptocurrency boosting. Ensure correct import paths and parameter initialization. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("") // Custom search with specific parameters params := yfa.SearchParams{ Query: "Bitcoin", QuotesCount: 15, NewsCount: 0, ListsCount: 0, EnableFuzzyQuery: true, // Enable fuzzy matching EnableEnhancedTrivialQuery: true, EnableCccBoost: true, // Boost cryptocurrency results EnablePrivateCompany: false, // Exclude private companies EnableResearchReports: false, EnableCulturalAssets: false, EnableLogoUrl: false, EnableNavLinks: false, EnableCb: false, EnableLists: false, QuotesQueryId: "tss_match_phrase_query", MultiQuoteQueryId: "multi_quote_single_token_query", RecommendCount: 5, Lang: "en-US", } results, err := ticker.SearchWithOptions(params) if err != nil { log.Fatal("Search error:", err) } fmt.Printf("Custom Search Results for 'Bitcoin' (%d results):\n", len(results)) for _, r := range results { fmt.Printf(" %s - %s (%s) [%s]\n", r.Symbol, r.Name, r.Type, r.Exchange) } // Output: // Custom Search Results for 'Bitcoin' (15 results): // BTC-USD - Bitcoin USD (CRYPTOCURRENCY) [CCC] // BTCUSD=X - BTC/USD (CURRENCY) [CCY] // BTC-EUR - Bitcoin EUR (CRYPTOCURRENCY) [CCC] // BTC-GBP - Bitcoin GBP (CRYPTOCURRENCY) [CCC] // GBTC - Grayscale Bitcoin Trust (ETF) [NYSEArca] // BITO - ProShares Bitcoin Strategy ETF (ETF) [NYSEArca] // IBIT - iShares Bitcoin Trust (ETF) [NASDAQ] // FBTC - Fidelity Wise Origin Bitcoin Fund (ETF) [NYSEArca] // BITB - Bitwise Bitcoin ETF (ETF) [NYSEArca] // ARKB - ARK 21Shares Bitcoin ETF (ETF) [NYSEArca] // ... } ``` -------------------------------- ### Create New Ticker Instance Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Creates a new Ticker instance for a given stock symbol. This is the main entry point for all data operations. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { // Create a new ticker for Apple Inc. ticker := yfa.NewTicker("AAPL") // The ticker can now be used to fetch various data fmt.Printf("Ticker created for symbol: %s\n", ticker.Symbol) // Output: Ticker created for symbol: AAPL } ``` -------------------------------- ### Fetch Historical Data with Start/End Dates and Interval Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Use this to retrieve historical stock data for a custom date range (YYYY-MM-DD) and a specified interval (e.g., '1wk'). ```go // Option 2: Using Start/End dates (format: YYYY-MM-DD) history2, err := ticker.History(yfa.HistoryQuery{ Start: "2024-01-01", End: "2024-06-30", Interval: "1wk", // Weekly data }) if err != nil { log.Fatal(err) } fmt.Printf("Custom date range weekly data: %d entries\n", len(history2)) ``` -------------------------------- ### Go: HistoryQuery Structure Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Configures historical data requests, specifying the time range, interval, and optional date ranges or user agent. ```go type HistoryQuery struct { Range string // Time range: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max Interval string // Data interval: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo Start string // Start date (YYYY-MM-DD) - alternative to Range End string // End date (YYYY-MM-DD) - optional, defaults to now UserAgent string // Custom user agent (optional) } ``` -------------------------------- ### Fetch Ticker Information Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Retrieves detailed information for a given ticker symbol, including market state, exchange, currency, and price metrics. Handles potential nil values for optional fields. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("TSLA") info, err := ticker.Info() if err != nil { log.Fatal("Error fetching info:", err) } fmt.Printf("Ticker Information for %s:\n", info.Symbol) fmt.Printf(" Name: %s\n", info.LongName) fmt.Printf(" Short Name: %s\n", info.ShortName) fmt.Printf(" Exchange: %s (%s)\n", info.ExchangeName, info.Exchange) fmt.Printf(" Currency: %s (%s)\n", info.Currency, info.CurrencySymbol) fmt.Printf(" Market State: %s\n", info.MarketState) fmt.Printf(" Quote Type: %s\n", info.QuoteType) if info.RegularMarketPrice != nil { fmt.Printf(" Current Price: %s\n", info.RegularMarketPrice.Fmt) } if info.RegularMarketDayHigh != nil { fmt.Printf(" Day High: %s\n", info.RegularMarketDayHigh.Fmt) } if info.RegularMarketDayLow != nil { fmt.Printf(" Day Low: %s\n", info.RegularMarketDayLow.Fmt) } if info.MarketCap != nil { fmt.Printf(" Market Cap: %s\n", info.MarketCap.Fmt) } ``` -------------------------------- ### Go: OptionData Structure Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Represents options chain data for a specific expiration date. Includes details on calls and puts. ```go type OptionData struct { ExpirationDate string // Expiration date (YYYY-MM-DD format) HasMiniOptions bool // Whether mini options are available Calls []OptionDetail // List of call options Puts []OptionDetail // List of put options } ``` -------------------------------- ### HistoryQuery Options Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt This section details how to query historical stock data using the `HistoryQuery` struct, supporting both predefined ranges and custom date ranges, along with various intervals. ```APIDOC ## HistoryQuery Options This endpoint allows you to retrieve historical stock data for a given ticker. You can customize your query using `HistoryQuery` options. ### Method GET (Implicitly through the `History` method) ### Endpoint `/ticker/{symbol}/history` (Conceptual endpoint, actual implementation is via library method) ### Parameters #### Query Parameters - **Range** (string) - Optional - Predefined time periods. Valid values: `1d`, `5d`, `1mo`, `3mo`, `6mo`, `1y`, `2y`, `5y`, `10y`, `ytd`, `max`. - **Start** (string) - Optional - Start date for the data range in `YYYY-MM-DD` format. Use either `Range` or `Start`/`End`. - **End** (string) - Optional - End date for the data range in `YYYY-MM-DD` format. Use either `Range` or `Start`/`End`. - **Interval** (string) - Required - The interval of the data. Valid values: `1m`, `2m`, `5m`, `15m`, `30m`, `60m`, `90m`, `1h`, `1d`, `5d`, `1wk`, `1mo`, `3mo`. Note: Intraday intervals (`1m` to `90m`) are only compatible with short ranges like `1d`, `5d`, `7d`. ### Request Example (Go) ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("GOOGL") // Option 1: Using Range history1, err := ticker.History(yfa.HistoryQuery{ Range: "1mo", Interval: "1d", }) if err != nil { log.Fatal(err) } fmt.Printf("1-month daily data: %d entries\n", len(history1)) // Option 2: Using Start/End dates history2, err := ticker.History(yfa.HistoryQuery{ Start: "2024-01-01", End: "2024-06-30", Interval: "1wk", }) if err != nil { log.Fatal(err) } fmt.Printf("Custom date range weekly data: %d entries\n", len(history2)) // Intraday example intradayHistory, err := ticker.History(yfa.HistoryQuery{ Range: "5d", Interval: "15m", }) if err != nil { log.Fatal(err) } fmt.Printf("5-day 15-minute data: %d entries\n", len(intradayHistory)) } ``` ### Response #### Success Response (200) Returns an array of historical data points, each containing fields like Date, Open, High, Low, Close, Volume, and Adj Close. #### Response Example (Conceptual) ```json [ { "Date": "2024-01-01", "Open": 130.00, "High": 131.50, "Low": 129.80, "Close": 131.20, "Adj Close": 131.20, "Volume": 1500000 } // ... more data points ] ``` ``` -------------------------------- ### Retrieve Expiration Dates for a Ticker Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Fetches a list of all available options expiration dates for a given stock symbol. The dates are returned as formatted strings. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("SPY") expirationDates := ticker.ExpirationDates() fmt.Printf("Available Options Expiration Dates for SPY (%d dates):\n", len(expirationDates)) for i, date := range expirationDates { if i >= 10 { fmt.Printf(" ... and %d more\n", len(expirationDates)-10) break } fmt.Printf(" %d. %s\n", i+1, date) } } ``` -------------------------------- ### Go: OptionDetail Structure Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Represents a single option contract with its trading and contract details. Used within OptionData. ```go type OptionDetail struct { ContractSymbol string // Option contract symbol Strike float64 // Strike price Currency string // Currency (e.g., "USD") LastPrice float64 // Last traded price Change float64 // Price change PercentChange float64 // Percent change Volume int64 // Trading volume OpenInterest int64 // Open interest Bid float64 // Bid price Ask float64 // Ask price ContractSize string // Contract size (e.g., "REGULAR") Expiration string // Expiration date LastTradeDate string // Last trade date ImpliedVolatility float64 // Implied volatility (decimal) InTheMoney bool // Whether option is in-the-money } ``` -------------------------------- ### Go: PriceData Structure Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Represents OHLCV (Open, High, Low, Close, Volume) price data for a single time period. Used for historical price fetching. ```go type PriceData struct { Open float64 // Opening price High float64 // Highest price Low float64 // Lowest price Close float64 // Closing price Volume int64 // Trading volume } ``` -------------------------------- ### Go: SearchResult Structure Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Represents a symbol search result, containing basic information about a financial instrument. ```go type SearchResult struct { Symbol string // Ticker symbol Name string // Display name ShortName string // Short name LongName string // Full company name Type string // Security type (EQUITY, ETF, etc.) Exchange string // Exchange code ExchDisp string // Exchange display name } ``` -------------------------------- ### NewTicker Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Creates a new Ticker instance for a given stock symbol. The Ticker is the main entry point for all data operations. ```APIDOC ## NewTicker Creates a new Ticker instance for a given stock symbol. The Ticker is the main entry point for all data operations and initializes internal components for history, options, information, and search functionality. ```go package main import ( "fmt" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { // Create a new ticker for Apple Inc. ticker := yfa.NewTicker("AAPL") // The ticker can now be used to fetch various data fmt.Printf("Ticker created for symbol: %s\n", ticker.Symbol) // Output: Ticker created for symbol: AAPL } ``` ``` -------------------------------- ### Retrieve Historical Price Data Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Retrieves historical price data for the ticker based on a customizable query. Supports configurable time ranges, intervals, and date periods. Returns a map of date strings to PriceData structs. ```go package main import ( "fmt" "log" "sort" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("MSFT") // Fetch 1-day history with 1-minute intervals history, err := ticker.History(yfa.HistoryQuery{ Range: "1d", Interval: "1m", }) if err != nil { log.Fatal("Error fetching history:", err) } // Get sorted dates dates := make([]string, 0, len(history)) for date := range history { dates = append(dates, date) } sort.Strings(dates) fmt.Printf("Intraday history for MSFT (%d data points):\n", len(history)) for _, date := range dates[:3] { // Show first 3 entries data := history[date] fmt.Printf(" %s - O: %.2f, H: %.2f, L: %.2f, C: %.2f, V: %d\n", date, data.Open, data.High, data.Low, data.Close, data.Volume) } // Fetch 6-month history with daily intervals using custom date range historyDaily, err := ticker.History(yfa.HistoryQuery{ Range: "6mo", Interval: "1d", }) if err != nil { log.Fatal("Error fetching daily history:", err) } fmt.Printf("\nDaily history: %d trading days\n", len(historyDaily)) // Output: // Intraday history for MSFT (390 data points): // 2024-01-15 09:30:00 - O: 390.50, H: 391.20, L: 390.10, C: 390.85, V: 125000 // 2024-01-15 09:31:00 - O: 390.85, H: 391.50, L: 390.70, C: 391.25, V: 98000 // 2024-01-15 09:32:00 - O: 391.25, H: 391.80, L: 391.00, C: 391.60, V: 87500 // // Daily history: 126 trading days } ``` -------------------------------- ### Search Investment Symbols Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Searches for investment symbols using a query string and a limit for the number of results. This function is useful for finding tickers by company name or ETF descriptions. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("") // Symbol not required for search // Search for technology companies results, err := ticker.Search("Apple", 10) if err != nil { log.Fatal("Search error:", err) } fmt.Printf("Search Results for 'Apple' (%d results):\n", len(results)) for _, r := range results { fmt.Printf(" %s - %s (%s) [%s]\n", r.Symbol, r.Name, r.Type, r.ExchDisp) } // Search for ETFs etfResults, err := ticker.Search("S&P 500 ETF", 5) if err != nil { log.Fatal("ETF search error:", err) } fmt.Printf("\nS&P 500 ETF Search Results:\n") for _, r := range etfResults { fmt.Printf(" %s - %s [%s]\n", r.Symbol, r.Name, r.Exchange) } } ``` -------------------------------- ### Quote Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Returns the latest price data for the ticker's symbol. This is a convenience wrapper that fetches historical data and returns the most recent entry. ```APIDOC ## Quote Returns the latest price data for the ticker's symbol. This is a convenience wrapper that fetches historical data and returns the most recent entry with open, high, low, close prices and volume. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("AAPL") quote, err := ticker.Quote() if err != nil { log.Fatal("Error fetching quote:", err) } fmt.Printf("Latest Quote for AAPL:\n") fmt.Printf(" Open: $%.2f\n", quote.Open) fmt.Printf(" High: $%.2f\n", quote.High) fmt.Printf(" Low: $%.2f\n", quote.Low) fmt.Printf(" Close: $%.2f\n", quote.Close) fmt.Printf(" Volume: %d\n", quote.Volume) // Output: // Latest Quote for AAPL: // Open: $223.50 // High: $225.75 // Low: $222.80 // Close: $224.90 // Volume: 52345678 } ``` ``` -------------------------------- ### History Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Retrieves historical price data for the ticker based on a customizable query. Supports configurable time ranges, intervals, and date periods. ```APIDOC ## History Retrieves historical price data for the ticker based on a customizable query. Supports configurable time ranges, intervals, and date periods. Returns a map of date strings to PriceData structs. ```go package main import ( "fmt" "log" "sort" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("MSFT") // Fetch 1-day history with 1-minute intervals history, err := ticker.History(yfa.HistoryQuery{ Range: "1d", Interval: "1m", }) if err != nil { log.Fatal("Error fetching history:", err) } // Get sorted dates dates := make([]string, 0, len(history)) for date := range history { dates = append(dates, date) } sort.Strings(dates) fmt.Printf("Intraday history for MSFT (%d data points):\n", len(history)) for _, date := range dates[:3] { // Show first 3 entries data := history[date] fmt.Printf(" %s - O: %.2f, H: %.2f, L: %.2f, C: %.2f, V: %d\n", date, data.Open, data.High, data.Low, data.Close, data.Volume) } // Fetch 6-month history with daily intervals using custom date range historyDaily, err := ticker.History(yfa.HistoryQuery{ Range: "6mo", Interval: "1d", }) if err != nil { log.Fatal("Error fetching daily history:", err) } fmt.Printf("\nDaily history: %d trading days\n", len(historyDaily)) // Output: // Intraday history for MSFT (390 data points): // 2024-01-15 09:30:00 - O: 390.50, H: 391.20, L: 390.10, C: 390.85, V: 125000 // 2024-01-15 09:31:00 - O: 390.85, H: 391.50, L: 390.70, C: 391.25, V: 98000 // 2024-01-15 09:32:00 - O: 391.25, H: 391.80, L: 391.00, C: 391.60, V: 87500 // // Daily history: 126 trading days } ``` ``` -------------------------------- ### Fetch Latest Stock Quote Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Returns the latest price data for the ticker's symbol. This function fetches historical data and returns the most recent entry. ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("AAPL") quote, err := ticker.Quote() if err != nil { log.Fatal("Error fetching quote:", err) } fmt.Printf("Latest Quote for AAPL:\n") fmt.Printf(" Open: $%.2f\n", quote.Open) fmt.Printf(" High: $%.2f\n", quote.High) fmt.Printf(" Low: $%.2f\n", quote.Low) fmt.Printf(" Close: $%.2f\n", quote.Close) fmt.Printf(" Volume: %d\n", quote.Volume) // Output: // Latest Quote for AAPL: // Open: $223.50 // High: $225.75 // Low: $222.80 // Close: $224.90 // Volume: 52345678 } ``` -------------------------------- ### Ticker Info API Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt This endpoint retrieves detailed information about a specific stock ticker, including market data, company details, and pricing metrics. ```APIDOC ## Info Retrieves detailed ticker information including market state, exchange info, currency, and current price metrics from Yahoo Finance's quoteSummary API. ### Method GET (Implicitly through the `Info` method) ### Endpoint `/ticker/{symbol}/info` (Conceptual endpoint, actual implementation is via library method) ### Parameters This endpoint does not require any specific parameters beyond the ticker symbol itself, which is typically set when initializing the ticker object. ### Request Example (Go) ```go package main import ( "fmt" "log" yfa "github.com/oscarli916/yahoo-finance-api" ) func main() { ticker := yfa.NewTicker("TSLA") info, err := ticker.Info() if err != nil { log.Fatal("Error fetching info:", err) } fmt.Printf("Ticker Information for %s:\n", info.Symbol) fmt.Printf(" Name: %s\n", info.LongName) fmt.Printf(" Short Name: %s\n", info.ShortName) fmt.Printf(" Exchange: %s (%s)\n", info.ExchangeName, info.Exchange) fmt.Printf(" Currency: %s (%s)\n", info.Currency, info.CurrencySymbol) fmt.Printf(" Market State: %s\n", info.MarketState) fmt.Printf(" Quote Type: %s\n", info.QuoteType) if info.RegularMarketPrice != nil { fmt.Printf(" Current Price: %s\n", info.RegularMarketPrice.Fmt) } if info.RegularMarketDayHigh != nil { fmt.Printf(" Day High: %s\n", info.RegularMarketDayHigh.Fmt) } if info.RegularMarketDayLow != nil { fmt.Printf(" Day Low: %s\n", info.RegularMarketDayLow.Fmt) } if info.MarketCap != nil { fmt.Printf(" Market Cap: %s\n", info.MarketCap.Fmt) } } ``` ### Response #### Success Response (200) Returns a JSON object containing various details about the ticker. Key fields include: - **Symbol** (string): The stock ticker symbol. - **LongName** (string): The full company name. - **ShortName** (string): A shorter name for the company. - **ExchangeName** (string): The name of the stock exchange. - **Exchange** (string): The exchange code. - **Currency** (string): The currency of trading. - **CurrencySymbol** (string): The symbol for the currency. - **MarketState** (string): The current state of the market (e.g., REGULAR, PRE, POST). - **QuoteType** (string): The type of security (e.g., EQUITY). - **RegularMarketPrice** (object): Current market price details. - **RegularMarketDayHigh** (object): The highest price during the regular trading day. - **RegularMarketDayLow** (object): The lowest price during the regular trading day. - **MarketCap** (object): The market capitalization of the company. #### Response Example (Conceptual) ```json { "Symbol": "TSLA", "LongName": "Tesla, Inc.", "ShortName": "Tesla, Inc.", "ExchangeName": "NASDAQ", "Exchange": "NMS", "Currency": "USD", "CurrencySymbol": "$", "MarketState": "REGULAR", "QuoteType": "EQUITY", "RegularMarketPrice": {"Raw": 248.50, "Fmt": "248.50"}, "RegularMarketDayHigh": {"Raw": 252.30, "Fmt": "252.30"}, "RegularMarketDayLow": {"Raw": 245.10, "Fmt": "245.10"}, "MarketCap": {"Raw": 789500000000, "Fmt": "789.5B"} } ``` ``` -------------------------------- ### Search API Source: https://context7.com/oscarli916/yahoo-finance-api/llms.txt Searches for investment symbols by query using Yahoo Finance's public search API. Returns matching symbols with metadata like name, type, and exchange. ```APIDOC ## GET /api/search ### Description Searches for investment symbols based on a query string. ### Method GET ### Endpoint `/api/search` ### Parameters #### Query Parameters - **query** (string) - Required - The search term (e.g., "Apple", "S&P 500 ETF"). - **limit** (integer) - Optional - The maximum number of results to return. Defaults to 10 if not specified. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **results** (array) - An array of search result objects. - **Symbol** (string) - The stock ticker symbol. - **Name** (string) - The full name of the company or ETF. - **Type** (string) - The type of security (e.g., EQUITY, ETF). - **ExchDisp** (string) - The displayed exchange name. - **Exchange** (string) - The exchange code. #### Response Example { "results": [ { "Symbol": "AAPL", "Name": "Apple Inc.", "Type": "EQUITY", "ExchDisp": "NASDAQ", "Exchange": "NASDAQ" } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.