yfinance

package module
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

goyfinace

goyfinace is a Go client for the public Yahoo Finance endpoints used by the Python yfinance project. It supports the common workflows: historical OHLCV downloads, quote metadata, fast info, symbol search, option chains, financial statement modules, holders, recommendations, and concurrent multi-symbol history downloads.

Yahoo Finance does not provide these endpoints as a supported public API. Treat upstream schema changes and rate limits as expected operational risks.

Acknowledgements

This project is inspired by and API-compatible in spirit with ranaroussi/yfinance. Thanks to the yfinance project for documenting the practical Yahoo Finance workflows that this Go implementation follows.

Install

go get github.com/Nightsuki/goyfinace

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	yfinance "github.com/Nightsuki/goyfinace"
)

func main() {
	client := yfinance.NewClient(nil)

	history, err := client.Ticker("AAPL").History(context.Background(), yfinance.HistoryParams{
		Period:   yfinance.Period1Mo,
		Interval: yfinance.Interval1D,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(history.Symbol, len(history.Candles))

	info, err := client.Ticker("AAPL").Info(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(info["regularMarketPrice"])
}

API Surface

  • Client.History / Ticker.History: chart candles from /v8/finance/chart/{symbol}.
  • Client.Download: concurrent history downloads for multiple symbols.
  • Client.Info / Ticker.Info: common quoteSummary modules flattened into a map.
  • Client.FastInfo: selected price metadata from chart metadata.
  • Client.QuoteSummary: raw quoteSummary module access for advanced callers.
  • Client.Search: symbol lookup via Yahoo Finance search.
  • Client.Options: option chains for the default or requested expiration.
  • Client.Financials, Client.Holders, Client.Recommendations: convenience wrappers over quote-summary modules.
  • yfinance-compatible extras: Actions, Dividends, Splits, CapitalGains, Quote, News, Calendar, SECFilings, Sustainability, Valuation, Analysis, analyst estimates, holder/insider helpers, FundProfile, FundsData, SharesFull, Shares, statement timeseries, Lookup, PredefinedScreen, Screen, screener query builders, Market, Tickers, Calendars, MarketSummary, MarketStatus, Sector, Industry, typed SectorOf/IndustryOf accessors, EarningsDates, and WebSocket.
  • Pricing adjustments: HistoryParams.AutoAdjust, BackAdjust, Rounding, and Repair mirror yfinance's auto_adjust/back_adjust/rounding/repair flags. HistoryParams.Threads bounds Download concurrency.
  • Cookie + crumb authentication: Client.Authenticate(ctx) primes the jar and crumb; subsequent calls to crumb-protected endpoints attach crumb automatically.
  • Reliability & observability: Client.Logger (slog), Client.Retries + Client.RetryBackoff (exponential backoff for 5xx/rate-limit/transient network errors), and Client.Limiter (NewRateLimiter(rps, burst) or any golang.org/x/time/rate.Limiter).
  • Download progress callbacks via HistoryParams.OnProgress; HistoryParams.NoEvents explicitly suppresses Yahoo events; HistoryParams.DropNaN drops all-NaN rows.
  • Advanced search via Client.SearchWithOptions exposing fuzzy / enhanced-trivial / private-company / region / lang flags.
  • Optional GET-JSON response cache: Client.Cache (NewMemoryCache() or any Cache implementation) with Client.CacheTTL.
  • Auto-reconnecting WebSocket: AutoReconnect, ReconnectBackoff, MaxReconnectAttempts, OnReconnect with transparent re-subscribe on reconnection.

The default UserAgent mirrors the browser user-agent list used by upstream yfinance. Set Client.UserAgent when a fixed application-specific value is required.

Detailed API documentation is available in English by default, with Chinese as a localized version:

Date Ranges

Use either a Yahoo period string or explicit start/end timestamps:

history, err := client.History(ctx, "MSFT", yfinance.HistoryParams{
	Start:    time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
	End:      time.Date(2024, 2, 1, 0, 0, 0, 0, time.UTC),
	Interval: yfinance.Interval1D,
})

Yahoo treats End as exclusive, matching yfinance behavior.

DataFrame Adapter

The core API returns Go structs, slices, and maps instead of exposing a DataFrame type. For pandas-style table workflows, import the Gota adapter:

import yfgota "github.com/Nightsuki/goyfinace/adapter/gota"

history, err := client.History(ctx, "AAPL", yfinance.HistoryParams{
	Period:   yfinance.Period1Mo,
	Interval: yfinance.Interval1D,
})
if err != nil {
	log.Fatal(err)
}

df := yfgota.History(history)
fmt.Println(df.Nrow(), df.Col("Close").Float())

The adapter currently supports history candles, corporate actions, option contracts/chains, search results, quote-summary modules, fundamentals timeseries, key/value maps, and generic records.

Testing

go test ./...
go vet ./...

The unit tests use httptest and do not call Yahoo Finance.

License

Apache License 2.0. This project is a Go implementation inspired by the public behavior of yfinance; it is not affiliated with Yahoo.

Documentation

Overview

Package yfinance provides a Go client for public Yahoo Finance endpoints.

The package mirrors the common yfinance workflows for downloading historical prices, reading quote metadata, searching symbols, fetching option chains, and retrieving quote-summary financial modules. Yahoo Finance does not publish a supported public API for these endpoints, so callers should handle upstream response changes and rate limiting as normal operational concerns.

A Client is safe to reuse across requests. Create one with NewClient, then call methods directly with a symbol:

client := yfinance.NewClient(nil)
history, err := client.History(ctx, "AAPL", yfinance.HistoryParams{
	Period:   yfinance.Period1Mo,
	Interval: yfinance.Interval1D,
})

For repeated calls against one symbol, use Ticker:

ticker := client.Ticker("MSFT")
info, err := ticker.Info(ctx)
options, err := ticker.Options(ctx, time.Time{})

History accepts either a Yahoo period such as Period1Mo or explicit Start and End values. When Start or End is set, the client sends Unix period1/period2 parameters and does not send range. End is exclusive, matching yfinance and Yahoo chart behavior.

Methods return normal Go errors. ErrRateLimited maps HTTP 429, ErrNoResult indicates a successful response without result data, and YahooError preserves structured errors returned by Yahoo JSON payloads.

Index

Examples

Constants

View Source
const (
	Period1D  = "1d"
	Period5D  = "5d"
	Period1Mo = "1mo"
	Period3Mo = "3mo"
	Period6Mo = "6mo"
	Period1Y  = "1y"
	Period2Y  = "2y"
	Period5Y  = "5y"
	Period10Y = "10y"
	PeriodYTD = "ytd"
	PeriodMax = "max"

	Interval1M  = "1m"
	Interval2M  = "2m"
	Interval5M  = "5m"
	Interval15M = "15m"
	Interval30M = "30m"
	Interval60M = "60m"
	Interval90M = "90m"
	Interval1H  = "1h"
	Interval1D  = "1d"
	Interval5D  = "5d"
	Interval1Wk = "1wk"
	Interval1Mo = "1mo"
	Interval3Mo = "3mo"
)
View Source
const (
	LookupAll            = "all"
	LookupEquity         = "equity"
	LookupMutualFund     = "mutualfund"
	LookupETF            = "etf"
	LookupIndex          = "index"
	LookupFuture         = "future"
	LookupCurrency       = "currency"
	LookupCryptocurrency = "cryptocurrency"
)

Variables

View Source
var (
	// ErrNoResult indicates Yahoo returned a syntactically valid response that
	// did not contain a result for the requested symbol.
	ErrNoResult = errors.New("yfinance: no result")

	// ErrRateLimited indicates Yahoo rejected the request due to rate limiting.
	ErrRateLimited = errors.New("yfinance: rate limited")
)
View Source
var DefaultUserAgents = []string{
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (X11; Linux i686; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Safari/605.1.15",
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/131.0.2903.86",
}

DefaultUserAgents mirrors the browser user-agent set used by yfinance.

Functions

func ETFQuery added in v0.4.0

func ETFQuery(filters ...ScreenerQuery) map[string]any

ETFQuery builds a Yahoo ETF screener query.

func EquityQuery added in v0.4.0

func EquityQuery(filters ...ScreenerQuery) map[string]any

EquityQuery builds a Yahoo equity screener query.

func FundQuery added in v0.4.0

func FundQuery(filters ...ScreenerQuery) map[string]any

FundQuery builds a Yahoo mutual-fund screener query.

Types

type Action added in v0.3.0

type Action struct {
	Time  time.Time
	Type  ActionType
	Value float64
}

Action is a dividend, capital-gains distribution, or stock split event.

type ActionType added in v0.3.0

type ActionType string

ActionType identifies a corporate action event.

const (
	ActionDividend    ActionType = "dividend"
	ActionCapitalGain ActionType = "capitalGain"
	ActionSplit       ActionType = "split"
)

type Cache added in v0.5.0

type Cache interface {
	Get(key string) ([]byte, bool)
	Set(key string, value []byte, ttl time.Duration)
}

Cache is the minimal interface for an HTTP-response cache. Implementations must be safe for concurrent use. The TTL is advisory — callers may treat zero as "no expiry" — and Set may be a no-op.

type CalendarQuery added in v0.3.0

type CalendarQuery struct {
	Size          int            `json:"size,omitempty"`
	Offset        int            `json:"offset,omitempty"`
	Query         map[string]any `json:"query,omitempty"`
	SortField     string         `json:"sortField,omitempty"`
	SortType      string         `json:"sortType,omitempty"`
	EntityIDType  string         `json:"entityIdType,omitempty"`
	IncludeFields []string       `json:"includeFields,omitempty"`
}

CalendarQuery is a raw Yahoo visualization calendar query.

type Calendars added in v0.4.0

type Calendars struct {
	// contains filtered or unexported fields
}

Calendars is a helper for Yahoo calendar endpoints.

func (*Calendars) Earnings added in v0.4.0

func (cals *Calendars) Earnings(ctx context.Context, limit int, symbols ...string) (map[string]any, error)

Earnings fetches earnings calendar rows. When symbols are provided, the first symbol is used for the ticker-specific endpoint.

func (*Calendars) Visualization added in v0.4.0

func (cals *Calendars) Visualization(ctx context.Context, query CalendarQuery) (map[string]any, error)

Visualization runs a raw Yahoo calendar visualization query.

type Candle

type Candle struct {
	// Time is the candle timestamp in UTC.
	Time time.Time
	// Open, High, Low, and Close are the raw OHLC prices. Yahoo null values are
	// represented as math.NaN for floating point fields.
	Open  float64
	High  float64
	Low   float64
	Close float64
	// AdjClose is Yahoo's adjusted close value. If Yahoo omits adjusted close,
	// the client falls back to Close for that row.
	AdjClose float64
	// Volume is the reported trading volume. Missing volume is zero.
	Volume int64
	// Dividends contains the dividend amount for this timestamp when Yahoo
	// returns a dividend event.
	Dividends float64
	// CapitalGains contains the capital-gains distribution amount for this
	// timestamp when Yahoo returns a capital-gains event.
	CapitalGains float64
	// Split is numerator/denominator for a split event at this timestamp. For
	// example, a 4-for-1 split is represented as 4.
	Split float64
}

Candle is one OHLCV row from Yahoo chart data.

type ChartMeta

type ChartMeta struct {
	Currency          string
	Symbol            string
	ExchangeName      string
	FullExchangeName  string
	InstrumentType    string
	FirstTradeDate    time.Time
	RegularMarketTime time.Time
	// GMTOffset is Yahoo's exchange offset in seconds.
	GMTOffset int
	Timezone  string
	// ExchangeTimezoneName is the IANA timezone name when Yahoo provides one.
	ExchangeTimezoneName string
	RegularMarketPrice   float64
	ChartPreviousClose   float64
	PriceHint            int
	// Raw contains the full chart meta object for callers that need fields not
	// promoted by this struct.
	Raw map[string]any
}

ChartMeta contains selected metadata returned by Yahoo chart.

type Client

type Client struct {
	// HTTPClient is used for all requests. A nil value is replaced by a client
	// with a 15 second timeout.
	HTTPClient *http.Client
	// Query1URL and Query2URL allow tests and advanced callers to override the
	// Yahoo host. Leave empty for the default Yahoo endpoints.
	Query1URL string
	Query2URL string
	// RootURL is used for Yahoo Finance frontend JSON endpoints.
	RootURL string
	// ISINURL is used only by the best-effort ISIN helper. Yahoo does not
	// expose a stable ticker-to-ISIN endpoint, so this is intentionally separate.
	ISINURL string
	// CookiePrimeURL is the small Yahoo endpoint visited only to set the
	// A1/A3 session cookies before fetching a crumb. yfinance's Python
	// implementation uses https://fc.yahoo.com (a 404-returning endpoint
	// that still sets cookies); the full https://finance.yahoo.com/ home
	// page is multiple megabytes and is the wrong choice for priming.
	CookiePrimeURL string
	// UserAgent is sent on every request. Leave empty for the package default.
	UserAgent string
	// Crumb is the bot-detection token Yahoo requires on quoteSummary and
	// related endpoints. Use Authenticate to populate it automatically; it is
	// then auto-appended to outgoing requests.
	Crumb string

	// Logger receives debug-level events for each request and response when
	// non-nil. Mirrors yfinance's enable_debug_mode() but uses slog so callers
	// can plug in any handler.
	Logger *slog.Logger

	// Retries bounds how many times a transient failure (5xx, ErrRateLimited,
	// network error) is retried with exponential backoff. Zero means a single
	// attempt with no retries. Mirrors yfinance's session-level retry behavior.
	Retries int

	// RetryBackoff is the base delay between retries; each retry doubles the
	// previous wait. Zero means 250ms.
	RetryBackoff time.Duration

	// Limiter, when non-nil, gates every outgoing request through Wait(ctx).
	// Use NewRateLimiter for a simple token-bucket implementation, or supply
	// any Limiter implementation (e.g. golang.org/x/time/rate.Limiter).
	Limiter Limiter

	// Cache, when non-nil, caches GET-JSON responses keyed by the full URL.
	// Use NewMemoryCache for a simple in-process implementation. CacheTTL
	// controls per-entry expiry; a zero value means cached entries never
	// expire.
	Cache    Cache
	CacheTTL time.Duration
	// contains filtered or unexported fields
}

Client is a Yahoo Finance HTTP client.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a client configured for Yahoo Finance public endpoints.

If httpClient is nil, a default client is created with a 15-second timeout and an in-memory cookie jar. The cookie jar is required for Yahoo's crumb-based authentication; supply your own jar by setting HTTPClient.Jar yourself when passing a custom http.Client.

func (*Client) Actions added in v0.3.0

func (c *Client) Actions(ctx context.Context, symbol string, params HistoryParams) ([]Action, error)

Actions returns dividend, capital-gains, and split events for a symbol.

func (*Client) Analysis added in v0.3.0

func (c *Client) Analysis(ctx context.Context, symbol string) (map[string]any, error)

Analysis fetches yfinance-style analyst modules.

func (*Client) AnalystPriceTargets added in v0.3.0

func (c *Client) AnalystPriceTargets(ctx context.Context, symbol string) (map[string]any, error)

AnalystPriceTargets returns the raw financialData module containing target prices.

func (*Client) AsyncWebSocket added in v0.4.0

func (c *Client) AsyncWebSocket(url string) *WebSocket

AsyncWebSocket creates a context-driven streaming client.

func (*Client) Authenticate added in v0.5.0

func (c *Client) Authenticate(ctx context.Context) error

Authenticate primes the client's cookie jar by visiting Yahoo Finance and then fetches a fresh crumb token. After a successful call, c.Crumb is set and is automatically appended to subsequent requests that target Yahoo's crumb-protected endpoints.

Authenticate is safe to call multiple times concurrently; only one fetch runs at a time and others observe the cached value.

func (*Client) BalanceSheet added in v0.3.0

func (c *Client) BalanceSheet(ctx context.Context, symbol string, freq string) (map[string]any, error)

BalanceSheet fetches a common balance-sheet fundamentals timeseries set.

func (*Client) Calendar added in v0.3.0

func (c *Client) Calendar(ctx context.Context, symbol string) (map[string]any, error)

Calendar fetches Yahoo calendar events for a symbol.

func (*Client) CalendarVisualization added in v0.3.0

func (c *Client) CalendarVisualization(ctx context.Context, query CalendarQuery) (map[string]any, error)

CalendarVisualization runs Yahoo's visualization endpoint used by yfinance calendars.

func (*Client) Calendars added in v0.4.0

func (c *Client) Calendars() *Calendars

Calendars creates a calendar helper.

func (*Client) CapitalGains added in v0.3.0

func (c *Client) CapitalGains(ctx context.Context, symbol string, params HistoryParams) ([]Action, error)

CapitalGains returns capital-gains distribution events for a symbol.

func (*Client) CashFlow added in v0.3.0

func (c *Client) CashFlow(ctx context.Context, symbol string, freq string) (map[string]any, error)

CashFlow fetches a common cash-flow fundamentals timeseries set.

func (*Client) Dividends added in v0.3.0

func (c *Client) Dividends(ctx context.Context, symbol string, params HistoryParams) ([]Action, error)

Dividends returns dividend events for a symbol.

func (*Client) Download

func (c *Client) Download(ctx context.Context, symbols []string, params HistoryParams) []DownloadResult

Download downloads history for multiple symbols concurrently.

When params.Threads > 0, concurrency is bounded to that many in-flight requests. Otherwise every symbol is fetched in its own goroutine.

func (*Client) EPSRevisions added in v0.4.0

func (c *Client) EPSRevisions(ctx context.Context, symbol string) (map[string]any, error)

EPSRevisions fetches EPS revisions from Yahoo earningsTrend.

func (*Client) EPSTrend added in v0.4.0

func (c *Client) EPSTrend(ctx context.Context, symbol string) (map[string]any, error)

EPSTrend fetches EPS trend data from Yahoo earningsTrend.

func (*Client) Earnings added in v0.4.0

func (c *Client) Earnings(ctx context.Context, symbol string) (map[string]any, error)

Earnings fetches Yahoo earnings modules.

func (*Client) EarningsDates added in v0.3.0

func (c *Client) EarningsDates(ctx context.Context, symbol string, limit int) (map[string]any, error)

EarningsDates fetches earnings calendar rows for a ticker using Yahoo's visualization endpoint.

func (*Client) EarningsEstimate added in v0.4.0

func (c *Client) EarningsEstimate(ctx context.Context, symbol string) (map[string]any, error)

EarningsEstimate fetches earnings-estimate data from Yahoo earningsTrend.

func (*Client) EarningsHistory added in v0.4.0

func (c *Client) EarningsHistory(ctx context.Context, symbol string) (map[string]any, error)

EarningsHistory fetches earnings-history data.

func (*Client) EnsureCrumb added in v0.5.0

func (c *Client) EnsureCrumb(ctx context.Context) error

EnsureCrumb calls Authenticate when the client does not yet have a crumb. It is invoked automatically before crumb-protected requests when the client targets the real Yahoo hosts.

func (*Client) FastInfo

func (c *Client) FastInfo(ctx context.Context, symbol string) (*FastInfo, error)

FastInfo returns selected price metadata from the chart endpoint.

func (*Client) Financials

func (c *Client) Financials(ctx context.Context, symbol string) (map[string]any, error)

Financials fetches Yahoo quoteSummary financial statement modules.

func (*Client) FundProfile added in v0.3.0

func (c *Client) FundProfile(ctx context.Context, symbol string) (map[string]any, error)

FundProfile fetches fund-specific quote summary modules.

func (*Client) FundamentalsTimeseries added in v0.3.0

func (c *Client) FundamentalsTimeseries(ctx context.Context, symbol string, types []string, start, end time.Time) (map[string]any, error)

FundamentalsTimeseries fetches raw Yahoo fundamentals timeseries types.

func (*Client) FundsData added in v0.5.0

func (c *Client) FundsData(ctx context.Context, symbol string) (*FundsData, error)

FundsData fetches fund-specific quoteSummary modules and returns a typed wrapper.

func (*Client) GrowthEstimates added in v0.4.0

func (c *Client) GrowthEstimates(ctx context.Context, symbol string) (map[string]any, error)

GrowthEstimates fetches stock, industry, sector, and index growth estimates.

func (*Client) History

func (c *Client) History(ctx context.Context, symbol string, params HistoryParams) (*HistoryResult, error)

History downloads historical OHLCV candles for a symbol.

Example
package main

import (
	"context"
	"fmt"
	"log"

	yfinance "github.com/Nightsuki/goyfinace"
)

func main() {
	client := yfinance.NewClient(nil)
	history, err := client.History(context.Background(), "AAPL", yfinance.HistoryParams{
		Period:   yfinance.Period1Mo,
		Interval: yfinance.Interval1D,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(history.Symbol)
}

func (*Client) HistoryMetadata added in v0.4.0

func (c *Client) HistoryMetadata(ctx context.Context, symbol string) (map[string]any, error)

HistoryMetadata fetches chart metadata for a symbol.

func (*Client) Holders

func (c *Client) Holders(ctx context.Context, symbol string) (map[string]any, error)

Holders fetches institutional, fund, and insider holders modules.

func (*Client) ISIN added in v0.3.0

func (c *Client) ISIN(ctx context.Context, symbol string) (string, error)

ISIN attempts to resolve a ticker's ISIN through an external suggestion endpoint. Yahoo does not expose a stable ticker-to-ISIN endpoint, so this helper is best-effort and returns ErrNoResult when it cannot verify an exact symbol match.

func (*Client) IncomeStatement added in v0.3.0

func (c *Client) IncomeStatement(ctx context.Context, symbol string, freq string) (map[string]any, error)

IncomeStatement fetches a common income-statement fundamentals timeseries set.

func (*Client) Industry added in v0.3.0

func (c *Client) Industry(ctx context.Context, key string) (map[string]any, error)

Industry fetches Yahoo industry domain data by key.

func (*Client) IndustryOf added in v0.5.0

func (c *Client) IndustryOf(ctx context.Context, key string) (*IndustryData, error)

IndustryOf fetches Yahoo industry data by key as a typed IndustryData value.

func (*Client) Info

func (c *Client) Info(ctx context.Context, symbol string) (map[string]any, error)

Info fetches the common yfinance info module set and flattens one level.

func (*Client) InsiderPurchases added in v0.4.0

func (c *Client) InsiderPurchases(ctx context.Context, symbol string) (map[string]any, error)

InsiderPurchases fetches net share purchase activity.

func (*Client) InsiderRosterHolders added in v0.4.0

func (c *Client) InsiderRosterHolders(ctx context.Context, symbol string) (map[string]any, error)

InsiderRosterHolders fetches insider roster/holder rows.

func (*Client) InsiderTransactions added in v0.4.0

func (c *Client) InsiderTransactions(ctx context.Context, symbol string) (map[string]any, error)

InsiderTransactions fetches insider transaction rows.

func (*Client) InstitutionalHolders added in v0.4.0

func (c *Client) InstitutionalHolders(ctx context.Context, symbol string) (map[string]any, error)

InstitutionalHolders fetches institutional ownership data.

func (*Client) Lookup added in v0.3.0

func (c *Client) Lookup(ctx context.Context, query string, lookupType string, count int) (map[string]any, error)

Lookup searches Yahoo Finance instruments by type.

func (*Client) LookupISIN added in v0.3.0

func (c *Client) LookupISIN(ctx context.Context, isin string) (*SearchResponse, error)

LookupISIN resolves an ISIN or other query through Yahoo search.

func (*Client) MajorHolders added in v0.4.0

func (c *Client) MajorHolders(ctx context.Context, symbol string) (map[string]any, error)

MajorHolders fetches major-holders breakdown data.

func (*Client) Market added in v0.4.0

func (c *Client) Market(name string) *Market

Market creates a market-scoped helper, for example "us".

func (*Client) MarketStatus added in v0.3.0

func (c *Client) MarketStatus(ctx context.Context, market string) (map[string]any, error)

MarketStatus fetches Yahoo market time/status data for a market, e.g. "us".

func (*Client) MarketSummary added in v0.3.0

func (c *Client) MarketSummary(ctx context.Context, market string) (map[string]any, error)

MarketSummary fetches Yahoo market summary data for a market, e.g. "us".

func (*Client) MutualFundHolders added in v0.4.0

func (c *Client) MutualFundHolders(ctx context.Context, symbol string) (map[string]any, error)

MutualFundHolders fetches fund ownership data.

func (*Client) News added in v0.3.0

func (c *Client) News(ctx context.Context, symbol string, count int, tab string) ([]map[string]any, error)

News fetches ticker news from Yahoo Finance's frontend JSON endpoint.

func (*Client) Options

func (c *Client) Options(ctx context.Context, symbol string, expiration time.Time) (*OptionChain, error)

Options fetches an option chain. Pass a zero expiration to fetch Yahoo's default expiration.

func (*Client) PredefinedScreen added in v0.3.0

func (c *Client) PredefinedScreen(ctx context.Context, screenID string, count int) (map[string]any, error)

PredefinedScreen runs one of Yahoo's predefined screener queries.

func (*Client) Quote added in v0.3.0

func (c *Client) Quote(ctx context.Context, symbols ...string) ([]Quote, error)

Quote fetches one or more quote rows from Yahoo's v7 quote endpoint.

func (*Client) QuoteSummary

func (c *Client) QuoteSummary(ctx context.Context, symbol string, modules ...string) (map[string]any, error)

QuoteSummary fetches raw quoteSummary modules for a symbol.

func (*Client) Recommendations

func (c *Client) Recommendations(ctx context.Context, symbol string) (map[string]any, error)

Recommendations fetches analyst recommendation modules.

func (*Client) RecommendationsSummary added in v0.4.0

func (c *Client) RecommendationsSummary(ctx context.Context, symbol string) (map[string]any, error)

RecommendationsSummary fetches Yahoo recommendation trend data.

func (*Client) RevenueEstimate added in v0.4.0

func (c *Client) RevenueEstimate(ctx context.Context, symbol string) (map[string]any, error)

RevenueEstimate fetches revenue-estimate data from Yahoo earningsTrend.

func (*Client) SECFilings added in v0.3.0

func (c *Client) SECFilings(ctx context.Context, symbol string) (map[string]any, error)

SECFilings fetches SEC filing metadata for a symbol.

func (*Client) Screen added in v0.3.0

func (c *Client) Screen(ctx context.Context, req ScreenRequest) (map[string]any, error)

Screen runs a custom Yahoo screener query.

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, quotesCount, newsCount int) (*SearchResponse, error)

Search queries Yahoo Finance's symbol search endpoint.

func (*Client) SearchWithOptions added in v0.5.0

func (c *Client) SearchWithOptions(ctx context.Context, query string, opts SearchOptions) (*SearchResponse, error)

SearchWithOptions runs Yahoo Finance's search endpoint with the full set of supported options. Use Search for the simple two-argument form.

func (*Client) Sector added in v0.3.0

func (c *Client) Sector(ctx context.Context, key string) (map[string]any, error)

Sector fetches Yahoo sector domain data by key, e.g. "technology".

func (*Client) SectorOf added in v0.5.0

func (c *Client) SectorOf(ctx context.Context, key string) (*SectorData, error)

SectorOf fetches Yahoo sector data by key as a typed SectorData value.

func (*Client) Shares added in v0.5.0

func (c *Client) Shares(ctx context.Context, symbol string, freq string) (map[string]any, error)

Shares fetches the quarterly or annual share-count time series. Mirrors yfinance's Ticker.shares (which returns sharesOutstanding by reporting period). Pass "quarterly", "annual" (default), or "trailing" for freq.

func (*Client) SharesFull added in v0.3.0

func (c *Client) SharesFull(ctx context.Context, symbol string, start, end time.Time) (map[string]any, error)

SharesFull fetches shares-out timeseries data.

func (*Client) Splits added in v0.3.0

func (c *Client) Splits(ctx context.Context, symbol string, params HistoryParams) ([]Action, error)

Splits returns stock split events for a symbol.

func (*Client) Sustainability added in v0.3.0

func (c *Client) Sustainability(ctx context.Context, symbol string) (map[string]any, error)

Sustainability fetches ESG score data for a symbol.

func (*Client) Ticker

func (c *Client) Ticker(symbol string) *Ticker

Ticker creates a symbol-scoped helper.

func (*Client) Tickers added in v0.4.0

func (c *Client) Tickers(symbols ...string) *Tickers

Tickers creates a multi-symbol helper.

func (*Client) UpgradesDowngrades added in v0.3.0

func (c *Client) UpgradesDowngrades(ctx context.Context, symbol string) (map[string]any, error)

UpgradesDowngrades fetches analyst upgrade/downgrade history.

func (*Client) Valuation added in v0.3.0

func (c *Client) Valuation(ctx context.Context, symbol string) (map[string]any, error)

Valuation fetches valuation-related quote summary modules.

func (*Client) WebSocket added in v0.4.0

func (c *Client) WebSocket(url string) *WebSocket

WebSocket creates a Yahoo Finance streaming client using this client's default user-agent settings.

type DownloadResult

type DownloadResult struct {
	// Symbol is the normalized uppercase symbol requested for this slot.
	Symbol string
	// Result is populated when Err is nil.
	Result *HistoryResult
	// Err is the per-symbol error. Download does not fail fast; inspect each
	// result independently.
	Err error
}

DownloadResult contains one symbol's download outcome.

type FastInfo

type FastInfo struct {
	Symbol           string
	Currency         string
	ExchangeName     string
	FullExchangeName string
	InstrumentType   string
	Timezone         string
	// ExchangeTimezoneName is the IANA timezone name returned in chart metadata.
	ExchangeTimezoneName string
	RegularMarketPrice   float64
	PreviousClose        float64
}

FastInfo contains selected ticker metadata.

type FundsData added in v0.5.0

type FundsData struct {
	Symbol string
	Raw    map[string]any
}

FundsData mirrors yfinance's `FundsData` accessor: a typed view over the fundProfile/topHoldings/quoteType/summaryProfile modules of an ETF or mutual fund.

func (*FundsData) AssetClasses added in v0.5.0

func (f *FundsData) AssetClasses() map[string]any

AssetClasses returns the topHoldings asset-class breakdown (cashPosition, stockPosition, bondPosition, etc.).

func (*FundsData) BondHoldings added in v0.5.0

func (f *FundsData) BondHoldings() map[string]any

BondHoldings returns the topHoldings.bondHoldings statistics.

func (*FundsData) BondRatings added in v0.5.0

func (f *FundsData) BondRatings() []map[string]any

BondRatings returns the topHoldings.bondRatings rows.

func (*FundsData) Description added in v0.5.0

func (f *FundsData) Description() string

Description returns the fund prospectus description.

func (*FundsData) EquityHoldings added in v0.5.0

func (f *FundsData) EquityHoldings() map[string]any

EquityHoldings returns the topHoldings.equityHoldings statistics.

func (*FundsData) FundOperations added in v0.5.0

func (f *FundsData) FundOperations() map[string]any

FundOperations returns the fund-operations table from fundProfile.

func (*FundsData) FundOverview added in v0.5.0

func (f *FundsData) FundOverview() map[string]any

FundOverview returns the typed overview ("family", "category", "legalType").

func (*FundsData) SectorWeightings added in v0.5.0

func (f *FundsData) SectorWeightings() []map[string]any

SectorWeightings returns the topHoldings.sectorWeightings rows.

func (*FundsData) TopHoldings added in v0.5.0

func (f *FundsData) TopHoldings() []map[string]any

TopHoldings returns the topHoldings.holdings rows.

type HistoryParams

type HistoryParams struct {
	// Period is a Yahoo range value such as Period1D, Period1Mo, Period1Y, or
	// PeriodMax. It is used only when Start and End are both zero. If empty, the
	// client defaults to Period1Mo.
	Period string
	// Interval is the candle size, for example Interval1D or Interval1H. If
	// empty, the client defaults to Interval1D.
	Interval string
	// Start is the inclusive beginning of an explicit date range. Set Start or
	// End to use period1/period2 instead of range.
	Start time.Time
	// End is the exclusive end of an explicit date range. If Start is set and
	// End is zero, the current time is used.
	End time.Time
	// PrePost includes pre-market and post-market rows when Yahoo supports them.
	PrePost bool
	// Events controls event data included by Yahoo. If empty, dividends, splits,
	// and capital gains are requested.
	Events []string
	// AutoAdjust applies Yahoo's adjusted-close ratio to Open, High, Low, and
	// Volume so OHLC are split- and dividend-adjusted. Mirrors yfinance's
	// auto_adjust=True behavior. Close becomes the adjusted close value.
	AutoAdjust bool
	// BackAdjust scales the entire history so the latest Close matches AdjClose,
	// preserving raw most-recent prices while back-adjusting older candles.
	// Mirrors yfinance's back_adjust=True behavior.
	BackAdjust bool
	// Rounding rounds OHLC to the chart meta's PriceHint number of decimals.
	// Mirrors yfinance's rounding=True behavior.
	Rounding bool
	// Repair runs a heuristic data-repair pass over the candles, fixing common
	// 100x or 0.01x price anomalies (often caused by Yahoo currency-unit
	// changes) and replacing zero-volume rows with NaN-like zero markers.
	// Mirrors yfinance's repair=True flag.
	Repair bool
	// Threads bounds concurrency in Download. Zero or negative means unlimited
	// (a goroutine per symbol). Mirrors yfinance's download(threads=N).
	Threads int
	// NoEvents suppresses dividend/split/capital-gain event requests. By
	// default Yahoo includes events when none are listed in Events.
	NoEvents bool
	// OnProgress, when non-nil, is invoked by Download once per symbol after
	// it completes (success or failure). idx is the zero-based index in the
	// input slice; total is len(symbols).
	OnProgress func(symbol string, idx, total int, err error)
	// DropNaN drops candles where every OHLC value is NaN, mirroring
	// yfinance's dropna=True behavior. Default is to keep all rows.
	DropNaN bool
}

HistoryParams controls chart downloads.

type HistoryResult

type HistoryResult struct {
	Symbol  string
	Meta    ChartMeta
	Candles []Candle
	// YahooErr is set when Yahoo returned a structured chart error. The same
	// error is also returned from History.
	YahooErr *YahooError
}

HistoryResult contains candles and response metadata for one symbol.

type IndustryData added in v0.5.0

type IndustryData struct {
	Key        string
	Name       string
	SectorKey  string
	SectorName string
	Raw        map[string]any
}

IndustryData contains typed views over a Yahoo /v1/finance/industries response.

func (*IndustryData) KeyCompanyGroups added in v0.5.0

func (i *IndustryData) KeyCompanyGroups() []map[string]any

KeyCompanyGroups returns the industry's labelled company groups.

func (*IndustryData) KeyCompanyKeys added in v0.5.0

func (i *IndustryData) KeyCompanyKeys() []string

KeyCompanyKeys returns the industry's `key_company_keys` symbol list.

func (*IndustryData) Overview added in v0.5.0

func (i *IndustryData) Overview() map[string]any

Overview returns the industry's overview block.

func (*IndustryData) TopGrowthCompanies added in v0.5.0

func (i *IndustryData) TopGrowthCompanies() []map[string]any

TopGrowthCompanies returns the industry's top-growth-companies rows.

func (*IndustryData) TopPerformingCompanies added in v0.5.0

func (i *IndustryData) TopPerformingCompanies() []map[string]any

TopPerformingCompanies returns the industry's top-performing-companies rows.

type Limiter added in v0.5.0

type Limiter interface {
	Wait(ctx context.Context) error
}

Limiter is the minimal interface a request-rate limiter must implement. It is satisfied by *RateLimiter in this package and by golang.org/x/time/rate.Limiter.

type Market added in v0.4.0

type Market struct {
	Name string
	// contains filtered or unexported fields
}

Market is a market-scoped helper for summary and status data.

func (*Market) Status added in v0.4.0

func (m *Market) Status(ctx context.Context) (map[string]any, error)

Status fetches market status/time data.

func (*Market) Summary added in v0.4.0

func (m *Market) Summary(ctx context.Context) (map[string]any, error)

Summary fetches market summary data.

type MemoryCache added in v0.5.0

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache is a simple in-process Cache. The zero value is unusable; use NewMemoryCache. Entries with TTL <= 0 never expire.

func NewMemoryCache added in v0.5.0

func NewMemoryCache() *MemoryCache

NewMemoryCache returns a ready-to-use MemoryCache.

func (*MemoryCache) Get added in v0.5.0

func (m *MemoryCache) Get(key string) ([]byte, bool)

Get returns the cached value if present and not expired.

func (*MemoryCache) Set added in v0.5.0

func (m *MemoryCache) Set(key string, value []byte, ttl time.Duration)

Set stores value under key. ttl <= 0 means no expiry.

type OptionChain

type OptionChain struct {
	Symbol string
	// Underlying is Yahoo's raw quote object for the underlying instrument.
	Underlying map[string]any
	// ExpirationDate is the expiration represented by Calls and Puts.
	ExpirationDate time.Time
	// Expirations lists all expiration dates Yahoo returned for the symbol.
	Expirations []time.Time
	Strikes     []float64
	Calls       []OptionContract
	Puts        []OptionContract
}

OptionChain contains calls and puts for one expiration date.

type OptionContract

type OptionContract struct {
	ContractSymbol string
	Strike         float64
	Currency       string
	LastPrice      float64
	Change         float64
	PercentChange  float64
	Volume         int64
	OpenInterest   int64
	Bid            float64
	Ask            float64
	ContractSize   string
	Expiration     time.Time
	LastTradeDate  time.Time
	// ImpliedVolatility is the decimal volatility returned by Yahoo, e.g. 0.25
	// for 25%.
	ImpliedVolatility float64
	InTheMoney        bool
}

OptionContract is an option row returned by Yahoo.

type Quote added in v0.3.0

type Quote struct {
	Symbol                     string
	ShortName                  string
	LongName                   string
	QuoteType                  string
	Exchange                   string
	Currency                   string
	Market                     string
	MarketState                string
	RegularMarketPrice         float64
	RegularMarketChange        float64
	RegularMarketChangePercent float64
	RegularMarketVolume        int64
	Raw                        map[string]any
}

Quote is one row returned by Yahoo's v7 quote endpoint.

type RateLimiter added in v0.5.0

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter is a minimal token-bucket limiter satisfying Limiter. It produces tokens at a steady rate and supports a burst capacity. The zero value is unusable; use NewRateLimiter.

func NewRateLimiter added in v0.5.0

func NewRateLimiter(requestsPerSecond float64, burst int) *RateLimiter

NewRateLimiter returns a limiter that allows requests at requestsPerSecond with the given burst size (minimum 1). A zero or negative rate disables rate limiting and Wait returns immediately.

func (*RateLimiter) Wait added in v0.5.0

func (r *RateLimiter) Wait(ctx context.Context) error

Wait blocks until a token is available or ctx is cancelled. When the limiter's rate is zero or negative, Wait returns immediately.

type ScreenRequest added in v0.3.0

type ScreenRequest struct {
	Offset     int            `json:"offset,omitempty"`
	Count      int            `json:"count,omitempty"`
	Size       int            `json:"size,omitempty"`
	SortField  string         `json:"sortField,omitempty"`
	SortType   string         `json:"sortType,omitempty"`
	QuoteType  string         `json:"quoteType,omitempty"`
	Query      map[string]any `json:"query,omitempty"`
	UserID     string         `json:"userId,omitempty"`
	UserIDType string         `json:"userIdType,omitempty"`
}

ScreenRequest is a Yahoo screener request body.

type ScreenerQuery added in v0.4.0

type ScreenerQuery struct {
	Operator string `json:"operator"`
	Operands []any  `json:"operands"`
}

ScreenerQuery is a composable Yahoo screener query expression.

func And added in v0.4.0

func And(filters ...ScreenerQuery) ScreenerQuery

And combines screener filters with a logical AND.

func Between added in v0.4.0

func Between(field string, low any, high any) ScreenerQuery

Between builds a between screener filter.

func Eq added in v0.4.0

func Eq(field string, value any) ScreenerQuery

Eq builds an equality screener filter.

func GT added in v0.4.0

func GT(field string, value any) ScreenerQuery

GT builds a greater-than screener filter.

func GTE added in v0.4.0

func GTE(field string, value any) ScreenerQuery

GTE builds a greater-than-or-equal screener filter.

func LT added in v0.4.0

func LT(field string, value any) ScreenerQuery

LT builds a less-than screener filter.

func LTE added in v0.4.0

func LTE(field string, value any) ScreenerQuery

LTE builds a less-than-or-equal screener filter.

func Or added in v0.4.0

func Or(filters ...ScreenerQuery) ScreenerQuery

Or combines screener filters with a logical OR.

func Screener added in v0.4.0

func Screener(operator string, operands ...any) ScreenerQuery

Screener builds a raw Yahoo screener query expression.

func (ScreenerQuery) Map added in v0.4.0

func (q ScreenerQuery) Map() map[string]any

Map converts a query expression into the raw map shape accepted by Screen.

type SearchOptions added in v0.5.0

type SearchOptions struct {
	QuotesCount                int
	NewsCount                  int
	ListsCount                 int
	EnableFuzzyQuery           *bool
	EnableEnhancedTrivialQuery *bool
	EnablePrivateCompany       *bool
	EnableNavLinks             *bool
	EnableResearchReports      *bool
	EnableCulturalAssets       *bool
	RecommendCount             int
	Region                     string
	Lang                       string
}

SearchOptions exposes the optional Yahoo search flags. yfinance forwards these as query parameters; the zero value reproduces the historical `Search(query, quotesCount, newsCount)` behavior.

type SearchResponse

type SearchResponse struct {
	Quotes []SearchResult `json:"quotes"`
	News   []any          `json:"news"`
	Raw    map[string]any `json:"-"`
}

SearchResponse contains Yahoo Finance search results.

func (*SearchResponse) All added in v0.5.0

func (r *SearchResponse) All() map[string]any

All collects every primary section into a single map keyed by section name ("quotes", "news", "lists", "researchReports"). Mirrors yfinance's Search.all.

func (*SearchResponse) Lists added in v0.5.0

func (r *SearchResponse) Lists() []map[string]any

Lists returns the "lists" block from a Yahoo search response. Mirrors yfinance's Search.lists.

func (*SearchResponse) NewsRows added in v0.5.0

func (r *SearchResponse) NewsRows() []map[string]any

NewsRows returns the news block as typed rows when Yahoo returns a list of objects. Mirrors yfinance's Search.news.

func (*SearchResponse) Research added in v0.5.0

func (r *SearchResponse) Research() []map[string]any

Research returns the "researchReports" block from a Yahoo search response. Mirrors yfinance's Search.research.

type SearchResult

type SearchResult struct {
	Symbol         string `json:"symbol"`
	ShortName      string `json:"shortname"`
	LongName       string `json:"longname"`
	QuoteType      string `json:"quoteType"`
	Exchange       string `json:"exchange"`
	Score          int    `json:"score"`
	TypeDisp       string `json:"typeDisp"`
	ExchangeDisp   string `json:"exchDisp"`
	Sector         string `json:"sector"`
	Industry       string `json:"industry"`
	IsYahooFinance bool   `json:"isYahooFinance"`
}

SearchResult is one symbol returned by Yahoo search.

type SectorData added in v0.5.0

type SectorData struct {
	Key  string
	Name string
	Raw  map[string]any
}

SectorData contains typed views over a Yahoo /v1/finance/sectors response.

The structured accessors expose the same fields that yfinance's `Sector` class surfaces (overview, top_companies, top_etfs, top_mutual_funds, industries, top_growth_companies, top_performing_companies). Use Raw for fields not promoted by this struct.

func (*SectorData) Industries added in v0.5.0

func (s *SectorData) Industries() []map[string]any

Industries returns the sector's industries breakdown.

func (*SectorData) Overview added in v0.5.0

func (s *SectorData) Overview() map[string]any

Overview returns the sector's overview block ("description", "marketCap", "marketWeight", "employeeCount", "companiesCount", etc.).

func (*SectorData) TopCompanies added in v0.5.0

func (s *SectorData) TopCompanies() []map[string]any

TopCompanies returns the rows of the sector's top-companies table.

func (*SectorData) TopETFs added in v0.5.0

func (s *SectorData) TopETFs() []map[string]any

TopETFs returns the rows of the sector's top-ETFs table.

func (*SectorData) TopGrowthCompanies added in v0.5.0

func (s *SectorData) TopGrowthCompanies() []map[string]any

TopGrowthCompanies returns the sector's top-growth-companies table.

func (*SectorData) TopMutualFunds added in v0.5.0

func (s *SectorData) TopMutualFunds() []map[string]any

TopMutualFunds returns the rows of the sector's top-mutual-funds table.

func (*SectorData) TopPerformingCompanies added in v0.5.0

func (s *SectorData) TopPerformingCompanies() []map[string]any

TopPerformingCompanies returns the sector's top-performing-companies table.

type StreamMessage added in v0.4.0

type StreamMessage struct {
	ID                  string
	Price               float64
	Time                int64
	Currency            string
	Exchange            string
	QuoteType           int64
	MarketHours         int64
	ChangePercent       float64
	DayVolume           int64
	DayHigh             float64
	DayLow              float64
	Change              float64
	ShortName           string
	ExpireDate          int64
	OpenPrice           float64
	PreviousClose       float64
	StrikePrice         float64
	UnderlyingSymbol    string
	OpenInterest        int64
	OptionsType         int64
	MiniOption          int64
	LastSize            int64
	Bid                 float64
	BidSize             int64
	Ask                 float64
	AskSize             int64
	PriceHint           int64
	Volume24Hr          int64
	VolumeAllCurrencies int64
	FromCurrency        string
	LastMarket          string
	CirculatingSupply   float64
	MarketCap           float64
	Raw                 map[string]any
}

StreamMessage is one decoded Yahoo Finance streaming price update.

func DecodeStreamMessage added in v0.4.0

func DecodeStreamMessage(data []byte) (StreamMessage, error)

DecodeStreamMessage decodes a Yahoo websocket frame. Yahoo normally sends a JSON envelope containing a base64 protobuf payload in the "message" field; plain JSON price objects are also accepted for tests and proxies.

type Ticker

type Ticker struct {
	Symbol string
	// contains filtered or unexported fields
}

Ticker is a symbol-scoped Yahoo Finance helper.

func (*Ticker) Actions added in v0.3.0

func (t *Ticker) Actions(ctx context.Context, params HistoryParams) ([]Action, error)

Actions returns dividend, capital-gains, and split events for this ticker.

func (*Ticker) Analysis added in v0.3.0

func (t *Ticker) Analysis(ctx context.Context) (map[string]any, error)

Analysis fetches yfinance-style analyst modules for this ticker.

func (*Ticker) AnalystPriceTargets added in v0.3.0

func (t *Ticker) AnalystPriceTargets(ctx context.Context) (map[string]any, error)

AnalystPriceTargets returns the raw financialData module for this ticker.

func (*Ticker) BalanceSheet added in v0.3.0

func (t *Ticker) BalanceSheet(ctx context.Context, freq string) (map[string]any, error)

func (*Ticker) Calendar added in v0.3.0

func (t *Ticker) Calendar(ctx context.Context) (map[string]any, error)

Calendar fetches Yahoo calendar events for this ticker.

func (*Ticker) CapitalGains added in v0.3.0

func (t *Ticker) CapitalGains(ctx context.Context, params HistoryParams) ([]Action, error)

CapitalGains returns capital-gains distribution events for this ticker.

func (*Ticker) CashFlow added in v0.3.0

func (t *Ticker) CashFlow(ctx context.Context, freq string) (map[string]any, error)

func (*Ticker) Dividends added in v0.3.0

func (t *Ticker) Dividends(ctx context.Context, params HistoryParams) ([]Action, error)

Dividends returns dividend events for this ticker.

func (*Ticker) EPSRevisions added in v0.4.0

func (t *Ticker) EPSRevisions(ctx context.Context) (map[string]any, error)

EPSRevisions fetches EPS revisions from Yahoo earningsTrend.

func (*Ticker) EPSTrend added in v0.4.0

func (t *Ticker) EPSTrend(ctx context.Context) (map[string]any, error)

EPSTrend fetches EPS trend data from Yahoo earningsTrend.

func (*Ticker) Earnings added in v0.4.0

func (t *Ticker) Earnings(ctx context.Context) (map[string]any, error)

Earnings fetches Yahoo earnings modules.

func (*Ticker) EarningsDates added in v0.3.0

func (t *Ticker) EarningsDates(ctx context.Context, limit int) (map[string]any, error)

EarningsDates fetches earnings calendar rows for this ticker.

func (*Ticker) EarningsEstimate added in v0.4.0

func (t *Ticker) EarningsEstimate(ctx context.Context) (map[string]any, error)

EarningsEstimate fetches earnings-estimate data from Yahoo earningsTrend.

func (*Ticker) EarningsHistory added in v0.4.0

func (t *Ticker) EarningsHistory(ctx context.Context) (map[string]any, error)

EarningsHistory fetches earnings-history data.

func (*Ticker) FastInfo

func (t *Ticker) FastInfo(ctx context.Context) (*FastInfo, error)

FastInfo returns selected price metadata from the chart endpoint.

func (*Ticker) Financials

func (t *Ticker) Financials(ctx context.Context) (map[string]any, error)

Financials fetches Yahoo quoteSummary financial statement modules.

func (*Ticker) FundProfile added in v0.3.0

func (t *Ticker) FundProfile(ctx context.Context) (map[string]any, error)

FundProfile fetches fund-specific quote summary modules for this ticker.

func (*Ticker) FundamentalsTimeseries added in v0.3.0

func (t *Ticker) FundamentalsTimeseries(ctx context.Context, types []string, start, end time.Time) (map[string]any, error)

FundamentalsTimeseries fetches raw Yahoo fundamentals timeseries types for this ticker.

func (*Ticker) FundsData added in v0.5.0

func (t *Ticker) FundsData(ctx context.Context) (*FundsData, error)

FundsData fetches fund-specific quoteSummary modules for this ticker.

func (*Ticker) GrowthEstimates added in v0.4.0

func (t *Ticker) GrowthEstimates(ctx context.Context) (map[string]any, error)

GrowthEstimates fetches stock, industry, sector, and index growth estimates.

func (*Ticker) History

func (t *Ticker) History(ctx context.Context, params HistoryParams) (*HistoryResult, error)

History downloads historical OHLCV candles for this ticker.

func (*Ticker) HistoryMetadata added in v0.4.0

func (t *Ticker) HistoryMetadata(ctx context.Context) (map[string]any, error)

HistoryMetadata fetches chart metadata for this ticker.

func (*Ticker) Holders

func (t *Ticker) Holders(ctx context.Context) (map[string]any, error)

Holders fetches institutional, fund, and insider holders modules.

func (*Ticker) ISIN added in v0.3.0

func (t *Ticker) ISIN(ctx context.Context) (string, error)

ISIN attempts to resolve this ticker's ISIN.

func (*Ticker) IncomeStatement added in v0.3.0

func (t *Ticker) IncomeStatement(ctx context.Context, freq string) (map[string]any, error)

func (*Ticker) Info

func (t *Ticker) Info(ctx context.Context) (map[string]any, error)

Info fetches the common yfinance info module set and flattens one level.

func (*Ticker) InsiderPurchases added in v0.4.0

func (t *Ticker) InsiderPurchases(ctx context.Context) (map[string]any, error)

InsiderPurchases fetches net share purchase activity.

func (*Ticker) InsiderRosterHolders added in v0.4.0

func (t *Ticker) InsiderRosterHolders(ctx context.Context) (map[string]any, error)

InsiderRosterHolders fetches insider roster/holder rows.

func (*Ticker) InsiderTransactions added in v0.4.0

func (t *Ticker) InsiderTransactions(ctx context.Context) (map[string]any, error)

InsiderTransactions fetches insider transaction rows.

func (*Ticker) InstitutionalHolders added in v0.4.0

func (t *Ticker) InstitutionalHolders(ctx context.Context) (map[string]any, error)

InstitutionalHolders fetches institutional ownership data.

func (*Ticker) MajorHolders added in v0.4.0

func (t *Ticker) MajorHolders(ctx context.Context) (map[string]any, error)

MajorHolders fetches major-holders breakdown data.

func (*Ticker) MutualFundHolders added in v0.4.0

func (t *Ticker) MutualFundHolders(ctx context.Context) (map[string]any, error)

MutualFundHolders fetches fund ownership data.

func (*Ticker) News added in v0.3.0

func (t *Ticker) News(ctx context.Context, count int, tab string) ([]map[string]any, error)

News fetches ticker news for this ticker.

func (*Ticker) Options

func (t *Ticker) Options(ctx context.Context, expiration time.Time) (*OptionChain, error)

Options fetches an option chain. Pass a zero expiration to fetch Yahoo's default expiration.

func (*Ticker) Quote added in v0.3.0

func (t *Ticker) Quote(ctx context.Context) (*Quote, error)

Quote fetches this ticker's quote row.

func (*Ticker) QuoteSummary

func (t *Ticker) QuoteSummary(ctx context.Context, modules ...string) (map[string]any, error)

QuoteSummary fetches raw quoteSummary modules for a symbol.

func (*Ticker) Recommendations

func (t *Ticker) Recommendations(ctx context.Context) (map[string]any, error)

Recommendations fetches analyst recommendation modules.

func (*Ticker) RecommendationsSummary added in v0.4.0

func (t *Ticker) RecommendationsSummary(ctx context.Context) (map[string]any, error)

RecommendationsSummary fetches Yahoo recommendation trend data.

func (*Ticker) RevenueEstimate added in v0.4.0

func (t *Ticker) RevenueEstimate(ctx context.Context) (map[string]any, error)

RevenueEstimate fetches revenue-estimate data from Yahoo earningsTrend.

func (*Ticker) SECFilings added in v0.3.0

func (t *Ticker) SECFilings(ctx context.Context) (map[string]any, error)

SECFilings fetches SEC filing metadata for this ticker.

func (*Ticker) Shares added in v0.5.0

func (t *Ticker) Shares(ctx context.Context, freq string) (map[string]any, error)

Shares fetches the quarterly or annual share-count time series for this ticker.

func (*Ticker) SharesFull added in v0.3.0

func (t *Ticker) SharesFull(ctx context.Context, start, end time.Time) (map[string]any, error)

SharesFull fetches shares-out timeseries data for this ticker.

func (*Ticker) Splits added in v0.3.0

func (t *Ticker) Splits(ctx context.Context, params HistoryParams) ([]Action, error)

Splits returns stock split events for this ticker.

func (*Ticker) Sustainability added in v0.3.0

func (t *Ticker) Sustainability(ctx context.Context) (map[string]any, error)

Sustainability fetches ESG score data for this ticker.

func (*Ticker) UpgradesDowngrades added in v0.3.0

func (t *Ticker) UpgradesDowngrades(ctx context.Context) (map[string]any, error)

UpgradesDowngrades fetches analyst upgrade/downgrade history for this ticker.

func (*Ticker) Valuation added in v0.3.0

func (t *Ticker) Valuation(ctx context.Context) (map[string]any, error)

Valuation fetches valuation-related quote summary modules for this ticker.

type Tickers added in v0.4.0

type Tickers struct {
	Symbols []string
	// contains filtered or unexported fields
}

Tickers is a multi-symbol helper similar to yfinance.Tickers.

func (*Tickers) Download added in v0.4.0

func (t *Tickers) Download(ctx context.Context, params HistoryParams) []DownloadResult

Download downloads history for all symbols in this collection.

func (*Tickers) Quotes added in v0.4.0

func (t *Tickers) Quotes(ctx context.Context) ([]Quote, error)

Quotes fetches quote rows for all symbols in this collection.

func (*Tickers) Ticker added in v0.4.0

func (t *Tickers) Ticker(symbol string) *Ticker

Ticker returns a symbol-scoped helper from this collection.

type WebSocket added in v0.4.0

type WebSocket struct {
	URL       string
	Origin    string
	UserAgent string

	// AutoReconnect enables transparent reconnection inside Listen when the
	// underlying connection drops. Re-subscribes to all known symbols after
	// each successful reconnection.
	AutoReconnect bool
	// ReconnectBackoff is the base delay between reconnection attempts; each
	// attempt doubles the prior wait, capped at 30 seconds. Defaults to 500ms.
	ReconnectBackoff time.Duration
	// MaxReconnectAttempts bounds the number of reconnection attempts per
	// drop. Zero means unlimited.
	MaxReconnectAttempts int
	// OnReconnect, when non-nil, is invoked before each reconnection attempt
	// with the attempt number (1-indexed) and the error that triggered it.
	OnReconnect func(attempt int, err error)
	// contains filtered or unexported fields
}

WebSocket streams live Yahoo Finance price updates.

func NewAsyncWebSocket added in v0.4.0

func NewAsyncWebSocket(url string) *WebSocket

NewAsyncWebSocket returns a WebSocket configured for context-driven asynchronous Listen calls.

func NewWebSocket added in v0.4.0

func NewWebSocket(url string) *WebSocket

NewWebSocket creates a streaming client. Empty url uses Yahoo's default streamer endpoint.

func (*WebSocket) Close added in v0.4.0

func (ws *WebSocket) Close() error

Close closes the websocket connection.

func (*WebSocket) Connect added in v0.4.0

func (ws *WebSocket) Connect(ctx context.Context) error

Connect opens the websocket connection.

func (*WebSocket) Listen added in v0.4.0

func (ws *WebSocket) Listen(ctx context.Context, handler func(StreamMessage)) error

Listen receives messages until the context is cancelled or Receive returns an error. The handler may be nil, in which case messages are simply decoded.

When ws.AutoReconnect is true, Listen transparently re-establishes the connection on transport errors and re-subscribes to every symbol tracked by Subscriptions().

func (*WebSocket) Subscribe added in v0.4.0

func (ws *WebSocket) Subscribe(ctx context.Context, symbols ...string) error

Subscribe subscribes to one or more symbols.

func (*WebSocket) Subscriptions added in v0.4.0

func (ws *WebSocket) Subscriptions() []string

Subscriptions returns the currently tracked subscription symbols.

func (*WebSocket) Unsubscribe added in v0.4.0

func (ws *WebSocket) Unsubscribe(ctx context.Context, symbols ...string) error

Unsubscribe unsubscribes from one or more symbols.

type YahooError

type YahooError struct {
	Code        string
	Description string
}

YahooError represents an error object returned by Yahoo Finance.

func (*YahooError) Error

func (e *YahooError) Error() string

Directories

Path Synopsis
adapter
gota
Package gota converts goyfinace results into go-gota DataFrames.
Package gota converts goyfinace results into go-gota DataFrames.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL