cache
Package cache provides an in-memory caching layer for go-yfinance.
Overview
The cache package provides a thread-safe, TTL-based in-memory cache for storing frequently accessed data like timezone mappings and ticker information.
Basic Usage
c := cache.New(cache.WithTTL(5 * time.Minute))
c.Set("AAPL:tz", "America/New_York")
if tz, ok := c.Get("AAPL:tz"); ok {
fmt.Println(tz)
}
Global Cache
A global cache instance is available for convenience:
Thread Safety
All cache operations are thread-safe and can be used from multiple goroutines.
Package cache provides an in-memory caching layer for go-yfinance.
Overview
The cache package provides a thread-safe, TTL-based in-memory cache for storing frequently accessed data like timezone mappings and ticker information.
Basic Usage
c := cache.New(cache.WithTTL(5 * time.Minute))
c.Set("AAPL:tz", "America/New_York")
if tz, ok := c.Get("AAPL:tz"); ok {
fmt.Println(tz)
}
Global Cache
A global cache instance is available for convenience:
Configuration Options
- WithTTL: Set custom TTL for cache entries (default: 5 minutes)
Automatic Cleanup
The cache automatically removes expired entries every 10 minutes to prevent memory leaks.
Thread Safety
All cache operations are thread-safe and can be used from multiple goroutines.
Index
- Constants
- func ClearGlobal()
- func DeleteGlobal(key string)
- func GetGlobal(key string) (interface{}, bool)
- func GetGlobalString(key string) (string, bool)
- func SetGlobal(key string, value interface{})
- func SetGlobalWithTTL(key string, value interface{}, ttl time.Duration)
- type Cache
- func New(opts ...Option) *Cache
- func (c *Cache) Clear()
- func (c *Cache) Close()
- func (c *Cache) Delete(key string)
- func (c *Cache) Get(key string) (interface{}, bool)
- func (c *Cache) GetString(key string) (string, bool)
- func (c *Cache) Len() int
- func (c *Cache) Set(key string, value interface{})
- func (c *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration)
- type Option
- func WithTTL(ttl time.Duration) Option
Constants
const (
// DefaultTTL is the default time-to-live for cache entries.
DefaultTTL = 5 * time.Minute
// DefaultCleanupInterval is the default interval for cleaning expired entries.
DefaultCleanupInterval = 10 * time.Minute
)
func ClearGlobal
ClearGlobal removes all entries from the global cache.
func DeleteGlobal
DeleteGlobal removes a key from the global cache.
func GetGlobal
GetGlobal retrieves a value from the global cache.
func GetGlobalString
GetGlobalString retrieves a string value from the global cache.
func SetGlobal
SetGlobal stores a value in the global cache.
func SetGlobalWithTTL
SetGlobalWithTTL stores a value in the global cache with a custom TTL.
type Cache
Cache is a thread-safe, TTL-based in-memory cache.
func New
New creates a new Cache with the given options.
func (*Cache) Clear
Clear removes all entries from the cache.
func (*Cache) Close
Close stops the cleanup goroutine and releases resources.
func (*Cache) Delete
Delete removes a key from the cache.
func (*Cache) Get
Get retrieves a value from the cache. Returns the value and true if found and not expired, otherwise nil and false.
func (*Cache) GetString
GetString retrieves a string value from the cache. Returns the value and true if found, not expired, and is a string.
func (*Cache) Len
Len returns the number of items in the cache (including expired ones).
func (*Cache) Set
Set stores a value in the cache with the default TTL.
func (*Cache) SetWithTTL
SetWithTTL stores a value in the cache with a custom TTL.
type Option
Option is a function that configures a Cache.
func WithTTL
WithTTL sets the default TTL for cache entries.
calendars
Package calendars provides Yahoo Finance economic calendar functionality.
Overview
The calendars package allows retrieving various financial calendars including earnings announcements, IPOs, economic events, and stock splits. This is useful for tracking upcoming market events and financial releases.
Basic Usage
cal, err := calendars.New()
if err != nil {
log.Fatal(err)
}
defer cal.Close()
// Get earnings calendar
earnings, err := cal.Earnings(nil)
if err != nil {
log.Fatal(err)
}
for _, e := range earnings {
fmt.Printf("%s: %s, EPS Est: %.2f\n",
e.Symbol, e.CompanyName, e.EPSEstimate)
}
Earnings Calendar
Get upcoming and recent earnings announcements:
earnings, err := cal.Earnings(&models.CalendarOptions{
Limit: 50,
})
for _, e := range earnings {
fmt.Printf("%s: Est %.2f, Actual %.2f, Surprise %.2f%%\n",
e.Symbol, e.EPSEstimate, e.EPSActual, e.SurprisePercent)
}
IPO Calendar
Get upcoming and recent IPO information:
ipos, err := cal.IPOs(nil)
for _, ipo := range ipos {
fmt.Printf("%s: %s, Price: $%.2f-$%.2f\n",
ipo.Symbol, ipo.CompanyName, ipo.PriceFrom, ipo.PriceTo)
}
Economic Events
Get economic releases and indicators:
events, err := cal.EconomicEvents(nil)
for _, e := range events {
fmt.Printf("%s (%s): Expected %.2f, Actual %.2f\n",
e.Event, e.Region, e.Expected, e.Actual)
}
Stock Splits
Get stock split events:
splits, err := cal.Splits(nil)
for _, s := range splits {
fmt.Printf("%s: %s (%s)\n",
s.Symbol, s.CompanyName, s.Ratio)
}
Custom Date Range
Specify a custom date range for calendar queries:
start := time.Now()
end := start.AddDate(0, 1, 0) // 1 month ahead
cal, err := calendars.New(calendars.WithDateRange(start, end))
// Or per-query:
earnings, err := cal.Earnings(&models.CalendarOptions{
Start: start,
End: end,
Limit: 100,
})
Calendar Options
Configure calendar queries with CalendarOptions:
opts := &models.CalendarOptions{
Start: time.Now(),
End: time.Now().AddDate(0, 0, 30),
Limit: 50, // Max results (capped at 100)
Offset: 0, // Pagination offset
}
earnings, err := cal.Earnings(opts)
Custom Client
Provide a custom HTTP client:
Thread Safety
All Calendars methods are safe for concurrent use from multiple goroutines.
Python Compatibility
This package implements the same functionality as Python yfinance's Calendars class:
Python | Go
----------------------------------------|----------------------------------------
yf.Calendars() | calendars.New()
yf.Calendars(start, end) | calendars.New(WithDateRange(start, end))
cal.get_earnings_calendar(limit) | cal.Earnings(&CalendarOptions{Limit: n})
cal.get_ipo_info_calendar() | cal.IPOs(nil)
cal.get_economic_events_calendar() | cal.EconomicEvents(nil)
cal.get_splits_calendar() | cal.Splits(nil)
cal.earnings_calendar | cal.Earnings(nil)
cal.ipo_info_calendar | cal.IPOs(nil)
cal.economic_events_calendar | cal.EconomicEvents(nil)
cal.splits_calendar | cal.Splits(nil)
Index
- type Calendars
- func New(opts ...Option) (*Calendars, error)
- func (c *Calendars) ClearCache()
- func (c *Calendars) Close()
- func (c *Calendars) Earnings(opts *models.CalendarOptions) ([]models.EarningsEvent, error)
- func (c *Calendars) EconomicEvents(opts *models.CalendarOptions) ([]models.EconomicEvent, error)
- func (c *Calendars) IPOs(opts *models.CalendarOptions) ([]models.IPOEvent, error)
- func (c *Calendars) Splits(opts *models.CalendarOptions) ([]models.CalendarSplitEvent, error)
- type Option
- func WithClient(c *client.Client) Option
- func WithDateRange(start, end time.Time) Option
type Calendars
Calendars provides access to Yahoo Finance economic calendars.
Calendars allows retrieving earnings, IPO, economic events, and stock splits data.
func New
New creates a new Calendars instance.
By default, the date range is from today to 7 days from now.
Example:
cal, err := calendars.New()
if err != nil {
log.Fatal(err)
}
defer cal.Close()
earnings, err := cal.Earnings(nil)
for _, e := range earnings {
fmt.Printf("%s: %s, EPS Est: %.2f\n", e.Symbol, e.CompanyName, e.EPSEstimate)
}
func (*Calendars) ClearCache
ClearCache clears all cached calendar data.
func (*Calendars) Close
Close releases resources used by the Calendars instance.
func (*Calendars) Earnings
Earnings retrieves the earnings calendar.
Returns upcoming and recent earnings announcements with EPS estimates.
Example:
earnings, err := cal.Earnings(nil)
if err != nil {
log.Fatal(err)
}
for _, e := range earnings {
fmt.Printf("%s: Est %.2f, Actual %.2f, Surprise %.2f%%\n",
e.Symbol, e.EPSEstimate, e.EPSActual, e.SurprisePercent)
}
func (*Calendars) EconomicEvents
EconomicEvents retrieves the economic events calendar.
Returns upcoming and recent economic releases and indicators.
Example:
events, err := cal.EconomicEvents(nil)
if err != nil {
log.Fatal(err)
}
for _, e := range events {
fmt.Printf("%s (%s): Expected %.2f, Actual %.2f\n",
e.Event, e.Region, e.Expected, e.Actual)
}
func (*Calendars) IPOs
IPOs retrieves the IPO calendar.
Returns upcoming and recent IPO information.
Example:
ipos, err := cal.IPOs(nil)
if err != nil {
log.Fatal(err)
}
for _, ipo := range ipos {
fmt.Printf("%s: %s, Price Range: $%.2f-$%.2f\n",
ipo.Symbol, ipo.CompanyName, ipo.PriceFrom, ipo.PriceTo)
}
func (*Calendars) Splits
Splits retrieves the stock splits calendar.
Returns upcoming and recent stock split events.
Example:
splits, err := cal.Splits(nil)
if err != nil {
log.Fatal(err)
}
for _, s := range splits {
fmt.Printf("%s: %s, Old: %.0f, New: %.0f\n",
s.Symbol, s.CompanyName, s.OldShareWorth, s.NewShareWorth)
}
type Option
Option is a function that configures a Calendars instance.
func WithClient
WithClient sets a custom HTTP client for the Calendars instance.
func WithDateRange
WithDateRange sets the date range for calendar queries.
client
Package client provides HTTP client functionality for Yahoo Finance API.
Package client provides HTTP client functionality for accessing Yahoo Finance API.
Overview
The client package handles all HTTP communication with Yahoo Finance servers, including TLS fingerprint spoofing using CycleTLS to avoid detection and blocking.
Authentication
Yahoo Finance API requires cookie/crumb authentication. This is handled automatically by the AuthManager which supports two strategies:
- Basic: Uses fc.yahoo.com for cookie acquisition (default)
- CSRF: Uses guce.yahoo.com consent flow (for EU users)
The AuthManager automatically falls back to the alternate strategy if one fails.
Usage
c, err := client.New(
client.WithTimeout(30),
client.WithUserAgent("Custom UA"),
)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Get("https://query2.finance.yahoo.com/v8/finance/chart/AAPL", nil)
Error Handling
The package provides typed errors via YFError for easy error handling:
See ErrorCode for all available error types.
Package client provides HTTP client functionality for Yahoo Finance API.
Index
- Variables
- func IsAuthError(err error) bool
- func IsInvalidSymbolError(err error) bool
- func IsNoDataError(err error) bool
- func IsNotFoundError(err error) bool
- func IsRateLimitError(err error) bool
- func IsTimeoutError(err error) bool
- func RandomUserAgent() string
- type AuthManager
- func NewAuthManager(client *Client) *AuthManager
- func (a *AuthManager) AddCrumbToParams(params url.Values) (url.Values, error)
- func (a *AuthManager) GetCrumb() (string, error)
- func (a *AuthManager) Reset()
- func (a *AuthManager) SwitchStrategy()
- type AuthStrategy
- type Client
- func New(opts ...ClientOption) (*Client, error)
- func (c *Client) Close()
- func (c *Client) Get(rawURL string, params url.Values) (*Response, error)
- func (c *Client) GetCookie() string
- func (c *Client) GetJSON(rawURL string, params url.Values, v interface{}) error
- func (c *Client) Post(rawURL string, params url.Values, body map[string]string) (*Response, error)
- func (c *Client) PostJSON(rawURL string, params url.Values, body []byte) (*Response, error)
- func (c *Client) SetCookie(cookie string)
- type ClientOption
- func WithJA3(ja3 string) ClientOption
- func WithTimeout(timeout int) ClientOption
- func WithUserAgent(userAgent string) ClientOption
- type ErrorCode
- type Response
- type YFError
- func HTTPStatusToError(statusCode int, body string) *YFError
- func NewError(code ErrorCode, message string, cause error) *YFError
- func WrapAuthError(err error) *YFError
- func WrapInvalidResponseError(err error) *YFError
- func WrapInvalidSymbolError(symbol string) *YFError
- func WrapNetworkError(err error) *YFError
- func WrapNoDataError(symbol string) *YFError
- func WrapNotFoundError(symbol string) *YFError
- func WrapRateLimitError() *YFError
- func WrapTimeoutError(err error) *YFError
- func (e *YFError) Error() string
- func (e *YFError) Is(target error) bool
- func (e *YFError) Unwrap() error
Variables
Predefined errors for easy comparison
var (
ErrNetwork = &YFError{Code: ErrCodeNetwork, Message: "network error"}
ErrAuth = &YFError{Code: ErrCodeAuth, Message: "authentication error"}
ErrRateLimit = &YFError{Code: ErrCodeRateLimit, Message: "rate limited"}
ErrNotFound = &YFError{Code: ErrCodeNotFound, Message: "not found"}
ErrInvalidSymbol = &YFError{Code: ErrCodeInvalidSymbol, Message: "invalid symbol"}
ErrInvalidResponse = &YFError{Code: ErrCodeInvalidResponse, Message: "invalid response"}
ErrNoData = &YFError{Code: ErrCodeNoData, Message: "no data available"}
ErrTimeout = &YFError{Code: ErrCodeTimeout, Message: "request timeout"}
)
UserAgents contains browser User-Agent strings for request rotation.
var UserAgents = []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",
}
func IsAuthError
IsAuthError checks if the error is an authentication error.
func IsInvalidSymbolError
IsInvalidSymbolError checks if the error is an invalid symbol error.
func IsNoDataError
IsNoDataError checks if the error is a no data error.
func IsNotFoundError
IsNotFoundError checks if the error is a not found error.
func IsRateLimitError
IsRateLimitError checks if the error is a rate limit error.
func IsTimeoutError
IsTimeoutError checks if the error is a timeout error.
func RandomUserAgent
RandomUserAgent returns a random User-Agent string.
type AuthManager
AuthManager handles Yahoo Finance authentication (Cookie + Crumb).
func NewAuthManager
NewAuthManager creates a new AuthManager with the given client.
func (*AuthManager) AddCrumbToParams
AddCrumbToParams adds the crumb parameter to URL values.
func (*AuthManager) GetCrumb
GetCrumb returns the current crumb, fetching it if necessary.
func (*AuthManager) Reset
Reset clears the authentication state.
func (*AuthManager) SwitchStrategy
SwitchStrategy switches to the alternate authentication strategy.
type AuthStrategy
AuthStrategy represents the authentication strategy.
const (
// StrategyBasic uses fc.yahoo.com for cookie acquisition.
StrategyBasic AuthStrategy = iota
// StrategyCSRF uses guce.yahoo.com consent flow for cookie acquisition.
StrategyCSRF
)
type Client
Client is the HTTP client for Yahoo Finance API with TLS fingerprint spoofing.
func New
New creates a new Client with optional configuration. The underlying CycleTLS client is lazily initialized on first request.
func (*Client) Close
Close closes the CycleTLS client.
func (*Client) Get
Get performs an HTTP GET request.
func (*Client) GetCookie
GetCookie returns the current cookie.
func (*Client) GetJSON
GetJSON performs an HTTP GET request and unmarshals the JSON response.
func (*Client) Post
Post performs an HTTP POST request with form data.
func (*Client) PostJSON
PostJSON performs an HTTP POST request with JSON body.
func (*Client) SetCookie
SetCookie sets the cookie for subsequent requests.
type ClientOption
ClientOption is a function that configures a Client.
func WithJA3
WithJA3 sets a custom JA3 fingerprint.
func WithTimeout
WithTimeout sets the request timeout in seconds.
func WithUserAgent
WithUserAgent sets a custom User-Agent.
type ErrorCode
ErrorCode represents the type of error.
const (
// ErrCodeUnknown is an unknown error.
ErrCodeUnknown ErrorCode = iota
// ErrCodeNetwork is a network-related error.
ErrCodeNetwork
// ErrCodeAuth is an authentication error.
ErrCodeAuth
// ErrCodeRateLimit is a rate limiting error (HTTP 429).
ErrCodeRateLimit
// ErrCodeNotFound is a not found error (HTTP 404).
ErrCodeNotFound
// ErrCodeInvalidSymbol is an invalid ticker symbol error.
ErrCodeInvalidSymbol
// ErrCodeInvalidResponse is an invalid response format error.
ErrCodeInvalidResponse
// ErrCodeNoData is a no data available error.
ErrCodeNoData
// ErrCodeTimeout is a request timeout error.
ErrCodeTimeout
)
type Response
Response represents an HTTP response.
type YFError
YFError represents a Yahoo Finance API error.
func HTTPStatusToError
HTTPStatusToError converts an HTTP status code to an appropriate error.
func NewError
NewError creates a new YFError.
func WrapAuthError
WrapAuthError wraps an error as an authentication error.
func WrapInvalidResponseError
WrapInvalidResponseError wraps an error as an invalid response error.
func WrapInvalidSymbolError
WrapInvalidSymbolError creates an invalid symbol error.
func WrapNetworkError
WrapNetworkError wraps an error as a network error.
func WrapNoDataError
WrapNoDataError creates a no data error for a symbol.
func WrapNotFoundError
WrapNotFoundError creates a not found error for a symbol.
func WrapRateLimitError
WrapRateLimitError creates a rate limit error.
func WrapTimeoutError
WrapTimeoutError wraps an error as a timeout error.
func (*YFError) Error
Error implements the error interface.
func (*YFError) Is
Is reports whether the error matches the target.
func (*YFError) Unwrap
Unwrap returns the underlying error.
config
Package config provides configuration management for go-yfinance.
Package config provides configuration management for go-yfinance.
Overview
The config package provides a centralized way to configure go-yfinance behavior. It supports both global configuration via Get and per-instance configuration via NewDefault.
Global Configuration
import "github.com/wnjoon/go-yfinance/pkg/config"
// Get global config and modify settings
config.Get().
SetTimeout(60 * time.Second).
SetProxy("http://proxy:8080").
SetDebug(true)
Available Settings
HTTP Client:
- Timeout: Request timeout duration
- UserAgent: Custom User-Agent string
- JA3: TLS fingerprint for spoofing
- ProxyURL: HTTP/HTTPS proxy URL
Rate Limiting:
- MaxRetries: Maximum retry attempts
- RetryDelay: Delay between retries
- MaxConcurrent: Maximum concurrent requests
Caching:
- CacheEnabled: Enable/disable response caching
- CacheTTL: Cache time-to-live duration
Debug:
- Debug: Enable debug logging
Thread Safety
All Config methods are safe for concurrent use.
Reset
Use Reset to restore global configuration to defaults:
Index
- Constants
- func Reset()
- type Config
- func Get() *Config
- func NewDefault() *Config
- func (c *Config) Clone() *Config
- func (c *Config) DisableCache() *Config
- func (c *Config) EnableCache(ttl time.Duration) *Config
- func (c *Config) GetJA3() string
- func (c *Config) GetProxyURL() string
- func (c *Config) GetTimeout() time.Duration
- func (c *Config) GetUserAgent() string
- func (c *Config) IsCacheEnabled() bool
- func (c *Config) IsDebug() bool
- func (c *Config) SetDebug(debug bool) *Config
- func (c *Config) SetJA3(ja3 string) *Config
- func (c *Config) SetMaxConcurrent(n int) *Config
- func (c *Config) SetMaxRetries(n int) *Config
- func (c *Config) SetProxy(proxyURL string) *Config
- func (c *Config) SetRetryDelay(d time.Duration) *Config
- func (c *Config) SetTimeout(d time.Duration) *Config
- func (c *Config) SetUserAgent(ua string) *Config
Constants
const (
DefaultTimeout = 30 * time.Second
DefaultMaxRetries = 3
DefaultRetryDelay = 1 * time.Second
DefaultMaxConcurrent = 10
DefaultCacheTTL = 5 * time.Minute
)
Default JA3 fingerprint (Chrome)
const DefaultJA3 = "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513,29-23-24,0"
func Reset
Reset resets the global configuration to defaults.
type Config
Config holds the global configuration for go-yfinance.
type Config struct {
// HTTP Client settings
Timeout time.Duration
UserAgent string
JA3 string
// Proxy settings
ProxyURL string
// Rate limiting
MaxRetries int
RetryDelay time.Duration
MaxConcurrent int
// Cache settings
CacheEnabled bool
CacheTTL time.Duration
// Debug settings
Debug bool
// contains filtered or unexported fields
}
func Get
Get returns the global configuration instance.
func NewDefault
NewDefault creates a new Config with default values.
func (*Config) Clone
Clone creates a copy of the configuration.
func (*Config) DisableCache
DisableCache disables response caching.
func (*Config) EnableCache
EnableCache enables response caching.
func (*Config) GetJA3
GetJA3 returns the JA3 fingerprint.
func (*Config) GetProxyURL
GetProxyURL returns the proxy URL.
func (*Config) GetTimeout
GetTimeout returns the timeout value.
func (*Config) GetUserAgent
GetUserAgent returns the User-Agent string.
func (*Config) IsCacheEnabled
IsCacheEnabled returns whether caching is enabled.
func (*Config) IsDebug
IsDebug returns whether debug mode is enabled.
func (*Config) SetDebug
SetDebug enables or disables debug mode.
func (*Config) SetJA3
SetJA3 sets the JA3 TLS fingerprint.
func (*Config) SetMaxConcurrent
SetMaxConcurrent sets the maximum concurrent requests.
func (*Config) SetMaxRetries
SetMaxRetries sets the maximum number of retries.
func (*Config) SetProxy
SetProxy sets the proxy URL.
func (*Config) SetRetryDelay
SetRetryDelay sets the delay between retries.
func (*Config) SetTimeout
SetTimeout sets the HTTP request timeout.
func (*Config) SetUserAgent
SetUserAgent sets the User-Agent string.
industry
Package industry provides Yahoo Finance industry data functionality.
Overview
The industry package allows retrieving financial industry information including overview data, top companies, sector information, top performing companies, and top growth companies. This is useful for industry-based analysis and screening.
Basic Usage
i, err := industry.New("semiconductors")
if err != nil {
log.Fatal(err)
}
defer i.Close()
// Get industry overview
overview, err := i.Overview()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Companies: %d\n", overview.CompaniesCount)
fmt.Printf("Market Cap: $%.2f\n", overview.MarketCap)
Sector Information
Get the parent sector of an industry:
sectorKey, err := i.SectorKey()
sectorName, err := i.SectorName()
fmt.Printf("Part of: %s (%s)\n", sectorName, sectorKey)
Top Performing Companies
Get companies with highest year-to-date returns:
companies, err := i.TopPerformingCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: YTD %.2f%%, Target: $%.2f\n",
c.Symbol, c.YTDReturn*100, c.TargetPrice)
}
Top Growth Companies
Get companies with highest growth estimates:
companies, err := i.TopGrowthCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: Growth Estimate: %.2f%%\n",
c.Symbol, c.GrowthEstimate*100)
}
Predefined Industries
Common industry identifiers are available as constants:
i, _ := industry.NewWithPredefined(models.IndustrySemiconductors)
i, _ := industry.NewWithPredefined(models.IndustryBiotechnology)
i, _ := industry.NewWithPredefined(models.IndustryBanksDiversified)
Available predefined industries (grouped by sector):
Technology:
- IndustrySemiconductors
- IndustrySoftwareInfrastructure
- IndustrySoftwareApplication
- IndustryConsumerElectronics
- IndustryComputerHardware
Healthcare:
- IndustryBiotechnology
- IndustryDrugManufacturersGeneral
- IndustryMedicalDevices
- IndustryHealthcarePlans
Financial Services:
- IndustryBanksDiversified
- IndustryBanksRegional
- IndustryAssetManagement
- IndustryCapitalMarkets
Energy:
- IndustryOilGasIntegrated
- IndustryOilGasEP
- IndustryOilGasMidstream
Caching
Industry data is cached after the first fetch. To refresh:
Custom Client
Provide a custom HTTP client:
Thread Safety
All Industry methods are safe for concurrent use from multiple goroutines.
Python Compatibility
This package implements the same functionality as Python yfinance's Industry class:
Python | Go
------------------------------------|------------------------------------
yf.Industry("semiconductors") | industry.New("semiconductors")
industry.key | i.Key()
industry.name | i.Name()
industry.symbol | i.Symbol()
industry.sector_key | i.SectorKey()
industry.sector_name | i.SectorName()
industry.overview | i.Overview()
industry.top_companies | i.TopCompanies()
industry.top_performing_companies | i.TopPerformingCompanies()
industry.top_growth_companies | i.TopGrowthCompanies()
industry.research_reports | i.ResearchReports()
Index
- type Industry
- func New(key string, opts ...Option) (*Industry, error)
- func NewWithPredefined(ind models.PredefinedIndustry, opts ...Option) (*Industry, error)
- func (i *Industry) ClearCache()
- func (i *Industry) Close()
- func (i *Industry) Data() (*models.IndustryData, error)
- func (i *Industry) Key() string
- func (i *Industry) Name() (string, error)
- func (i *Industry) Overview() (models.IndustryOverview, error)
- func (i *Industry) ResearchReports() ([]models.ResearchReport, error)
- func (i *Industry) SectorKey() (string, error)
- func (i *Industry) SectorName() (string, error)
- func (i *Industry) Symbol() (string, error)
- func (i *Industry) TopCompanies() ([]models.IndustryTopCompany, error)
- func (i *Industry) TopGrowthCompanies() ([]models.GrowthCompany, error)
- func (i *Industry) TopPerformingCompanies() ([]models.PerformingCompany, error)
- type Option
- func WithClient(c *client.Client) Option
type Industry
Industry provides access to financial industry data from Yahoo Finance.
Industry allows retrieving industry-related information such as overview, top companies, sector information, and performing/growth companies.
func New
New creates a new Industry instance for the given industry key.
Industry keys are lowercase with hyphens, e.g., "semiconductors", "software-infrastructure". Use predefined constants from models package for convenience.
Example:
i, err := industry.New("semiconductors")
if err != nil {
log.Fatal(err)
}
defer i.Close()
overview, err := i.Overview()
fmt.Printf("Industry has %d companies\n", overview.CompaniesCount)
func NewWithPredefined
NewWithPredefined creates a new Industry instance using a predefined industry constant.
Example:
i, err := industry.NewWithPredefined(models.IndustrySemiconductors)
if err != nil {
log.Fatal(err)
}
func (*Industry) ClearCache
ClearCache clears the cached industry data. The next call to any data method will fetch fresh data.
func (*Industry) Close
Close releases resources used by the Industry instance.
func (*Industry) Data
Data returns all industry data.
This fetches and returns the complete industry information including overview, top companies, sector info, and performing/growth companies.
Example:
data, err := i.Data()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Industry: %s in Sector: %s\n", data.Name, data.SectorName)
func (*Industry) Key
Key returns the industry key.
func (*Industry) Name
Name returns the industry name.
Example:
func (*Industry) Overview
Overview returns the industry overview information.
Example:
overview, err := i.Overview()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Companies: %d\n", overview.CompaniesCount)
fmt.Printf("Market Cap: $%.2f\n", overview.MarketCap)
func (*Industry) ResearchReports
ResearchReports returns research reports for the industry.
Example:
reports, err := i.ResearchReports()
if err != nil {
log.Fatal(err)
}
for _, r := range reports {
fmt.Printf("%s: %s\n", r.Provider, r.Title)
}
func (*Industry) SectorKey
SectorKey returns the key of the parent sector.
Example:
func (*Industry) SectorName
SectorName returns the name of the parent sector.
Example:
func (*Industry) Symbol
Symbol returns the industry symbol.
func (*Industry) TopCompanies
TopCompanies returns the top companies in the industry.
Example:
companies, err := i.TopCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: %s (Weight: %.2f%%)\n",
c.Symbol, c.Name, c.MarketWeight*100)
}
func (*Industry) TopGrowthCompanies
TopGrowthCompanies returns the top growth companies in the industry.
Returns companies with highest growth estimates.
Example:
companies, err := i.TopGrowthCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: YTD %.2f%%, Growth Estimate: %.2f%%\n",
c.Symbol, c.YTDReturn*100, c.GrowthEstimate*100)
}
func (*Industry) TopPerformingCompanies
TopPerformingCompanies returns the top performing companies in the industry.
Returns companies with highest year-to-date returns.
Example:
companies, err := i.TopPerformingCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: YTD %.2f%%, Last: $%.2f, Target: $%.2f\n",
c.Symbol, c.YTDReturn*100, c.LastPrice, c.TargetPrice)
}
type Option
Option is a function that configures an Industry instance.
func WithClient
WithClient sets a custom HTTP client for the Industry instance.
live
Package live provides real-time WebSocket streaming for Yahoo Finance data.
Overview
The live package enables real-time price updates via Yahoo Finance's WebSocket streaming API. Messages are delivered as protobuf-encoded pricing data and decoded into [models.PricingData] structs.
Basic Usage
ws, err := live.New()
if err != nil {
log.Fatal(err)
}
defer ws.Close()
// Subscribe to symbols
ws.Subscribe([]string{"AAPL", "MSFT", "GOOGL"})
// Listen for updates
ws.Listen(func(data *models.PricingData) {
fmt.Printf("%s: $%.2f (%.2f%%)\n",
data.ID, data.Price, data.ChangePercent)
})
Async Listening
For non-blocking operation, use ListenAsync:
ws.Subscribe([]string{"AAPL"})
ws.ListenAsync(func(data *models.PricingData) {
fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})
// Do other work...
time.Sleep(10 * time.Second)
ws.Close()
Error Handling
Set an error handler to receive connection errors:
ws, _ := live.New(
live.WithErrorHandler(func(err error) {
log.Printf("WebSocket error: %v", err)
}),
)
Configuration Options
- WithURL: Set custom WebSocket URL
- WithHeartbeatInterval: Set heartbeat interval (default 15s)
- WithReconnectDelay: Set reconnection delay (default 3s)
- WithErrorHandler: Set error callback
Data Fields
The [models.PricingData] struct contains real-time market data:
- ID: Ticker symbol
- Price: Current price
- Change: Price change from previous close
- ChangePercent: Percentage change
- DayHigh, DayLow: Day's high and low
- DayVolume: Trading volume
- Bid, Ask: Current bid/ask prices
- MarketHours: Market state (pre/regular/post/closed)
Thread Safety
All WebSocket methods are safe for concurrent use from multiple goroutines.
Package live provides real-time WebSocket streaming for Yahoo Finance data.
Overview
The live package enables real-time price updates via Yahoo Finance's WebSocket streaming API. Messages are delivered as protobuf-encoded pricing data.
Basic Usage
ws, err := live.New()
if err != nil {
log.Fatal(err)
}
defer ws.Close()
// Subscribe to symbols
ws.Subscribe([]string{"AAPL", "MSFT", "GOOGL"})
// Listen for updates
ws.Listen(func(data *models.PricingData) {
fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})
With Ticker Integration
ticker, _ := ticker.New("AAPL")
ticker.Live(func(data *models.PricingData) {
fmt.Printf("Price: $%.2f\n", data.Price)
})
Thread Safety
All WebSocket methods are safe for concurrent use from multiple goroutines.
Index
- Constants
- type ErrorHandler
- type MessageHandler
- type Option
- func WithErrorHandler(handler ErrorHandler) Option
- func WithHeartbeatInterval(d time.Duration) Option
- func WithReconnectDelay(d time.Duration) Option
- func WithURL(url string) Option
- type WebSocket
- func New(opts ...Option) (*WebSocket, error)
- func (ws *WebSocket) Close() error
- func (ws *WebSocket) Connect() error
- func (ws *WebSocket) IsConnected() bool
- func (ws *WebSocket) Listen(handler MessageHandler) error
- func (ws *WebSocket) ListenAsync(handler MessageHandler) error
- func (ws *WebSocket) Subscribe(symbols []string) error
- func (ws *WebSocket) Subscriptions() []string
- func (ws *WebSocket) Unsubscribe(symbols []string) error
Constants
const (
// DefaultURL is the Yahoo Finance WebSocket endpoint.
DefaultURL = "wss://streamer.finance.yahoo.com/?version=2"
// DefaultHeartbeatInterval is the interval for re-sending subscriptions.
DefaultHeartbeatInterval = 15 * time.Second
// DefaultReconnectDelay is the delay before attempting reconnection.
DefaultReconnectDelay = 3 * time.Second
)
type ErrorHandler
ErrorHandler is a callback function for handling errors.
type MessageHandler
MessageHandler is a callback function for handling pricing data.
type Option
Option is a function that configures a WebSocket.
func WithErrorHandler
WithErrorHandler sets the error handler callback.
func WithHeartbeatInterval
WithHeartbeatInterval sets the heartbeat interval.
func WithReconnectDelay
WithReconnectDelay sets the reconnection delay.
func WithURL
WithURL sets a custom WebSocket URL.
type WebSocket
WebSocket represents a WebSocket client for Yahoo Finance streaming.
func New
New creates a new WebSocket client.
Example:
func (*WebSocket) Close
Close closes the WebSocket connection.
func (*WebSocket) Connect
Connect establishes the WebSocket connection.
func (*WebSocket) IsConnected
IsConnected returns true if the WebSocket is connected.
func (*WebSocket) Listen
Listen starts listening for messages and calls the handler for each message. This method blocks until Close() is called or an unrecoverable error occurs.
Example:
func (*WebSocket) ListenAsync
ListenAsync starts listening in a separate goroutine. Returns immediately. Use Close() to stop listening.
Example:
ws.ListenAsync(func(data *models.PricingData) {
fmt.Printf("%s: $%.2f\n", data.ID, data.Price)
})
// ... do other work ...
ws.Close()
func (*WebSocket) Subscribe
Subscribe adds symbols to the subscription list and sends subscribe message.
Example:
func (*WebSocket) Subscriptions
Subscriptions returns the current list of subscribed symbols.
func (*WebSocket) Unsubscribe
Unsubscribe removes symbols from the subscription list.
Example:
lookup
Package lookup provides Yahoo Finance ticker lookup functionality.
Overview
The lookup package allows searching for financial instruments (stocks, ETFs, mutual funds, indices, futures, currencies, and cryptocurrencies) by query string. This is useful for finding ticker symbols when you know the company name or a partial symbol.
Unlike the search package which provides general search across news, lists, and research, lookup is specifically designed for finding ticker symbols with optional filtering by instrument type.
Basic Usage
l, err := lookup.New("Apple")
if err != nil {
log.Fatal(err)
}
defer l.Close()
// Get all matching instruments
results, err := l.All(10)
if err != nil {
log.Fatal(err)
}
for _, doc := range results {
fmt.Printf("%s: %s (%s)\n", doc.Symbol, doc.Name, doc.QuoteType)
}
Filtering by Type
You can filter results by specific instrument types:
// Get only stocks
stocks, err := l.Stock(10)
// Get only ETFs
etfs, err := l.ETF(10)
// Get only mutual funds
funds, err := l.MutualFund(10)
// Get only indices
indices, err := l.Index(10)
// Get only futures
futures, err := l.Future(10)
// Get only currencies
currencies, err := l.Currency(10)
// Get only cryptocurrencies
cryptos, err := l.Cryptocurrency(10)
Pricing Data
By default, lookup results include real-time pricing data such as:
- RegularMarketPrice: Current market price
- RegularMarketChange: Price change
- RegularMarketChangePercent: Percentage change
- RegularMarketVolume: Trading volume
- MarketCap: Market capitalization
- FiftyTwoWeekHigh/Low: 52-week price range
Caching
Lookup results are cached per query/type combination. To clear the cache:
Custom Client
You can provide a custom HTTP client for the Lookup instance:
Thread Safety
All Lookup methods are safe for concurrent use from multiple goroutines.
Python Compatibility
This package implements the same functionality as Python yfinance's Lookup class:
Python | Go
----------------------------|---------------------------
yf.Lookup("AAPL") | lookup.New("AAPL")
lookup.get_all(count=10) | l.All(10)
lookup.get_stock(count=10) | l.Stock(10)
lookup.get_etf(count=10) | l.ETF(10)
lookup.get_mutualfund(10) | l.MutualFund(10)
lookup.get_index(count=10) | l.Index(10)
lookup.get_future(count=10) | l.Future(10)
lookup.get_currency(10) | l.Currency(10)
lookup.get_cryptocurrency() | l.Cryptocurrency(10)
Index
- type Lookup
- func New(query string, opts ...Option) (*Lookup, error)
- func (l *Lookup) All(count int) ([]models.LookupDocument, error)
- func (l *Lookup) ClearCache()
- func (l *Lookup) Close()
- func (l *Lookup) Cryptocurrency(count int) ([]models.LookupDocument, error)
- func (l *Lookup) Currency(count int) ([]models.LookupDocument, error)
- func (l *Lookup) ETF(count int) ([]models.LookupDocument, error)
- func (l *Lookup) Future(count int) ([]models.LookupDocument, error)
- func (l *Lookup) Index(count int) ([]models.LookupDocument, error)
- func (l *Lookup) MutualFund(count int) ([]models.LookupDocument, error)
- func (l *Lookup) Query() string
- func (l *Lookup) Stock(count int) ([]models.LookupDocument, error)
- type Option
- func WithClient(c *client.Client) Option
type Lookup
Lookup provides Yahoo Finance ticker lookup functionality.
Lookup allows searching for financial instruments by query string, with optional filtering by instrument type.
func New
New creates a new Lookup instance for the given query.
The query can be a ticker symbol, company name, or partial match.
Example:
l, err := lookup.New("AAPL")
if err != nil {
log.Fatal(err)
}
defer l.Close()
results, err := l.All(10)
for _, doc := range results {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) All
All returns all types of financial instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
results, err := l.All(10)
for _, doc := range results {
fmt.Printf("%s: %s (%s)\n", doc.Symbol, doc.Name, doc.QuoteType)
}
func (*Lookup) ClearCache
ClearCache clears the cached lookup results.
func (*Lookup) Close
Close releases resources used by the Lookup instance.
func (*Lookup) Cryptocurrency
Cryptocurrency returns cryptocurrency instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
cryptos, err := l.Cryptocurrency(10)
for _, doc := range cryptos {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) Currency
Currency returns currency instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
currencies, err := l.Currency(10)
for _, doc := range currencies {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) ETF
ETF returns ETF instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
func (*Lookup) Future
Future returns futures instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
futures, err := l.Future(10)
for _, doc := range futures {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) Index
Index returns index instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
indices, err := l.Index(10)
for _, doc := range indices {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) MutualFund
MutualFund returns mutual fund instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
funds, err := l.MutualFund(10)
for _, doc := range funds {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
func (*Lookup) Query
Query returns the search query string.
func (*Lookup) Stock
Stock returns equity/stock instruments matching the query.
Parameters:
- count: Maximum number of results to return (default 25 if \<= 0)
Example:
stocks, err := l.Stock(10)
for _, doc := range stocks {
fmt.Printf("%s: %s\n", doc.Symbol, doc.Name)
}
type Option
Option is a function that configures a Lookup instance.
func WithClient
WithClient sets a custom HTTP client for the Lookup instance.
market
Package market provides Yahoo Finance market status and summary functionality.
Overview
The market package allows retrieving market trading hours, timezone information, and summary data for major market indices. This is useful for determining market state and getting an overview of major indices like S&P 500, Dow Jones, etc.
Basic Usage
m, err := market.New("us_market")
if err != nil {
log.Fatal(err)
}
defer m.Close()
// Get market status (opening/closing times)
status, err := m.Status()
if err != nil {
log.Fatal(err)
}
if status.Open != nil {
fmt.Printf("Market opens at: %s\n", status.Open.Format("15:04"))
}
fmt.Printf("Timezone: %s\n", status.Timezone.Short)
Market Summary
Get an overview of major market indices:
summary, err := m.Summary()
if err != nil {
log.Fatal(err)
}
for exchange, item := range summary {
fmt.Printf("%s: %.2f (%.2f%%)\n",
item.ShortName,
item.RegularMarketPrice,
item.RegularMarketChangePercent)
}
Predefined Markets
Common market identifiers are available as constants:
m, _ := market.NewWithPredefined(models.MarketUS) // US market
m, _ := market.NewWithPredefined(models.MarketJP) // Japan market
m, _ := market.NewWithPredefined(models.MarketGB) // UK market
Available predefined markets:
- MarketUS: United States
- MarketGB: United Kingdom
- MarketDE: Germany
- MarketFR: France
- MarketJP: Japan
- MarketHK: Hong Kong
- MarketCN: China
- MarketCA: Canada
- MarketAU: Australia
- MarketIN: India
- MarketKR: Korea
- MarketBR: Brazil
Market State
Check if the market is currently open:
Caching
Market data is cached after the first fetch. To refresh:
Custom Client
Provide a custom HTTP client:
Thread Safety
All Market methods are safe for concurrent use from multiple goroutines.
Python Compatibility
This package implements the same functionality as Python yfinance's Market class:
Python | Go
------------------------|---------------------------
yf.Market("us_market") | market.New("us_market")
market.status | m.Status()
market.summary | m.Summary()
Index
- type Market
- func New(market string, opts ...Option) (*Market, error)
- func NewWithPredefined(market models.PredefinedMarket, opts ...Option) (*Market, error)
- func (m *Market) ClearCache()
- func (m *Market) Close()
- func (m *Market) IsOpen() (bool, error)
- func (m *Market) Market() string
- func (m *Market) Status() (*models.MarketStatus, error)
- func (m *Market) Summary() (models.MarketSummary, error)
- type Option
- func WithClient(c *client.Client) Option
type Market
Market provides access to market status and summary information.
Market allows retrieving market opening/closing times, timezone information, and summary data for major market indices.
func New
New creates a new Market instance for the given market identifier.
Common market identifiers:
- "us_market" - United States
- "gb_market" - United Kingdom
- "de_market" - Germany
- "jp_market" - Japan
- "hk_market" - Hong Kong
- "cn_market" - China
Example:
m, err := market.New("us_market")
if err != nil {
log.Fatal(err)
}
defer m.Close()
status, err := m.Status()
fmt.Printf("Market opens at: %s\n", status.Open.Format("15:04"))
func NewWithPredefined
NewWithPredefined creates a new Market instance using a predefined market constant.
Example:
func (*Market) ClearCache
ClearCache clears the cached market data. The next call to Status() or Summary() will fetch fresh data.
func (*Market) Close
Close releases resources used by the Market instance.
func (*Market) IsOpen
IsOpen returns true if the market is currently open. This is determined by checking if the current time is between open and close times.
func (*Market) Market
Market returns the market identifier string.
func (*Market) Status
Status returns the current market status including opening/closing times.
Example:
status, err := m.Status()
if err != nil {
log.Fatal(err)
}
if status.Open != nil {
fmt.Printf("Opens at: %s\n", status.Open.Format("15:04"))
}
if status.Timezone != nil {
fmt.Printf("Timezone: %s\n", status.Timezone.Short)
}
func (*Market) Summary
Summary returns the market summary with major indices data.
The result is a map where keys are exchange codes (e.g., "SNP", "DJI") and values contain price and change information.
Example:
summary, err := m.Summary()
if err != nil {
log.Fatal(err)
}
for exchange, item := range summary {
fmt.Printf("%s (%s): %.2f (%.2f%%)\n",
item.ShortName, exchange,
item.RegularMarketPrice,
item.RegularMarketChangePercent)
}
type Option
Option is a function that configures a Market instance.
func WithClient
WithClient sets a custom HTTP client for the Market instance.
models
Package models provides data structures for Yahoo Finance API responses.
Package models provides data structures for Yahoo Finance API responses.
Package models provides data structures for Yahoo Finance API responses.
Overview
The models package defines all the data types used throughout go-yfinance. These types represent the structured data returned by Yahoo Finance APIs.
Core Types
Quote and Price Data:
- Quote: Real-time quote data including price, volume, and market state
- FastInfo: Quick-access subset of quote/info data
- Bar: Single OHLCV candlestick bar
- History: Historical price data as a collection of bars
Company Information:
- Info: Comprehensive company information and statistics
- Officer: Company officer/executive information
Options:
- Option: Single option contract (call or put)
- OptionChain: Complete option chain with calls and puts
- OptionsData: All expiration dates and strikes
Financial Statements:
- FinancialStatement: Income statement, balance sheet, or cash flow data
- FinancialItem: Single financial data point with date and value
Analysis:
- RecommendationTrend: Analyst buy/hold/sell recommendations
- PriceTarget: Analyst price targets
- EarningsEstimate: Earnings estimates by period
- RevenueEstimate: Revenue estimates by period
- EPSTrend: EPS trend over time
- EPSRevision: EPS revision counts
- EarningsHistory: Historical earnings vs estimates
- GrowthEstimate: Growth estimates from various sources
Holders:
- MajorHolders: Major shareholders breakdown (insiders, institutions)
- Holder: Institutional or mutual fund holder information
- InsiderTransaction: Insider purchase/sale transaction
- InsiderHolder: Company insider with holdings
- InsiderPurchases: Net share purchase activity summary
- HoldersData: Aggregate holder data container
Calendar:
- Calendar: Upcoming events including earnings and dividend dates
Search:
- SearchResult: Complete search response with quotes, news, lists
- SearchQuote: Quote match from search results
- SearchNews: News article from search results
- SearchParams: Search query parameters
Screener:
- ScreenerResult: Stock screener results with pagination
- ScreenerQuote: Stock from screener results with financial data
- ScreenerQuery: Custom screener query structure
- ScreenerParams: Screener parameters (offset, count, sort)
- PredefinedScreener: Predefined screener identifiers (day_gainers, etc.)
Multi-ticker:
- DownloadParams: Parameters for batch downloads (symbols, period, threads)
- MultiTickerResult: Results from multi-ticker download with data and errors
Live Streaming:
- PricingData: Real-time pricing data from WebSocket stream
- MarketState: Market hours state (pre/regular/post/closed)
News:
- NewsArticle: News article with title, publisher, link, thumbnail
- NewsThumbnail: Thumbnail image with multiple resolutions
- NewsTab: News type (all/news/press releases)
- NewsParams: News query parameters
History Parameters
The HistoryParams type controls historical data fetching:
params := models.HistoryParams{
Period: "1mo", // 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
Interval: "1d", // 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
PrePost: false, // Include pre/post market data
}
Use ValidPeriods and ValidIntervals to get lists of valid values.
Package models provides data structures for Yahoo Finance API responses.
Package models provides data structures for Yahoo Finance API responses.
Package models provides data structures for Yahoo Finance API responses.
Package models provides data structures for Yahoo Finance API responses.
Index
- func IsValidInterval(interval string) bool
- func IsValidPeriod(period string) bool
- func ValidIntervals() []string
- func ValidPeriods() []string
- type Actions
- type AnalysisData
- type Bar
- type Calendar
- func (c *Calendar) HasDividend() bool
- func (c *Calendar) HasEarnings() bool
- func (c *Calendar) NextEarningsDate() *time.Time
- type CalendarOptions
- func DefaultCalendarOptions() CalendarOptions
- type CalendarResponse
- type CalendarSplitEvent
- type CalendarType
- type CapitalGainEvent
- type ChartAdjClose
- type ChartError
- type ChartEvents
- type ChartIndicators
- type ChartMeta
- type ChartQuote
- type ChartResponse
- type ChartResult
- type Dividend
- type DividendEvent
- type DownloadParams
- func DefaultDownloadParams() DownloadParams
- type EPSRevision
- type EPSTrend
- type EarningsEstimate
- type EarningsEvent
- type EarningsHistory
- type EarningsHistoryItem
- type EconomicEvent
- type FastInfo
- type FinancialItem
- type FinancialStatement
- func NewFinancialStatement() *FinancialStatement
- func (fs *FinancialStatement) Fields() []string
- func (fs *FinancialStatement) Get(field string, date time.Time) (float64, bool)
- func (fs *FinancialStatement) GetLatest(field string) (float64, bool)
- type Financials
- type Frequency
- type GrowthCompany
- type GrowthEstimate
- type History
- type HistoryParams
- func DefaultHistoryParams() HistoryParams
- type Holder
- type HoldersData
- type IPOEvent
- type IndustryData
- type IndustryOverview
- type IndustryResponse
- type IndustryTopCompany
- type Info
- type InsiderHolder
- func (h *InsiderHolder) TotalShares() int64
- type InsiderPurchases
- type InsiderTransaction
- type LookupDocument
- type LookupParams
- func DefaultLookupParams() LookupParams
- type LookupResponse
- type LookupResult
- type LookupType
- type MajorHolders
- type MarketState
- func (m MarketState) String() string
- type MarketStatus
- type MarketSummary
- type MarketSummaryItem
- type MarketSummaryResponse
- type MarketTimeResponse
- type MarketTimezone
- type MultiTickerResult
- func (r *MultiTickerResult) ErrorCount() int
- func (r *MultiTickerResult) Get(symbol string) []Bar
- func (r *MultiTickerResult) HasErrors() bool
- func (r *MultiTickerResult) SuccessCount() int
- type NewsArticle
- func (n *NewsArticle) PublishedAt() time.Time
- type NewsParams
- type NewsTab
- func (t NewsTab) QueryRef() string
- func (t NewsTab) String() string
- type NewsThumbnail
- type Officer
- type Option
- func (o *Option) ExpirationDatetime() time.Time
- func (o *Option) LastTradeDatetime() time.Time
- type OptionChain
- type OptionChainResponse
- type OptionQuote
- type OptionsData
- type PerformingCompany
- type PredefinedIndustry
- func AllIndustries() []PredefinedIndustry
- type PredefinedMarket
- type PredefinedScreener
- func AllPredefinedScreeners() []PredefinedScreener
- type PredefinedSector
- func AllSectors() []PredefinedSector
- type PriceTarget
- type PricingData
- func (p *PricingData) ExpireTime() time.Time
- func (p *PricingData) IsPostMarket() bool
- func (p *PricingData) IsPreMarket() bool
- func (p *PricingData) IsRegularMarket() bool
- func (p *PricingData) Timestamp() time.Time
- type QueryOperator
- type Quote
- type QuoteError
- type QuoteResponse
- type QuoteResult
- type QuoteSummaryError
- type QuoteSummaryResponse
- type QuoteSummaryResult
- type Recommendation
- func (r *Recommendation) Total() int
- type RecommendationTrend
- type RepairOptions
- func DefaultRepairOptions() RepairOptions
- type ResearchReport
- type RevenueEstimate
- type ScreenerParams
- func DefaultScreenerParams() ScreenerParams
- type ScreenerQuery
- func NewEquityQuery(op QueryOperator, operands []interface{}) *ScreenerQuery
- type ScreenerQuote
- type ScreenerResponse
- type ScreenerResult
- type SearchList
- type SearchNav
- type SearchNews
- type SearchParams
- func DefaultSearchParams() SearchParams
- type SearchQuote
- type SearchResearch
- type SearchResponse
- type SearchResult
- type SearchThumbnail
- type SectorData
- type SectorIndustry
- type SectorOverview
- type SectorResponse
- type SectorTopCompany
- type Split
- type SplitEvent
- type ThumbnailResolution
- type TimeseriesDataPoint
- type TimeseriesResponse
- type TimeseriesResult
- type TransactionStats
func IsValidInterval
IsValidInterval checks if an interval string is valid.
func IsValidPeriod
IsValidPeriod checks if a period string is valid.
func ValidIntervals
ValidIntervals returns all valid interval values.
func ValidPeriods
ValidPeriods returns all valid period values.
type Actions
Actions represents dividend and split actions.
type Actions struct {
Dividends []Dividend `json:"dividends,omitempty"`
Splits []Split `json:"splits,omitempty"`
}
type AnalysisData
AnalysisData holds all analysis data for a ticker.
type AnalysisData struct {
Recommendations *RecommendationTrend `json:"recommendations,omitempty"`
PriceTarget *PriceTarget `json:"priceTarget,omitempty"`
EarningsEstimates []EarningsEstimate `json:"earningsEstimates,omitempty"`
RevenueEstimates []RevenueEstimate `json:"revenueEstimates,omitempty"`
EPSTrends []EPSTrend `json:"epsTrends,omitempty"`
EPSRevisions []EPSRevision `json:"epsRevisions,omitempty"`
EarningsHistory *EarningsHistory `json:"earningsHistory,omitempty"`
GrowthEstimates []GrowthEstimate `json:"growthEstimates,omitempty"`
}
type Bar
Bar represents a single OHLCV bar (candlestick).
type Bar struct {
Date time.Time `json:"date"`
Open float64 `json:"open"`
High float64 `json:"high"`
Low float64 `json:"low"`
Close float64 `json:"close"`
AdjClose float64 `json:"adjClose"`
Volume int64 `json:"volume"`
Dividends float64 `json:"dividends,omitempty"`
Splits float64 `json:"splits,omitempty"`
CapitalGains float64 `json:"capitalGains,omitempty"` // Capital gains distribution (ETF/MutualFund)
Repaired bool `json:"repaired,omitempty"` // True if this bar was repaired
}
type Calendar
Calendar represents upcoming calendar events for a ticker.
This includes dividend dates, earnings dates, and earnings estimates.
Example:
calendar, err := ticker.Calendar()
if err != nil {
log.Fatal(err)
}
if calendar.ExDividendDate != nil {
fmt.Printf("Ex-Dividend: %s\n", calendar.ExDividendDate.Format("2006-01-02"))
}
for _, date := range calendar.EarningsDate {
fmt.Printf("Earnings: %s\n", date.Format("2006-01-02"))
}
type Calendar struct {
// DividendDate is the next dividend payment date.
DividendDate *time.Time `json:"dividendDate,omitempty"`
// ExDividendDate is the ex-dividend date (must own before this date).
ExDividendDate *time.Time `json:"exDividendDate,omitempty"`
// EarningsDate contains the expected earnings announcement date(s).
// Often contains a range (start and end date).
EarningsDate []time.Time `json:"earningsDate,omitempty"`
// EarningsHigh is the highest earnings estimate.
EarningsHigh *float64 `json:"earningsHigh,omitempty"`
// EarningsLow is the lowest earnings estimate.
EarningsLow *float64 `json:"earningsLow,omitempty"`
// EarningsAverage is the average earnings estimate.
EarningsAverage *float64 `json:"earningsAverage,omitempty"`
// RevenueHigh is the highest revenue estimate.
RevenueHigh *float64 `json:"revenueHigh,omitempty"`
// RevenueLow is the lowest revenue estimate.
RevenueLow *float64 `json:"revenueLow,omitempty"`
// RevenueAverage is the average revenue estimate.
RevenueAverage *float64 `json:"revenueAverage,omitempty"`
}
func (*Calendar) HasDividend
HasDividend returns true if dividend data is available.
func (*Calendar) HasEarnings
HasEarnings returns true if earnings data is available.
func (*Calendar) NextEarningsDate
NextEarningsDate returns the earliest earnings date, or nil if none.
type CalendarOptions
CalendarOptions contains options for calendar queries.
type CalendarOptions struct {
// Start is the start date for the calendar range.
Start time.Time
// End is the end date for the calendar range.
End time.Time
// Limit is the maximum number of results (max 100).
Limit int
// Offset is the pagination offset.
Offset int
}
func DefaultCalendarOptions
DefaultCalendarOptions returns default calendar options. Default range is today to 7 days from now, limit 12.
type CalendarResponse
CalendarResponse represents the raw API response for calendar data.
type CalendarResponse struct {
Finance struct {
Result []struct {
Documents []struct {
Columns []struct {
Label string `json:"label"`
Type string `json:"type"`
} `json:"columns"`
Rows [][]interface{} `json:"rows"`
} `json:"documents"`
} `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
} `json:"finance"`
}
type CalendarSplitEvent
CalendarSplitEvent represents a stock split calendar event.
type CalendarSplitEvent struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// CompanyName is the company's short name.
CompanyName string `json:"company_name"`
// PayableDate is the split payable date.
PayableDate *time.Time `json:"payable_date,omitempty"`
// Optionable indicates if the stock is optionable.
Optionable bool `json:"optionable"`
// OldShareWorth is the old share worth.
OldShareWorth float64 `json:"old_share_worth,omitempty"`
// NewShareWorth is the new share worth after split.
NewShareWorth float64 `json:"new_share_worth,omitempty"`
// Ratio represents the split ratio (e.g., "2:1").
Ratio string `json:"ratio,omitempty"`
}
type CalendarType
CalendarType represents the type of calendar.
const (
// CalendarEarnings represents the S&P earnings calendar.
CalendarEarnings CalendarType = "sp_earnings"
// CalendarIPO represents the IPO info calendar.
CalendarIPO CalendarType = "ipo_info"
// CalendarEconomicEvents represents the economic events calendar.
CalendarEconomicEvents CalendarType = "economic_event"
// CalendarSplits represents the stock splits calendar.
CalendarSplits CalendarType = "splits"
)
type CapitalGainEvent
CapitalGainEvent represents a capital gain distribution event.
type ChartAdjClose
ChartAdjClose contains adjusted close prices.
type ChartError
ChartError represents an error from the chart API.
type ChartEvents
ChartEvents contains dividend and split events.
type ChartEvents struct {
Dividends map[string]DividendEvent `json:"dividends,omitempty"`
Splits map[string]SplitEvent `json:"splits,omitempty"`
CapitalGains map[string]CapitalGainEvent `json:"capitalGains,omitempty"`
}
type ChartIndicators
ChartIndicators contains OHLCV data.
type ChartIndicators struct {
Quote []ChartQuote `json:"quote"`
AdjClose []ChartAdjClose `json:"adjclose,omitempty"`
}
type ChartMeta
ChartMeta represents metadata from chart API response.
type ChartMeta struct {
Currency string `json:"currency"`
Symbol string `json:"symbol"`
ExchangeName string `json:"exchangeName"`
ExchangeTimezoneName string `json:"exchangeTimezoneName"`
InstrumentType string `json:"instrumentType"`
FirstTradeDate int64 `json:"firstTradeDate"`
RegularMarketTime int64 `json:"regularMarketTime"`
GMTOffset int `json:"gmtoffset"`
Timezone string `json:"timezone"`
RegularMarketPrice float64 `json:"regularMarketPrice"`
ChartPreviousClose float64 `json:"chartPreviousClose"`
PreviousClose float64 `json:"previousClose"`
Scale int `json:"scale"`
PriceHint int `json:"priceHint"`
DataGranularity string `json:"dataGranularity"`
Range string `json:"range"`
ValidRanges []string `json:"validRanges"`
}
type ChartQuote
ChartQuote contains OHLCV arrays.
type ChartQuote struct {
Open []*float64 `json:"open"`
High []*float64 `json:"high"`
Low []*float64 `json:"low"`
Close []*float64 `json:"close"`
Volume []*int64 `json:"volume"`
}
type ChartResponse
ChartResponse represents the response from Yahoo Finance chart API.
type ChartResponse struct {
Chart struct {
Result []ChartResult `json:"result"`
Error *ChartError `json:"error"`
} `json:"chart"`
}
type ChartResult
ChartResult represents a single chart result.
type ChartResult struct {
Meta ChartMeta `json:"meta"`
Timestamp []int64 `json:"timestamp"`
Events *ChartEvents `json:"events,omitempty"`
Indicators ChartIndicators `json:"indicators"`
}
type Dividend
Dividend represents a dividend payment.
type DividendEvent
DividendEvent represents a dividend event in chart response.
type DownloadParams
DownloadParams represents parameters for downloading multiple tickers.
Example:
params := models.DownloadParams{
Symbols: []string{"AAPL", "MSFT", "GOOGL"},
Period: "1mo",
Interval: "1d",
}
type DownloadParams struct {
// Symbols is the list of ticker symbols to download.
Symbols []string
// Period is the data period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max).
// Either use Period or Start/End.
Period string
// Interval is the data interval (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo).
Interval string
// Start is the start date.
Start *time.Time
// End is the end date.
End *time.Time
// PrePost includes pre and post market data.
PrePost bool
// Actions includes dividend and stock split data.
Actions bool
// AutoAdjust adjusts OHLC for splits and dividends.
AutoAdjust bool
// Threads is the number of concurrent downloads.
// 0 or 1 means sequential, >1 means parallel.
Threads int
// Timeout is the request timeout in seconds.
Timeout int
}
func DefaultDownloadParams
DefaultDownloadParams returns default download parameters.
type EPSRevision
EPSRevision represents EPS revision data for a period.
type EPSRevision struct {
Period string `json:"period"`
UpLast7Days int `json:"upLast7days"`
UpLast30Days int `json:"upLast30days"`
DownLast7Days int `json:"downLast7days"`
DownLast30Days int `json:"downLast30days"`
}
type EPSTrend
EPSTrend represents EPS trend data for a period.
type EPSTrend struct {
Period string `json:"period"`
Current float64 `json:"current"`
SevenDays float64 `json:"7daysAgo"`
ThirtyDays float64 `json:"30daysAgo"`
SixtyDays float64 `json:"60daysAgo"`
NinetyDays float64 `json:"90daysAgo"`
}
type EarningsEstimate
EarningsEstimate represents earnings estimates for a period.
type EarningsEstimate struct {
Period string `json:"period"` // "0q", "+1q", "0y", "+1y"
EndDate string `json:"endDate"`
NumberOfAnalysts int `json:"numberOfAnalysts"`
Avg float64 `json:"avg"`
Low float64 `json:"low"`
High float64 `json:"high"`
YearAgoEPS float64 `json:"yearAgoEps"`
Growth float64 `json:"growth"` // as decimal (0.15 = 15%)
}
type EarningsEvent
EarningsEvent represents an earnings calendar event.
type EarningsEvent struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// CompanyName is the company's short name.
CompanyName string `json:"company_name"`
// MarketCap is the intraday market capitalization.
MarketCap float64 `json:"market_cap,omitempty"`
// EventName is the name of the earnings event.
EventName string `json:"event_name,omitempty"`
// EventTime is the event start datetime.
EventTime *time.Time `json:"event_time,omitempty"`
// Timing indicates if the event is before/after market (BMO/AMC).
Timing string `json:"timing,omitempty"`
// EPSEstimate is the estimated earnings per share.
EPSEstimate float64 `json:"eps_estimate,omitempty"`
// EPSActual is the actual reported earnings per share.
EPSActual float64 `json:"eps_actual,omitempty"`
// SurprisePercent is the earnings surprise percentage.
SurprisePercent float64 `json:"surprise_percent,omitempty"`
}
type EarningsHistory
EarningsHistory represents historical earnings data.
type EarningsHistoryItem
EarningsHistoryItem represents a single earnings report.
type EarningsHistoryItem struct {
Period string `json:"period"` // "-1q", "-2q", etc.
Quarter time.Time `json:"quarter"`
EPSActual float64 `json:"epsActual"`
EPSEstimate float64 `json:"epsEstimate"`
EPSDifference float64 `json:"epsDifference"`
SurprisePercent float64 `json:"surprisePercent"` // as decimal
}
type EconomicEvent
EconomicEvent represents an economic calendar event.
type EconomicEvent struct {
// Event is the economic release name.
Event string `json:"event"`
// Region is the country code.
Region string `json:"region,omitempty"`
// EventTime is the event start datetime.
EventTime *time.Time `json:"event_time,omitempty"`
// Period is the reporting period.
Period string `json:"period,omitempty"`
// Actual is the actual released value.
Actual float64 `json:"actual,omitempty"`
// Expected is the consensus estimate.
Expected float64 `json:"expected,omitempty"`
// Last is the prior release actual value.
Last float64 `json:"last,omitempty"`
// Revised is the revised value from original report.
Revised float64 `json:"revised,omitempty"`
}
type FastInfo
FastInfo represents a subset of quote data that can be fetched quickly.
type FastInfo struct {
Currency string `json:"currency"`
QuoteType string `json:"quoteType"`
Exchange string `json:"exchange"`
Timezone string `json:"timezone"`
Shares int64 `json:"shares"`
MarketCap float64 `json:"marketCap"`
LastPrice float64 `json:"lastPrice"`
PreviousClose float64 `json:"previousClose"`
Open float64 `json:"open"`
DayHigh float64 `json:"dayHigh"`
DayLow float64 `json:"dayLow"`
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose"`
LastVolume int64 `json:"lastVolume"`
FiftyDayAverage float64 `json:"fiftyDayAverage"`
TwoHundredDayAverage float64 `json:"twoHundredDayAverage"`
TenDayAverageVolume int64 `json:"tenDayAverageVolume"`
ThreeMonthAverageVolume int64 `json:"threeMonthAverageVolume"`
YearHigh float64 `json:"yearHigh"`
YearLow float64 `json:"yearLow"`
YearChange float64 `json:"yearChange"`
}
type FinancialItem
FinancialItem represents a single financial data point.
type FinancialItem struct {
AsOfDate time.Time `json:"asOfDate"`
CurrencyCode string `json:"currencyCode"`
PeriodType string `json:"periodType"` // "12M" for annual, "3M" for quarterly
Value float64 `json:"value"`
Formatted string `json:"formatted"`
}
type FinancialStatement
FinancialStatement represents a financial statement (income, balance sheet, or cash flow). It maps field names to their historical values.
type FinancialStatement struct {
// Data maps field names (e.g., "TotalRevenue") to time-ordered values.
// Each slice is ordered by date ascending.
Data map[string][]FinancialItem `json:"data"`
// Dates contains all unique dates in the statement, ordered ascending.
Dates []time.Time `json:"dates"`
// Currency is the primary currency of the statement.
Currency string `json:"currency"`
}
func NewFinancialStatement
NewFinancialStatement creates an empty FinancialStatement.
func (*FinancialStatement) Fields
Fields returns all available field names in the statement.
func (*FinancialStatement) Get
Get returns the value for a specific field and date. Returns 0 and false if not found.
func (*FinancialStatement) GetLatest
GetLatest returns the most recent value for a field. Returns 0 and false if not found.
type Financials
Financials holds all financial statements for a ticker.
type Financials struct {
// Income statements
IncomeStatementAnnual *FinancialStatement `json:"incomeStatementAnnual,omitempty"`
IncomeStatementQuarterly *FinancialStatement `json:"incomeStatementQuarterly,omitempty"`
// Balance sheets
BalanceSheetAnnual *FinancialStatement `json:"balanceSheetAnnual,omitempty"`
BalanceSheetQuarterly *FinancialStatement `json:"balanceSheetQuarterly,omitempty"`
// Cash flow statements
CashFlowAnnual *FinancialStatement `json:"cashFlowAnnual,omitempty"`
CashFlowQuarterly *FinancialStatement `json:"cashFlowQuarterly,omitempty"`
}
type Frequency
Frequency represents the time frequency for financial data.
const (
FrequencyAnnual Frequency = "annual"
FrequencyQuarterly Frequency = "quarterly"
FrequencyTrailing Frequency = "trailing"
)
type GrowthCompany
GrowthCompany represents a top growth company in the industry.
type GrowthCompany struct {
// Symbol is the stock ticker symbol.
Symbol string `json:"symbol"`
// Name is the company name.
Name string `json:"name"`
// YTDReturn is the year-to-date return.
YTDReturn float64 `json:"ytd_return,omitempty"`
// GrowthEstimate is the estimated growth rate.
GrowthEstimate float64 `json:"growth_estimate,omitempty"`
}
type GrowthEstimate
GrowthEstimate represents growth estimates from various sources.
type GrowthEstimate struct {
Period string `json:"period"`
StockGrowth *float64 `json:"stockGrowth,omitempty"` // nil if not available
IndustryGrowth *float64 `json:"industryGrowth,omitempty"`
SectorGrowth *float64 `json:"sectorGrowth,omitempty"`
IndexGrowth *float64 `json:"indexGrowth,omitempty"`
}
type History
History represents historical price data.
type History struct {
Symbol string `json:"symbol"`
Currency string `json:"currency"`
Bars []Bar `json:"bars"`
}
type HistoryParams
HistoryParams represents parameters for fetching historical data.
type HistoryParams struct {
// Period: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
Period string `json:"period,omitempty"`
// Interval: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
Interval string `json:"interval,omitempty"`
// Start date (YYYY-MM-DD or time.Time)
Start *time.Time `json:"start,omitempty"`
// End date (YYYY-MM-DD or time.Time)
End *time.Time `json:"end,omitempty"`
// Include pre/post market data
PrePost bool `json:"prepost,omitempty"`
// Automatically adjust OHLC for splits/dividends
AutoAdjust bool `json:"autoAdjust,omitempty"`
// Include dividend and split events
Actions bool `json:"actions,omitempty"`
// Repair bad data (100x errors, missing data)
Repair bool `json:"repair,omitempty"`
// RepairOptions provides fine-grained control over repair operations.
// If nil, all repairs are enabled when Repair is true.
RepairOptions *RepairOptions `json:"repairOptions,omitempty"`
// Keep NaN rows
KeepNA bool `json:"keepna,omitempty"`
}
func DefaultHistoryParams
DefaultHistoryParams returns default history parameters.
type Holder
Holder represents an institutional or mutual fund holder.
This structure is used for both institutional holders and mutual fund holders.
type Holder struct {
// DateReported is when this holding was reported.
DateReported time.Time `json:"dateReported"`
// Holder is the name of the holding institution or fund.
Holder string `json:"holder"`
// Shares is the number of shares held.
Shares int64 `json:"shares"`
// Value is the total value of the holding.
Value float64 `json:"value"`
// PctHeld is the percentage of outstanding shares held (0.0-1.0).
PctHeld float64 `json:"pctHeld"`
// PctChange is the percentage change in position since last report (0.0-1.0).
PctChange float64 `json:"pctChange"`
}
type HoldersData
HoldersData contains all holder-related data for a ticker.
type HoldersData struct {
// Major contains the major holders breakdown.
Major *MajorHolders `json:"major,omitempty"`
// Institutional contains the list of institutional holders.
Institutional []Holder `json:"institutional,omitempty"`
// MutualFund contains the list of mutual fund holders.
MutualFund []Holder `json:"mutualFund,omitempty"`
// InsiderTransactions contains the list of insider transactions.
InsiderTransactions []InsiderTransaction `json:"insiderTransactions,omitempty"`
// InsiderRoster contains the list of insiders.
InsiderRoster []InsiderHolder `json:"insiderRoster,omitempty"`
// InsiderPurchases contains insider purchase activity summary.
InsiderPurchases *InsiderPurchases `json:"insiderPurchases,omitempty"`
}
type IPOEvent
IPOEvent represents an IPO calendar event.
type IPOEvent struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// CompanyName is the company's short name.
CompanyName string `json:"company_name"`
// Exchange is the exchange short name.
Exchange string `json:"exchange,omitempty"`
// FilingDate is the SEC filing date.
FilingDate *time.Time `json:"filing_date,omitempty"`
// Date is the IPO date.
Date *time.Time `json:"date,omitempty"`
// AmendedDate is the amended filing date.
AmendedDate *time.Time `json:"amended_date,omitempty"`
// PriceFrom is the lower end of the price range.
PriceFrom float64 `json:"price_from,omitempty"`
// PriceTo is the upper end of the price range.
PriceTo float64 `json:"price_to,omitempty"`
// OfferPrice is the final offer price.
OfferPrice float64 `json:"offer_price,omitempty"`
// Currency is the currency name.
Currency string `json:"currency,omitempty"`
// Shares is the number of shares offered.
Shares int64 `json:"shares,omitempty"`
// DealType is the type of deal.
DealType string `json:"deal_type,omitempty"`
}
type IndustryData
IndustryData contains all data for an industry.
This includes overview information, top companies, sector info, performing companies, and growth companies.
Example:
i, err := industry.New("semiconductors")
if err != nil {
log.Fatal(err)
}
data, err := i.Data()
fmt.Printf("Industry: %s in Sector: %s\n", data.Name, data.SectorName)
type IndustryData struct {
// Key is the industry identifier.
Key string `json:"key"`
// Name is the display name of the industry.
Name string `json:"name"`
// Symbol is the associated symbol (e.g., index symbol).
Symbol string `json:"symbol,omitempty"`
// SectorKey is the key of the parent sector.
SectorKey string `json:"sector_key,omitempty"`
// SectorName is the name of the parent sector.
SectorName string `json:"sector_name,omitempty"`
// Overview contains industry overview information.
Overview IndustryOverview `json:"overview"`
// TopCompanies lists the top companies in the industry.
TopCompanies []IndustryTopCompany `json:"top_companies,omitempty"`
// TopPerformingCompanies lists the top performing companies.
TopPerformingCompanies []PerformingCompany `json:"top_performing_companies,omitempty"`
// TopGrowthCompanies lists the top growth companies.
TopGrowthCompanies []GrowthCompany `json:"top_growth_companies,omitempty"`
// ResearchReports contains research reports for the industry.
ResearchReports []ResearchReport `json:"research_reports,omitempty"`
}
type IndustryOverview
IndustryOverview contains overview information for an industry.
type IndustryOverview struct {
// CompaniesCount is the number of companies in the industry.
CompaniesCount int `json:"companies_count,omitempty"`
// MarketCap is the total market capitalization of the industry.
MarketCap float64 `json:"market_cap,omitempty"`
// MessageBoardID is the Yahoo Finance message board identifier.
MessageBoardID string `json:"message_board_id,omitempty"`
// Description is a text description of the industry.
Description string `json:"description,omitempty"`
// MarketWeight is the industry's weight in the market.
MarketWeight float64 `json:"market_weight,omitempty"`
// EmployeeCount is the total number of employees in the industry.
EmployeeCount int64 `json:"employee_count,omitempty"`
}
type IndustryResponse
IndustryResponse represents the raw API response for industry data.
type IndustryResponse struct {
Data struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
SectorKey string `json:"sectorKey"`
SectorName string `json:"sectorName"`
Overview map[string]interface{} `json:"overview"`
TopCompanies []map[string]interface{} `json:"topCompanies"`
TopPerformingCompanies []map[string]interface{} `json:"topPerformingCompanies"`
TopGrowthCompanies []map[string]interface{} `json:"topGrowthCompanies"`
ResearchReports []map[string]interface{} `json:"researchReports"`
} `json:"data"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
}
type IndustryTopCompany
IndustryTopCompany represents a top company within an industry.
type IndustryTopCompany struct {
// Symbol is the stock ticker symbol.
Symbol string `json:"symbol"`
// Name is the company name.
Name string `json:"name"`
// Rating is the analyst rating.
Rating string `json:"rating,omitempty"`
// MarketWeight is the company's weight within the industry.
MarketWeight float64 `json:"market_weight,omitempty"`
}
type Info
Info represents comprehensive company information from quoteSummary API.
type Info struct {
// Basic identifiers
Symbol string `json:"symbol"`
ShortName string `json:"shortName"`
LongName string `json:"longName"`
// Company profile (assetProfile module)
Sector string `json:"sector,omitempty"`
Industry string `json:"industry,omitempty"`
FullTimeEmployees int64 `json:"fullTimeEmployees,omitempty"`
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
Country string `json:"country,omitempty"`
Phone string `json:"phone,omitempty"`
Address1 string `json:"address1,omitempty"`
Address2 string `json:"address2,omitempty"`
Zip string `json:"zip,omitempty"`
Website string `json:"website,omitempty"`
LongBusinessSummary string `json:"longBusinessSummary,omitempty"`
CompanyOfficers []Officer `json:"companyOfficers,omitempty"`
AuditRisk int `json:"auditRisk,omitempty"`
BoardRisk int `json:"boardRisk,omitempty"`
CompensationRisk int `json:"compensationRisk,omitempty"`
ShareHolderRightsRisk int `json:"shareHolderRightsRisk,omitempty"`
OverallRisk int `json:"overallRisk,omitempty"`
GovernanceEpochDate int64 `json:"governanceEpochDate,omitempty"`
CompensationAsOfEpochDate int64 `json:"compensationAsOfEpochDate,omitempty"`
// Quote type info (quoteType module)
QuoteType string `json:"quoteType,omitempty"`
Exchange string `json:"exchange,omitempty"`
ExchangeTimezoneName string `json:"exchangeTimezoneName,omitempty"`
ExchangeTimezoneShort string `json:"exchangeTimezoneShortName,omitempty"`
Currency string `json:"currency,omitempty"`
Market string `json:"market,omitempty"`
FirstTradeDateEpoch int64 `json:"firstTradeDateEpochUtc,omitempty"`
GMTOffset int `json:"gmtOffSetMilliseconds,omitempty"`
TimeZoneFullName string `json:"timeZoneFullName,omitempty"`
TimeZoneShortName string `json:"timeZoneShortName,omitempty"`
// Key statistics (defaultKeyStatistics module)
EnterpriseValue int64 `json:"enterpriseValue,omitempty"`
ForwardPE float64 `json:"forwardPE,omitempty"`
ProfitMargins float64 `json:"profitMargins,omitempty"`
FloatShares int64 `json:"floatShares,omitempty"`
SharesOutstanding int64 `json:"sharesOutstanding,omitempty"`
SharesShort int64 `json:"sharesShort,omitempty"`
SharesShortPriorMonth int64 `json:"sharesShortPriorMonth,omitempty"`
SharesShortPreviousMonthDate int64 `json:"sharesShortPreviousMonthDate,omitempty"`
DateShortInterest int64 `json:"dateShortInterest,omitempty"`
SharesPercentSharesOut float64 `json:"sharesPercentSharesOut,omitempty"`
HeldPercentInsiders float64 `json:"heldPercentInsiders,omitempty"`
HeldPercentInstitutions float64 `json:"heldPercentInstitutions,omitempty"`
ShortRatio float64 `json:"shortRatio,omitempty"`
ShortPercentOfFloat float64 `json:"shortPercentOfFloat,omitempty"`
Beta float64 `json:"beta,omitempty"`
ImpliedSharesOutstanding int64 `json:"impliedSharesOutstanding,omitempty"`
BookValue float64 `json:"bookValue,omitempty"`
PriceToBook float64 `json:"priceToBook,omitempty"`
LastFiscalYearEnd int64 `json:"lastFiscalYearEnd,omitempty"`
NextFiscalYearEnd int64 `json:"nextFiscalYearEnd,omitempty"`
MostRecentQuarter int64 `json:"mostRecentQuarter,omitempty"`
EarningsQuarterlyGrowth float64 `json:"earningsQuarterlyGrowth,omitempty"`
NetIncomeToCommon int64 `json:"netIncomeToCommon,omitempty"`
TrailingEps float64 `json:"trailingEps,omitempty"`
ForwardEps float64 `json:"forwardEps,omitempty"`
PegRatio float64 `json:"pegRatio,omitempty"`
LastSplitFactor string `json:"lastSplitFactor,omitempty"`
LastSplitDate int64 `json:"lastSplitDate,omitempty"`
EnterpriseToRevenue float64 `json:"enterpriseToRevenue,omitempty"`
EnterpriseToEbitda float64 `json:"enterpriseToEbitda,omitempty"`
FiftyTwoWeekChange float64 `json:"52WeekChange,omitempty"`
SandP52WeekChange float64 `json:"SandP52WeekChange,omitempty"`
LastDividendValue float64 `json:"lastDividendValue,omitempty"`
LastDividendDate int64 `json:"lastDividendDate,omitempty"`
LastCapGain float64 `json:"lastCapGain,omitempty"`
AnnualHoldingsTurnover float64 `json:"annualHoldingsTurnover,omitempty"`
// Summary detail (summaryDetail module)
PreviousClose float64 `json:"previousClose,omitempty"`
Open float64 `json:"open,omitempty"`
DayLow float64 `json:"dayLow,omitempty"`
DayHigh float64 `json:"dayHigh,omitempty"`
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose,omitempty"`
RegularMarketOpen float64 `json:"regularMarketOpen,omitempty"`
RegularMarketDayLow float64 `json:"regularMarketDayLow,omitempty"`
RegularMarketDayHigh float64 `json:"regularMarketDayHigh,omitempty"`
DividendRate float64 `json:"dividendRate,omitempty"`
DividendYield float64 `json:"dividendYield,omitempty"`
ExDividendDate int64 `json:"exDividendDate,omitempty"`
PayoutRatio float64 `json:"payoutRatio,omitempty"`
FiveYearAvgDividendYield float64 `json:"fiveYearAvgDividendYield,omitempty"`
Beta5Y float64 `json:"beta5Y,omitempty"`
TrailingPE float64 `json:"trailingPE,omitempty"`
Volume int64 `json:"volume,omitempty"`
RegularMarketVolume int64 `json:"regularMarketVolume,omitempty"`
AverageVolume int64 `json:"averageVolume,omitempty"`
AverageVolume10Days int64 `json:"averageVolume10days,omitempty"`
AverageDailyVolume10Day int64 `json:"averageDailyVolume10Day,omitempty"`
Bid float64 `json:"bid,omitempty"`
Ask float64 `json:"ask,omitempty"`
BidSize int64 `json:"bidSize,omitempty"`
AskSize int64 `json:"askSize,omitempty"`
MarketCap int64 `json:"marketCap,omitempty"`
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow,omitempty"`
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh,omitempty"`
PriceToSalesTrailing12Mo float64 `json:"priceToSalesTrailing12Months,omitempty"`
FiftyDayAverage float64 `json:"fiftyDayAverage,omitempty"`
TwoHundredDayAverage float64 `json:"twoHundredDayAverage,omitempty"`
TrailingAnnualDividendRate float64 `json:"trailingAnnualDividendRate,omitempty"`
TrailingAnnualDividendYield float64 `json:"trailingAnnualDividendYield,omitempty"`
// Financial data (financialData module)
CurrentPrice float64 `json:"currentPrice,omitempty"`
TargetHighPrice float64 `json:"targetHighPrice,omitempty"`
TargetLowPrice float64 `json:"targetLowPrice,omitempty"`
TargetMeanPrice float64 `json:"targetMeanPrice,omitempty"`
TargetMedianPrice float64 `json:"targetMedianPrice,omitempty"`
RecommendationMean float64 `json:"recommendationMean,omitempty"`
RecommendationKey string `json:"recommendationKey,omitempty"`
NumberOfAnalystOpinions int `json:"numberOfAnalystOpinions,omitempty"`
TotalCash int64 `json:"totalCash,omitempty"`
TotalCashPerShare float64 `json:"totalCashPerShare,omitempty"`
Ebitda int64 `json:"ebitda,omitempty"`
TotalDebt int64 `json:"totalDebt,omitempty"`
QuickRatio float64 `json:"quickRatio,omitempty"`
CurrentRatio float64 `json:"currentRatio,omitempty"`
TotalRevenue int64 `json:"totalRevenue,omitempty"`
DebtToEquity float64 `json:"debtToEquity,omitempty"`
RevenuePerShare float64 `json:"revenuePerShare,omitempty"`
ReturnOnAssets float64 `json:"returnOnAssets,omitempty"`
ReturnOnEquity float64 `json:"returnOnEquity,omitempty"`
GrossProfits int64 `json:"grossProfits,omitempty"`
FreeCashflow int64 `json:"freeCashflow,omitempty"`
OperatingCashflow int64 `json:"operatingCashflow,omitempty"`
EarningsGrowth float64 `json:"earningsGrowth,omitempty"`
RevenueGrowth float64 `json:"revenueGrowth,omitempty"`
GrossMargins float64 `json:"grossMargins,omitempty"`
EbitdaMargins float64 `json:"ebitdaMargins,omitempty"`
OperatingMargins float64 `json:"operatingMargins,omitempty"`
FinancialCurrency string `json:"financialCurrency,omitempty"`
// Trailing PEG (from timeseries API)
TrailingPegRatio float64 `json:"trailingPegRatio,omitempty"`
}
type InsiderHolder
InsiderHolder represents an insider on the company's roster.
This provides information about company insiders and their holdings.
type InsiderHolder struct {
// Name is the insider's name.
Name string `json:"name"`
// Position is the insider's position/title.
Position string `json:"position"`
// URL is a link to more information.
URL string `json:"url,omitempty"`
// MostRecentTransaction describes the most recent transaction.
MostRecentTransaction string `json:"mostRecentTransaction,omitempty"`
// LatestTransDate is the date of the most recent transaction.
LatestTransDate *time.Time `json:"latestTransDate,omitempty"`
// PositionDirectDate is when direct position was last reported.
PositionDirectDate *time.Time `json:"positionDirectDate,omitempty"`
// SharesOwnedDirectly is the number of shares owned directly.
SharesOwnedDirectly int64 `json:"sharesOwnedDirectly"`
// SharesOwnedIndirectly is the number of shares owned indirectly.
SharesOwnedIndirectly int64 `json:"sharesOwnedIndirectly"`
}
func (*InsiderHolder) TotalShares
TotalShares returns the total shares owned (direct + indirect).
type InsiderPurchases
InsiderPurchases represents net share purchase activity by insiders.
This summarizes insider buying and selling activity over a period.
type InsiderPurchases struct {
// Period is the time period covered (e.g., "6m" for 6 months).
Period string `json:"period"`
// Purchases contains purchase statistics.
Purchases TransactionStats `json:"purchases"`
// Sales contains sale statistics.
Sales TransactionStats `json:"sales"`
// Net contains net purchase/sale statistics.
Net TransactionStats `json:"net"`
// TotalInsiderShares is total shares held by insiders.
TotalInsiderShares int64 `json:"totalInsiderShares"`
// NetPercentInsiderShares is net shares as percent of insider holdings.
NetPercentInsiderShares float64 `json:"netPercentInsiderShares"`
// BuyPercentInsiderShares is buy shares as percent of insider holdings.
BuyPercentInsiderShares float64 `json:"buyPercentInsiderShares"`
// SellPercentInsiderShares is sell shares as percent of insider holdings.
SellPercentInsiderShares float64 `json:"sellPercentInsiderShares"`
}
type InsiderTransaction
InsiderTransaction represents a single insider transaction.
This includes purchases, sales, and other transactions by company insiders.
type InsiderTransaction struct {
// StartDate is the transaction date.
StartDate time.Time `json:"startDate"`
// Insider is the name of the insider.
Insider string `json:"insider"`
// Position is the insider's position/title in the company.
Position string `json:"position"`
// URL is a link to more information about the insider.
URL string `json:"url,omitempty"`
// Transaction is the type of transaction (e.g., "Sale", "Purchase").
Transaction string `json:"transaction"`
// Text is a description of the transaction.
Text string `json:"text,omitempty"`
// Shares is the number of shares involved.
Shares int64 `json:"shares"`
// Value is the total value of the transaction.
Value float64 `json:"value"`
// Ownership indicates ownership type (e.g., "D" for direct, "I" for indirect).
Ownership string `json:"ownership"`
}
type LookupDocument
LookupDocument represents a single financial instrument from lookup results.
This structure contains detailed information about a matching ticker symbol, including pricing data if requested.
type LookupDocument struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// Name is the company/instrument name.
Name string `json:"name"`
// ShortName is the short name (alternative to Name).
ShortName string `json:"shortName,omitempty"`
// Exchange is the exchange where the instrument is traded.
Exchange string `json:"exchange"`
// ExchangeDisplay is the display name of the exchange.
ExchangeDisplay string `json:"exchDisp,omitempty"`
// QuoteType is the type of instrument (EQUITY, ETF, MUTUALFUND, etc.).
QuoteType string `json:"quoteType"`
// TypeDisplay is the display name of the instrument type.
TypeDisplay string `json:"typeDisp,omitempty"`
// Industry is the industry classification.
Industry string `json:"industry,omitempty"`
// Sector is the sector classification.
Sector string `json:"sector,omitempty"`
// Score is the relevance score of this result.
Score float64 `json:"score,omitempty"`
// RegularMarketPrice is the current market price.
RegularMarketPrice float64 `json:"regularMarketPrice,omitempty"`
// RegularMarketChange is the price change.
RegularMarketChange float64 `json:"regularMarketChange,omitempty"`
// RegularMarketChangePercent is the percentage price change.
RegularMarketChangePercent float64 `json:"regularMarketChangePercent,omitempty"`
// RegularMarketPreviousClose is the previous closing price.
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose,omitempty"`
// RegularMarketOpen is the opening price.
RegularMarketOpen float64 `json:"regularMarketOpen,omitempty"`
// RegularMarketDayHigh is the day's high price.
RegularMarketDayHigh float64 `json:"regularMarketDayHigh,omitempty"`
// RegularMarketDayLow is the day's low price.
RegularMarketDayLow float64 `json:"regularMarketDayLow,omitempty"`
// RegularMarketVolume is the trading volume.
RegularMarketVolume int64 `json:"regularMarketVolume,omitempty"`
// MarketCap is the market capitalization.
MarketCap int64 `json:"marketCap,omitempty"`
// FiftyTwoWeekHigh is the 52-week high price.
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh,omitempty"`
// FiftyTwoWeekLow is the 52-week low price.
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow,omitempty"`
// Currency is the trading currency.
Currency string `json:"currency,omitempty"`
// MarketState is the current market state (PRE, REGULAR, POST, CLOSED).
MarketState string `json:"marketState,omitempty"`
}
type LookupParams
LookupParams represents parameters for the Lookup function.
type LookupParams struct {
// Type is the instrument type filter (default "all").
Type LookupType
// Count is the maximum number of results to return (default 25).
Count int
// Start is the offset for pagination (default 0).
Start int
// FetchPricingData includes real-time pricing data in results (default true).
FetchPricingData bool
}
func DefaultLookupParams
DefaultLookupParams returns default lookup parameters.
Default values:
- Type: LookupTypeAll
- Count: 25
- Start: 0
- FetchPricingData: true
type LookupResponse
LookupResponse represents the raw API response from Yahoo Finance lookup.
type LookupResponse struct {
Finance struct {
Result []struct {
Documents []map[string]interface{} `json:"documents"`
Count int `json:"count,omitempty"`
Start int `json:"start,omitempty"`
Total int `json:"total,omitempty"`
} `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
} `json:"finance"`
}
type LookupResult
LookupResult represents the result of a lookup query.
This contains a list of matching financial instruments based on the search query.
Example:
l, err := lookup.New("AAPL")
if err != nil {
log.Fatal(err)
}
results, err := l.All(10)
for _, doc := range results {
fmt.Printf("%s: %s (%s)\n", doc.Symbol, doc.Name, doc.Exchange)
}
type LookupResult struct {
// Documents contains the list of matching financial instruments.
Documents []LookupDocument `json:"documents"`
// Count is the number of results returned.
Count int `json:"count"`
}
type LookupType
LookupType represents the type of financial instrument for lookup queries.
const (
// LookupTypeAll returns all types of financial instruments.
LookupTypeAll LookupType = "all"
// LookupTypeEquity returns stock/equity instruments.
LookupTypeEquity LookupType = "equity"
// LookupTypeMutualFund returns mutual fund instruments.
LookupTypeMutualFund LookupType = "mutualfund"
// LookupTypeETF returns ETF instruments.
LookupTypeETF LookupType = "etf"
// LookupTypeIndex returns index instruments.
LookupTypeIndex LookupType = "index"
// LookupTypeFuture returns future instruments.
LookupTypeFuture LookupType = "future"
// LookupTypeCurrency returns currency instruments.
LookupTypeCurrency LookupType = "currency"
// LookupTypeCryptocurrency returns cryptocurrency instruments.
LookupTypeCryptocurrency LookupType = "cryptocurrency"
)
type MajorHolders
MajorHolders represents the breakdown of major shareholders.
This includes percentages held by insiders, institutions, and the total count of institutional holders.
Example:
holders, err := ticker.MajorHolders()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Insiders: %.2f%%\n", holders.InsidersPercentHeld*100)
fmt.Printf("Institutions: %.2f%%\n", holders.InstitutionsPercentHeld*100)
type MajorHolders struct {
// InsidersPercentHeld is the percentage of shares held by insiders (0.0-1.0).
InsidersPercentHeld float64 `json:"insidersPercentHeld"`
// InstitutionsPercentHeld is the percentage of shares held by institutions (0.0-1.0).
InstitutionsPercentHeld float64 `json:"institutionsPercentHeld"`
// InstitutionsFloatPercentHeld is the percentage of float held by institutions (0.0-1.0).
InstitutionsFloatPercentHeld float64 `json:"institutionsFloatPercentHeld"`
// InstitutionsCount is the number of institutional holders.
InstitutionsCount int `json:"institutionsCount"`
}
type MarketState
MarketState represents the market hours state.
const (
// MarketStatePreMarket indicates pre-market hours.
MarketStatePreMarket MarketState = 0
// MarketStateRegular indicates regular trading hours.
MarketStateRegular MarketState = 1
// MarketStatePostMarket indicates post-market hours.
MarketStatePostMarket MarketState = 2
// MarketStateClosed indicates market is closed.
MarketStateClosed MarketState = 3
)
func (MarketState) String
String returns the string representation of MarketState.
type MarketStatus
MarketStatus represents the status and trading hours of a market.
This includes opening/closing times, timezone information, and current market state.
Example:
m, err := market.New("us_market")
if err != nil {
log.Fatal(err)
}
status, err := m.Status()
fmt.Printf("Market opens at: %s\n", status.Open.Format("15:04"))
type MarketStatus struct {
// ID is the market identifier (e.g., "us_market").
ID string `json:"id,omitempty"`
// Open is the market opening time.
Open *time.Time `json:"open,omitempty"`
// Close is the market closing time.
Close *time.Time `json:"close,omitempty"`
// Timezone contains timezone information.
Timezone *MarketTimezone `json:"timezone,omitempty"`
// State is the current market state (e.g., "REGULAR", "CLOSED", "PRE", "POST").
State string `json:"state,omitempty"`
// OpenStr is the raw open time string from API.
OpenStr string `json:"-"`
// CloseStr is the raw close time string from API.
CloseStr string `json:"-"`
}
type MarketSummary
MarketSummary represents the summary of all market indices.
This provides an overview of major market indices like S&P 500, Dow Jones, NASDAQ, etc.
Example:
m, err := market.New("us_market")
if err != nil {
log.Fatal(err)
}
summary, err := m.Summary()
for exchange, item := range summary {
fmt.Printf("%s: %.2f (%.2f%%)\n",
item.ShortName, item.RegularMarketPrice, item.RegularMarketChangePercent)
}
type MarketSummaryItem
MarketSummaryItem represents a single market index or asset in the summary.
Each item represents an index like S&P 500, Dow Jones, etc.
type MarketSummaryItem struct {
// Exchange is the exchange code (e.g., "SNP", "DJI").
Exchange string `json:"exchange"`
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// ShortName is the short name of the index.
ShortName string `json:"shortName"`
// FullExchangeName is the full name of the exchange.
FullExchangeName string `json:"fullExchangeName,omitempty"`
// MarketState is the current market state.
MarketState string `json:"marketState,omitempty"`
// RegularMarketPrice is the current price.
RegularMarketPrice float64 `json:"regularMarketPrice"`
// RegularMarketChange is the price change.
RegularMarketChange float64 `json:"regularMarketChange"`
// RegularMarketChangePercent is the percentage change.
RegularMarketChangePercent float64 `json:"regularMarketChangePercent"`
// RegularMarketPreviousClose is the previous closing price.
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose,omitempty"`
// RegularMarketTime is the time of the last regular market trade.
RegularMarketTime int64 `json:"regularMarketTime,omitempty"`
// QuoteType is the type of quote (e.g., "INDEX", "EQUITY").
QuoteType string `json:"quoteType,omitempty"`
// SourceInterval is the data update interval in seconds.
SourceInterval int `json:"sourceInterval,omitempty"`
// ExchangeDataDelayedBy is the delay in seconds.
ExchangeDataDelayedBy int `json:"exchangeDataDelayedBy,omitempty"`
}
type MarketSummaryResponse
MarketSummaryResponse represents the raw API response for market summary.
type MarketSummaryResponse struct {
MarketSummaryResponse struct {
Result []map[string]interface{} `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
} `json:"marketSummaryResponse"`
}
type MarketTimeResponse
MarketTimeResponse represents the raw API response for market time.
type MarketTimeResponse struct {
Finance struct {
MarketTimes []struct {
ID string `json:"id"`
MarketTime []struct {
ID string `json:"id"`
Open string `json:"open"`
Close string `json:"close"`
Timezone []map[string]interface{} `json:"timezone"`
Time string `json:"time,omitempty"`
} `json:"marketTime"`
} `json:"marketTimes"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
} `json:"finance"`
}
type MarketTimezone
MarketTimezone represents timezone information for a market.
type MarketTimezone struct {
// GMTOffset is the GMT offset in milliseconds.
GMTOffset int64 `json:"gmtoffset,omitempty"`
// Short is the short timezone name (e.g., "EST", "PST").
Short string `json:"short,omitempty"`
// Long is the full timezone name (e.g., "Eastern Standard Time").
Long string `json:"long,omitempty"`
}
type MultiTickerResult
MultiTickerResult represents the result of downloading multiple tickers.
type MultiTickerResult struct {
// Data contains the history data for each ticker.
// Key is the ticker symbol.
Data map[string][]Bar
// Errors contains any errors that occurred during download.
// Key is the ticker symbol.
Errors map[string]error
// Symbols is the list of successfully downloaded symbols.
Symbols []string
}
func (*MultiTickerResult) ErrorCount
ErrorCount returns the number of tickers that had errors.
func (*MultiTickerResult) Get
Get returns the history data for a specific ticker.
func (*MultiTickerResult) HasErrors
HasErrors returns true if any ticker had an error.
func (*MultiTickerResult) SuccessCount
SuccessCount returns the number of successfully downloaded tickers.
type NewsArticle
NewsArticle represents a single news article from Yahoo Finance.
type NewsArticle struct {
// UUID is the unique identifier for the article.
UUID string `json:"uuid"`
// Title is the headline of the article.
Title string `json:"title"`
// Publisher is the source of the article.
Publisher string `json:"publisher"`
// Link is the URL to the full article.
Link string `json:"link"`
// PublishTime is the Unix timestamp when the article was published.
PublishTime int64 `json:"providerPublishTime"`
// Type is the content type (e.g., "STORY", "VIDEO").
Type string `json:"type"`
// Thumbnail contains image URLs for the article.
Thumbnail *NewsThumbnail `json:"thumbnail,omitempty"`
// RelatedTickers lists ticker symbols related to this article.
RelatedTickers []string `json:"relatedTickers,omitempty"`
}
func (*NewsArticle) PublishedAt
PublishedAt returns the publish time as a time.Time value.
type NewsParams
NewsParams contains parameters for fetching news articles.
type NewsParams struct {
// Count is the number of articles to fetch (default: 10).
Count int
// Tab specifies the type of news to fetch.
Tab NewsTab
}
type NewsTab
NewsTab represents the type of news to fetch.
const (
// NewsTabAll fetches all news including articles and press releases.
NewsTabAll NewsTab = "all"
// NewsTabNews fetches only news articles (default).
NewsTabNews NewsTab = "news"
// NewsTabPressReleases fetches only press releases.
NewsTabPressReleases NewsTab = "press releases"
)
func (NewsTab) QueryRef
QueryRef returns the Yahoo Finance API query reference for this tab.
func (NewsTab) String
String returns the string representation of the NewsTab.
type NewsThumbnail
NewsThumbnail contains thumbnail image information for a news article. It reuses ThumbnailResolution from the search package.
type NewsThumbnail struct {
// Resolutions contains different size versions of the thumbnail.
Resolutions []ThumbnailResolution `json:"resolutions,omitempty"`
}
type Officer
Officer represents a company officer.
type Officer struct {
MaxAge int `json:"maxAge,omitempty"`
Name string `json:"name"`
Age int `json:"age,omitempty"`
Title string `json:"title"`
YearBorn int `json:"yearBorn,omitempty"`
FiscalYear int `json:"fiscalYear,omitempty"`
TotalPay int64 `json:"totalPay,omitempty"`
ExercisedValue int64 `json:"exercisedValue,omitempty"`
UnexercisedValue int64 `json:"unexercisedValue,omitempty"`
}
type Option
Option represents a single option contract (call or put).
type Option struct {
ContractSymbol string `json:"contractSymbol"`
Strike float64 `json:"strike"`
Currency string `json:"currency"`
LastPrice float64 `json:"lastPrice"`
Change float64 `json:"change"`
PercentChange float64 `json:"percentChange"`
Volume int64 `json:"volume"`
OpenInterest int64 `json:"openInterest"`
Bid float64 `json:"bid"`
Ask float64 `json:"ask"`
ContractSize string `json:"contractSize"`
Expiration int64 `json:"expiration"`
LastTradeDate int64 `json:"lastTradeDate"`
ImpliedVolatility float64 `json:"impliedVolatility"`
InTheMoney bool `json:"inTheMoney"`
}
func (*Option) ExpirationDatetime
ExpirationDatetime returns the expiration date as time.Time.
func (*Option) LastTradeDatetime
LastTradeDatetime returns the last trade date as time.Time.
type OptionChain
OptionChain represents the complete option chain for a symbol.
type OptionChain struct {
Calls []Option `json:"calls"`
Puts []Option `json:"puts"`
Underlying *OptionQuote `json:"underlying,omitempty"`
Expiration time.Time `json:"expiration"`
}
type OptionChainResponse
OptionChainResponse represents the API response for options data.
type OptionChainResponse struct {
OptionChain struct {
Result []struct {
UnderlyingSymbol string `json:"underlyingSymbol"`
ExpirationDates []int64 `json:"expirationDates"`
Strikes []float64 `json:"strikes"`
HasMiniOptions bool `json:"hasMiniOptions"`
Quote OptionQuote `json:"quote"`
Options []struct {
ExpirationDate int64 `json:"expirationDate"`
HasMiniOptions bool `json:"hasMiniOptions"`
Calls []Option `json:"calls"`
Puts []Option `json:"puts"`
} `json:"options"`
} `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error"`
} `json:"optionChain"`
}
type OptionQuote
OptionQuote represents quote data within options API response. Uses int64 for timestamps since options API returns Unix timestamps.
type OptionQuote struct {
Symbol string `json:"symbol"`
ShortName string `json:"shortName"`
LongName string `json:"longName"`
QuoteType string `json:"quoteType"`
Exchange string `json:"exchange"`
Currency string `json:"currency"`
MarketState string `json:"marketState"`
RegularMarketPrice float64 `json:"regularMarketPrice"`
RegularMarketChange float64 `json:"regularMarketChange"`
RegularMarketChangePercent float64 `json:"regularMarketChangePercent"`
RegularMarketDayHigh float64 `json:"regularMarketDayHigh"`
RegularMarketDayLow float64 `json:"regularMarketDayLow"`
RegularMarketOpen float64 `json:"regularMarketOpen"`
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose"`
RegularMarketVolume int64 `json:"regularMarketVolume"`
RegularMarketTime int64 `json:"regularMarketTime"`
Bid float64 `json:"bid"`
Ask float64 `json:"ask"`
BidSize int64 `json:"bidSize"`
AskSize int64 `json:"askSize"`
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh"`
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow"`
}
type OptionsData
OptionsData holds all expiration dates and the current option chain.
type OptionsData struct {
ExpirationDates []time.Time `json:"expirationDates"`
Strikes []float64 `json:"strikes"`
HasMiniOptions bool `json:"hasMiniOptions"`
OptionChain *OptionChain `json:"optionChain,omitempty"`
}
type PerformingCompany
PerformingCompany represents a top performing company in the industry.
type PerformingCompany struct {
// Symbol is the stock ticker symbol.
Symbol string `json:"symbol"`
// Name is the company name.
Name string `json:"name"`
// YTDReturn is the year-to-date return.
YTDReturn float64 `json:"ytd_return,omitempty"`
// LastPrice is the last traded price.
LastPrice float64 `json:"last_price,omitempty"`
// TargetPrice is the analyst target price.
TargetPrice float64 `json:"target_price,omitempty"`
}
type PredefinedIndustry
PredefinedIndustry represents commonly used industry identifiers.
const (
// IndustrySemiconductors represents the Semiconductors industry.
IndustrySemiconductors PredefinedIndustry = "semiconductors"
// IndustrySoftwareInfrastructure represents the Software - Infrastructure industry.
IndustrySoftwareInfrastructure PredefinedIndustry = "software-infrastructure"
// IndustrySoftwareApplication represents the Software - Application industry.
IndustrySoftwareApplication PredefinedIndustry = "software-application"
// IndustryConsumerElectronics represents the Consumer Electronics industry.
IndustryConsumerElectronics PredefinedIndustry = "consumer-electronics"
// IndustryComputerHardware represents the Computer Hardware industry.
IndustryComputerHardware PredefinedIndustry = "computer-hardware"
// IndustrySemiconductorEquipment represents the Semiconductor Equipment & Materials industry.
IndustrySemiconductorEquipment PredefinedIndustry = "semiconductor-equipment-materials"
// IndustryITServices represents the Information Technology Services industry.
IndustryITServices PredefinedIndustry = "information-technology-services"
// IndustryCommunicationEquipment represents the Communication Equipment industry.
IndustryCommunicationEquipment PredefinedIndustry = "communication-equipment"
// IndustryElectronicComponents represents the Electronic Components industry.
IndustryElectronicComponents PredefinedIndustry = "electronic-components"
// IndustrySolar represents the Solar industry.
IndustrySolar PredefinedIndustry = "solar"
)
const (
// IndustryBiotechnology represents the Biotechnology industry.
IndustryBiotechnology PredefinedIndustry = "biotechnology"
// IndustryDrugManufacturersGeneral represents the Drug Manufacturers - General industry.
IndustryDrugManufacturersGeneral PredefinedIndustry = "drug-manufacturers-general"
// IndustryMedicalDevices represents the Medical Devices industry.
IndustryMedicalDevices PredefinedIndustry = "medical-devices"
// IndustryHealthcarePlans represents the Healthcare Plans industry.
IndustryHealthcarePlans PredefinedIndustry = "healthcare-plans"
// IndustryDiagnosticsResearch represents the Diagnostics & Research industry.
IndustryDiagnosticsResearch PredefinedIndustry = "diagnostics-research"
)
Financial Services Sector Industries
const (
// IndustryBanksDiversified represents the Banks - Diversified industry.
IndustryBanksDiversified PredefinedIndustry = "banks-diversified"
// IndustryBanksRegional represents the Banks - Regional industry.
IndustryBanksRegional PredefinedIndustry = "banks-regional"
// IndustryAssetManagement represents the Asset Management industry.
IndustryAssetManagement PredefinedIndustry = "asset-management"
// IndustryCapitalMarkets represents the Capital Markets industry.
IndustryCapitalMarkets PredefinedIndustry = "capital-markets"
// IndustryInsuranceDiversified represents the Insurance - Diversified industry.
IndustryInsuranceDiversified PredefinedIndustry = "insurance-diversified"
// IndustryCreditServices represents the Credit Services industry.
IndustryCreditServices PredefinedIndustry = "credit-services"
)
const (
// IndustryOilGasIntegrated represents the Oil & Gas Integrated industry.
IndustryOilGasIntegrated PredefinedIndustry = "oil-gas-integrated"
// IndustryOilGasEP represents the Oil & Gas E&P industry.
IndustryOilGasEP PredefinedIndustry = "oil-gas-e-p"
// IndustryOilGasMidstream represents the Oil & Gas Midstream industry.
IndustryOilGasMidstream PredefinedIndustry = "oil-gas-midstream"
// IndustryOilGasEquipmentServices represents the Oil & Gas Equipment & Services industry.
IndustryOilGasEquipmentServices PredefinedIndustry = "oil-gas-equipment-services"
)
const (
// IndustryAutoManufacturers represents the Auto Manufacturers industry.
IndustryAutoManufacturers PredefinedIndustry = "auto-manufacturers"
// IndustryInternetRetail represents the Internet Retail industry.
IndustryInternetRetail PredefinedIndustry = "internet-retail"
// IndustryRestaurants represents the Restaurants industry.
IndustryRestaurants PredefinedIndustry = "restaurants"
// IndustryHomeImprovementRetail represents the Home Improvement Retail industry.
IndustryHomeImprovementRetail PredefinedIndustry = "home-improvement-retail"
)
const (
// IndustryAerospaceDefense represents the Aerospace & Defense industry.
IndustryAerospaceDefense PredefinedIndustry = "aerospace-defense"
// IndustryRailroads represents the Railroads industry.
IndustryRailroads PredefinedIndustry = "railroads"
// IndustryAirlines represents the Airlines industry.
IndustryAirlines PredefinedIndustry = "airlines"
// IndustryBuildingProductsEquipment represents the Building Products & Equipment industry.
IndustryBuildingProductsEquipment PredefinedIndustry = "building-products-equipment"
)
func AllIndustries
AllIndustries returns a list of common predefined industry identifiers. Note: This is not exhaustive - there are many more industries available.
type PredefinedMarket
PredefinedMarket represents commonly used market identifiers.
const (
// MarketUS represents the US market.
MarketUS PredefinedMarket = "us_market"
// MarketGB represents the UK market.
MarketGB PredefinedMarket = "gb_market"
// MarketDE represents the German market.
MarketDE PredefinedMarket = "de_market"
// MarketFR represents the French market.
MarketFR PredefinedMarket = "fr_market"
// MarketJP represents the Japanese market.
MarketJP PredefinedMarket = "jp_market"
// MarketHK represents the Hong Kong market.
MarketHK PredefinedMarket = "hk_market"
// MarketCN represents the Chinese market.
MarketCN PredefinedMarket = "cn_market"
// MarketCA represents the Canadian market.
MarketCA PredefinedMarket = "ca_market"
// MarketAU represents the Australian market.
MarketAU PredefinedMarket = "au_market"
// MarketIN represents the Indian market.
MarketIN PredefinedMarket = "in_market"
// MarketKR represents the Korean market.
MarketKR PredefinedMarket = "kr_market"
// MarketBR represents the Brazilian market.
MarketBR PredefinedMarket = "br_market"
)
type PredefinedScreener
PredefinedScreener represents a predefined screener query name.
const (
// Equity Screeners
ScreenerAggressiveSmallCaps PredefinedScreener = "aggressive_small_caps"
ScreenerDayGainers PredefinedScreener = "day_gainers"
ScreenerDayLosers PredefinedScreener = "day_losers"
ScreenerGrowthTech PredefinedScreener = "growth_technology_stocks"
ScreenerMostActives PredefinedScreener = "most_actives"
ScreenerMostShorted PredefinedScreener = "most_shorted_stocks"
ScreenerSmallCapGainers PredefinedScreener = "small_cap_gainers"
ScreenerUndervaluedGrowth PredefinedScreener = "undervalued_growth_stocks"
ScreenerUndervaluedLargeCaps PredefinedScreener = "undervalued_large_caps"
// Fund Screeners
ScreenerConservativeForeign PredefinedScreener = "conservative_foreign_funds"
ScreenerHighYieldBond PredefinedScreener = "high_yield_bond"
ScreenerPortfolioAnchors PredefinedScreener = "portfolio_anchors"
ScreenerSolidLargeGrowth PredefinedScreener = "solid_large_growth_funds"
ScreenerSolidMidcapGrowth PredefinedScreener = "solid_midcap_growth_funds"
ScreenerTopMutualFunds PredefinedScreener = "top_mutual_funds"
)
func AllPredefinedScreeners
AllPredefinedScreeners returns all available predefined screener names.
type PredefinedSector
PredefinedSector represents commonly used sector identifiers.
const (
// SectorBasicMaterials represents the Basic Materials sector.
SectorBasicMaterials PredefinedSector = "basic-materials"
// SectorCommunicationServices represents the Communication Services sector.
SectorCommunicationServices PredefinedSector = "communication-services"
// SectorConsumerCyclical represents the Consumer Cyclical sector.
SectorConsumerCyclical PredefinedSector = "consumer-cyclical"
// SectorConsumerDefensive represents the Consumer Defensive sector.
SectorConsumerDefensive PredefinedSector = "consumer-defensive"
// SectorEnergy represents the Energy sector.
SectorEnergy PredefinedSector = "energy"
// SectorFinancialServices represents the Financial Services sector.
SectorFinancialServices PredefinedSector = "financial-services"
// SectorHealthcare represents the Healthcare sector.
SectorHealthcare PredefinedSector = "healthcare"
// SectorIndustrials represents the Industrials sector.
SectorIndustrials PredefinedSector = "industrials"
// SectorRealEstate represents the Real Estate sector.
SectorRealEstate PredefinedSector = "real-estate"
// SectorTechnology represents the Technology sector.
SectorTechnology PredefinedSector = "technology"
// SectorUtilities represents the Utilities sector.
SectorUtilities PredefinedSector = "utilities"
)
func AllSectors
AllSectors returns a list of all predefined sector identifiers.
type PriceTarget
PriceTarget represents analyst price targets.
type PriceTarget struct {
Current float64 `json:"current"`
High float64 `json:"high"`
Low float64 `json:"low"`
Mean float64 `json:"mean"`
Median float64 `json:"median"`
NumberOfAnalysts int `json:"numberOfAnalysts"`
// Additional recommendation data
RecommendationKey string `json:"recommendationKey"` // "buy", "hold", "sell"
RecommendationMean float64 `json:"recommendationMean"` // 1.0 (strong buy) to 5.0 (strong sell)
}
type PricingData
PricingData represents real-time pricing data from Yahoo Finance WebSocket.
This structure contains live market data including price, volume, bid/ask, and various market indicators.
type PricingData struct {
// ID is the ticker symbol.
ID string `json:"id,omitempty"`
// Price is the current price.
Price float32 `json:"price,omitempty"`
// Time is the quote timestamp (Unix timestamp).
Time int64 `json:"time,omitempty"`
// Currency is the trading currency (e.g., "USD").
Currency string `json:"currency,omitempty"`
// Exchange is the exchange name (e.g., "NMS").
Exchange string `json:"exchange,omitempty"`
// QuoteType indicates the type of quote (1=equity, 2=option, etc.).
QuoteType int32 `json:"quote_type,omitempty"`
// MarketHours indicates market state (0=pre, 1=regular, 2=post, 3=closed).
MarketHours int32 `json:"market_hours,omitempty"`
// ChangePercent is the percentage change from previous close.
ChangePercent float32 `json:"change_percent,omitempty"`
// DayVolume is the trading volume for the day.
DayVolume int64 `json:"day_volume,omitempty"`
// DayHigh is the day's high price.
DayHigh float32 `json:"day_high,omitempty"`
// DayLow is the day's low price.
DayLow float32 `json:"day_low,omitempty"`
// Change is the absolute change from previous close.
Change float32 `json:"change,omitempty"`
// ShortName is the company short name.
ShortName string `json:"short_name,omitempty"`
// ExpireDate is the option expiration date (Unix timestamp).
ExpireDate int64 `json:"expire_date,omitempty"`
// OpenPrice is the day's opening price.
OpenPrice float32 `json:"open_price,omitempty"`
// PreviousClose is the previous day's closing price.
PreviousClose float32 `json:"previous_close,omitempty"`
// StrikePrice is the option strike price.
StrikePrice float32 `json:"strike_price,omitempty"`
// UnderlyingSymbol is the underlying symbol for options.
UnderlyingSymbol string `json:"underlying_symbol,omitempty"`
// OpenInterest is the option open interest.
OpenInterest int64 `json:"open_interest,omitempty"`
// OptionsType indicates call (0) or put (1).
OptionsType int64 `json:"options_type,omitempty"`
// MiniOption indicates if this is a mini option.
MiniOption int64 `json:"mini_option,omitempty"`
// LastSize is the last trade size.
LastSize int64 `json:"last_size,omitempty"`
// Bid is the current bid price.
Bid float32 `json:"bid,omitempty"`
// BidSize is the bid size.
BidSize int64 `json:"bid_size,omitempty"`
// Ask is the current ask price.
Ask float32 `json:"ask,omitempty"`
// AskSize is the ask size.
AskSize int64 `json:"ask_size,omitempty"`
// PriceHint is the decimal precision hint.
PriceHint int64 `json:"price_hint,omitempty"`
// Vol24Hr is 24-hour volume (for crypto).
Vol24Hr int64 `json:"vol_24hr,omitempty"`
// VolAllCurrencies is volume in all currencies (for crypto).
VolAllCurrencies int64 `json:"vol_all_currencies,omitempty"`
// FromCurrency is the source currency (for crypto).
FromCurrency string `json:"from_currency,omitempty"`
// LastMarket is the last market (for crypto).
LastMarket string `json:"last_market,omitempty"`
// CirculatingSupply is the circulating supply (for crypto).
CirculatingSupply float64 `json:"circulating_supply,omitempty"`
// MarketCap is the market capitalization.
MarketCap float64 `json:"market_cap,omitempty"`
}
func (*PricingData) ExpireTime
ExpireTime returns the option expiration date as time.Time.
func (*PricingData) IsPostMarket
IsPostMarket returns true if trading during post-market hours.
func (*PricingData) IsPreMarket
IsPreMarket returns true if trading during pre-market hours.
func (*PricingData) IsRegularMarket
IsRegularMarket returns true if trading during regular market hours.
func (*PricingData) Timestamp
Timestamp returns the quote time as time.Time.
type QueryOperator
QueryOperator represents an operator for custom screener queries.
const (
// Comparison operators
OpEQ QueryOperator = "eq" // Equals
OpGT QueryOperator = "gt" // Greater than
OpLT QueryOperator = "lt" // Less than
OpGTE QueryOperator = "gte" // Greater than or equal
OpLTE QueryOperator = "lte" // Less than or equal
OpBTWN QueryOperator = "btwn" // Between
// Logical operators
OpAND QueryOperator = "and" // All conditions must match
OpOR QueryOperator = "or" // Any condition can match
)
type Quote
Quote represents current quote data for a ticker.
type Quote struct {
// Symbol information
Symbol string `json:"symbol"`
ShortName string `json:"shortName"`
LongName string `json:"longName"`
QuoteType string `json:"quoteType"` // EQUITY, ETF, MUTUALFUND, etc.
// Exchange information
Exchange string `json:"exchange"`
ExchangeName string `json:"exchangeName"`
ExchangeTimezoneName string `json:"exchangeTimezoneName"`
Currency string `json:"currency"`
// Regular market data
RegularMarketPrice float64 `json:"regularMarketPrice"`
RegularMarketChange float64 `json:"regularMarketChange"`
RegularMarketChangePercent float64 `json:"regularMarketChangePercent"`
RegularMarketDayHigh float64 `json:"regularMarketDayHigh"`
RegularMarketDayLow float64 `json:"regularMarketDayLow"`
RegularMarketOpen float64 `json:"regularMarketOpen"`
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose"`
RegularMarketVolume int64 `json:"regularMarketVolume"`
RegularMarketTime time.Time `json:"regularMarketTime"`
// Pre/Post market data
PreMarketPrice float64 `json:"preMarketPrice,omitempty"`
PreMarketChange float64 `json:"preMarketChange,omitempty"`
PreMarketChangePercent float64 `json:"preMarketChangePercent,omitempty"`
PreMarketTime time.Time `json:"preMarketTime,omitempty"`
PostMarketPrice float64 `json:"postMarketPrice,omitempty"`
PostMarketChange float64 `json:"postMarketChange,omitempty"`
PostMarketChangePercent float64 `json:"postMarketChangePercent,omitempty"`
PostMarketTime time.Time `json:"postMarketTime,omitempty"`
// 52-week range
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh"`
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow"`
FiftyTwoWeekChange float64 `json:"fiftyTwoWeekChange"`
FiftyTwoWeekChangePerc float64 `json:"fiftyTwoWeekChangePercent"`
// Moving averages
FiftyDayAverage float64 `json:"fiftyDayAverage"`
FiftyDayAverageChange float64 `json:"fiftyDayAverageChange"`
FiftyDayAverageChangePerc float64 `json:"fiftyDayAverageChangePercent"`
TwoHundredDayAverage float64 `json:"twoHundredDayAverage"`
TwoHundredDayAverageChg float64 `json:"twoHundredDayAverageChange"`
TwoHundredDayAverageChgPc float64 `json:"twoHundredDayAverageChangePercent"`
// Volume averages
AverageDailyVolume3Month int64 `json:"averageDailyVolume3Month"`
AverageDailyVolume10Day int64 `json:"averageDailyVolume10Day"`
// Market cap and shares
MarketCap int64 `json:"marketCap"`
SharesOutstanding int64 `json:"sharesOutstanding"`
// Dividend info
TrailingAnnualDividendRate float64 `json:"trailingAnnualDividendRate,omitempty"`
TrailingAnnualDividendYield float64 `json:"trailingAnnualDividendYield,omitempty"`
DividendDate int64 `json:"dividendDate,omitempty"`
// Earnings info
TrailingPE float64 `json:"trailingPE,omitempty"`
ForwardPE float64 `json:"forwardPE,omitempty"`
EpsTrailingTwelveMonths float64 `json:"epsTrailingTwelveMonths,omitempty"`
EpsForward float64 `json:"epsForward,omitempty"`
EpsCurrentYear float64 `json:"epsCurrentYear,omitempty"`
// Book value
BookValue float64 `json:"bookValue,omitempty"`
PriceToBook float64 `json:"priceToBook,omitempty"`
// Bid/Ask
Bid float64 `json:"bid,omitempty"`
BidSize int64 `json:"bidSize,omitempty"`
Ask float64 `json:"ask,omitempty"`
AskSize int64 `json:"askSize,omitempty"`
// Market state
MarketState string `json:"marketState"` // PRE, REGULAR, POST, CLOSED
}
type QuoteError
QuoteError represents an error from quote API.
type QuoteResponse
QuoteResponse represents the response from quote API (v7).
type QuoteResponse struct {
QuoteResponse struct {
Result []QuoteResult `json:"result"`
Error *QuoteError `json:"error"`
} `json:"quoteResponse"`
}
type QuoteResult
QuoteResult represents a single quote result.
type QuoteResult struct {
Language string `json:"language"`
Region string `json:"region"`
QuoteType string `json:"quoteType"`
TypeDisp string `json:"typeDisp"`
QuoteSourceName string `json:"quoteSourceName"`
Triggerable bool `json:"triggerable"`
CustomPriceAlertConfidence string `json:"customPriceAlertConfidence"`
Currency string `json:"currency"`
Exchange string `json:"exchange"`
ShortName string `json:"shortName"`
LongName string `json:"longName"`
MessageBoardID string `json:"messageBoardId"`
ExchangeTimezoneName string `json:"exchangeTimezoneName"`
ExchangeTimezoneShortName string `json:"exchangeTimezoneShortName"`
GMTOffSetMilliseconds int64 `json:"gmtOffSetMilliseconds"`
Market string `json:"market"`
EsgPopulated bool `json:"esgPopulated"`
MarketState string `json:"marketState"`
RegularMarketChangePercent float64 `json:"regularMarketChangePercent"`
RegularMarketPrice float64 `json:"regularMarketPrice"`
RegularMarketChange float64 `json:"regularMarketChange"`
RegularMarketTime int64 `json:"regularMarketTime"`
RegularMarketDayHigh float64 `json:"regularMarketDayHigh"`
RegularMarketDayRange string `json:"regularMarketDayRange"`
RegularMarketDayLow float64 `json:"regularMarketDayLow"`
RegularMarketVolume int64 `json:"regularMarketVolume"`
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose"`
RegularMarketOpen float64 `json:"regularMarketOpen"`
Bid float64 `json:"bid"`
Ask float64 `json:"ask"`
BidSize int64 `json:"bidSize"`
AskSize int64 `json:"askSize"`
FullExchangeName string `json:"fullExchangeName"`
FinancialCurrency string `json:"financialCurrency"`
SourceInterval int `json:"sourceInterval"`
ExchangeDataDelayedBy int `json:"exchangeDataDelayedBy"`
Tradeable bool `json:"tradeable"`
CryptoTradeable bool `json:"cryptoTradeable"`
FirstTradeDateMilliseconds int64 `json:"firstTradeDateMilliseconds"`
PriceHint int `json:"priceHint"`
PostMarketChangePercent float64 `json:"postMarketChangePercent"`
PostMarketTime int64 `json:"postMarketTime"`
PostMarketPrice float64 `json:"postMarketPrice"`
PostMarketChange float64 `json:"postMarketChange"`
PreMarketChangePercent float64 `json:"preMarketChangePercent"`
PreMarketTime int64 `json:"preMarketTime"`
PreMarketPrice float64 `json:"preMarketPrice"`
PreMarketChange float64 `json:"preMarketChange"`
FiftyTwoWeekLowChange float64 `json:"fiftyTwoWeekLowChange"`
FiftyTwoWeekLowChangePercent float64 `json:"fiftyTwoWeekLowChangePercent"`
FiftyTwoWeekRange string `json:"fiftyTwoWeekRange"`
FiftyTwoWeekHighChange float64 `json:"fiftyTwoWeekHighChange"`
FiftyTwoWeekHighChangePercent float64 `json:"fiftyTwoWeekHighChangePercent"`
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow"`
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh"`
FiftyTwoWeekChangePercent float64 `json:"fiftyTwoWeekChangePercent"`
DividendDate int64 `json:"dividendDate"`
EarningsTimestamp int64 `json:"earningsTimestamp"`
EarningsTimestampStart int64 `json:"earningsTimestampStart"`
EarningsTimestampEnd int64 `json:"earningsTimestampEnd"`
TrailingAnnualDividendRate float64 `json:"trailingAnnualDividendRate"`
TrailingPE float64 `json:"trailingPE"`
TrailingAnnualDividendYield float64 `json:"trailingAnnualDividendYield"`
EpsTrailingTwelveMonths float64 `json:"epsTrailingTwelveMonths"`
EpsForward float64 `json:"epsForward"`
EpsCurrentYear float64 `json:"epsCurrentYear"`
PriceEpsCurrentYear float64 `json:"priceEpsCurrentYear"`
SharesOutstanding int64 `json:"sharesOutstanding"`
BookValue float64 `json:"bookValue"`
FiftyDayAverage float64 `json:"fiftyDayAverage"`
FiftyDayAverageChange float64 `json:"fiftyDayAverageChange"`
FiftyDayAverageChangePercent float64 `json:"fiftyDayAverageChangePercent"`
TwoHundredDayAverage float64 `json:"twoHundredDayAverage"`
TwoHundredDayAverageChange float64 `json:"twoHundredDayAverageChange"`
TwoHundredDayAverageChangePercent float64 `json:"twoHundredDayAverageChangePercent"`
MarketCap int64 `json:"marketCap"`
ForwardPE float64 `json:"forwardPE"`
PriceToBook float64 `json:"priceToBook"`
AverageDailyVolume10Day int64 `json:"averageDailyVolume10Day"`
AverageDailyVolume3Month int64 `json:"averageDailyVolume3Month"`
DisplayName string `json:"displayName"`
Symbol string `json:"symbol"`
}
type QuoteSummaryError
QuoteSummaryError represents an error from quoteSummary API.
type QuoteSummaryResponse
QuoteSummaryResponse represents the response from quoteSummary API.
type QuoteSummaryResponse struct {
QuoteSummary struct {
Result []QuoteSummaryResult `json:"result"`
Error *QuoteSummaryError `json:"error"`
} `json:"quoteSummary"`
}
type QuoteSummaryResult
QuoteSummaryResult contains all module data.
type QuoteSummaryResult struct {
AssetProfile map[string]interface{} `json:"assetProfile,omitempty"`
SummaryDetail map[string]interface{} `json:"summaryDetail,omitempty"`
DefaultKeyStatistics map[string]interface{} `json:"defaultKeyStatistics,omitempty"`
FinancialData map[string]interface{} `json:"financialData,omitempty"`
QuoteType map[string]interface{} `json:"quoteType,omitempty"`
Price map[string]interface{} `json:"price,omitempty"`
CalendarEvents map[string]interface{} `json:"calendarEvents,omitempty"`
}
type Recommendation
Recommendation represents analyst recommendation counts for a period.
type Recommendation struct {
Period string `json:"period"` // "0m", "-1m", "-2m", "-3m"
StrongBuy int `json:"strongBuy"`
Buy int `json:"buy"`
Hold int `json:"hold"`
Sell int `json:"sell"`
StrongSell int `json:"strongSell"`
}
func (*Recommendation) Total
Total returns total number of recommendations.
type RecommendationTrend
RecommendationTrend represents analyst recommendations over time.
type RepairOptions
RepairOptions provides fine-grained control over which repairs to apply.
type RepairOptions struct {
// FixUnitMixups repairs 100x currency errors ($/cents, £/pence)
FixUnitMixups bool `json:"fixUnitMixups,omitempty"`
// FixZeroes repairs missing/zero price values
FixZeroes bool `json:"fixZeroes,omitempty"`
// FixSplits repairs bad stock split adjustments
FixSplits bool `json:"fixSplits,omitempty"`
// FixDividends repairs bad dividend adjustments
FixDividends bool `json:"fixDividends,omitempty"`
// FixCapitalGains repairs capital gains double-counting (ETF/MutualFund only)
FixCapitalGains bool `json:"fixCapitalGains,omitempty"`
}
func DefaultRepairOptions
DefaultRepairOptions returns options with all repairs enabled.
type ResearchReport
ResearchReport represents a research report.
type ResearchReport struct {
// ID is the unique report identifier.
ID string `json:"id,omitempty"`
// Title is the report title.
Title string `json:"title,omitempty"`
// Provider is the report provider name.
Provider string `json:"provider,omitempty"`
// PublishDate is the publication date.
PublishDate string `json:"publish_date,omitempty"`
// Summary is a brief summary of the report.
Summary string `json:"summary,omitempty"`
}
type RevenueEstimate
RevenueEstimate represents revenue estimates for a period.
type RevenueEstimate struct {
Period string `json:"period"`
EndDate string `json:"endDate"`
NumberOfAnalysts int `json:"numberOfAnalysts"`
Avg float64 `json:"avg"`
Low float64 `json:"low"`
High float64 `json:"high"`
YearAgoRevenue float64 `json:"yearAgoRevenue"`
Growth float64 `json:"growth"`
}
type ScreenerParams
ScreenerParams represents parameters for the Screen function.
type ScreenerParams struct {
// Offset is the result offset for pagination (default 0).
Offset int
// Count is the number of results to return (default 25, max 250).
Count int
// SortField is the field to sort by (default "ticker").
SortField string
// SortAsc sorts in ascending order if true (default false/descending).
SortAsc bool
}
func DefaultScreenerParams
DefaultScreenerParams returns default screener parameters.
type ScreenerQuery
ScreenerQuery represents a custom screener query.
type ScreenerQuery struct {
// Operator is the query operator (eq, gt, lt, and, or, etc.).
Operator QueryOperator `json:"operator"`
// Operands contains the operands for this query.
// For comparison operators: [fieldName, value] or [fieldName, min, max] for btwn
// For logical operators: nested ScreenerQuery objects
Operands []interface{} `json:"operands"`
}
func NewEquityQuery
NewEquityQuery creates a new equity screener query.
Example:
// Find US tech stocks with price > $10
q := models.NewEquityQuery(models.OpAND, []interface{}{
models.NewEquityQuery(models.OpEQ, []interface{}{"region", "us"}),
models.NewEquityQuery(models.OpEQ, []interface{}{"sector", "Technology"}),
models.NewEquityQuery(models.OpGT, []interface{}{"eodprice", 10}),
})
type ScreenerQuote
ScreenerQuote represents a single stock from screener results.
type ScreenerQuote struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// ShortName is the short company name.
ShortName string `json:"shortName,omitempty"`
// LongName is the full company name.
LongName string `json:"longName,omitempty"`
// Exchange is the exchange where the stock is traded.
Exchange string `json:"exchange,omitempty"`
// ExchangeDisp is the display name of the exchange.
ExchangeDisp string `json:"fullExchangeName,omitempty"`
// QuoteType is the type of asset.
QuoteType string `json:"quoteType,omitempty"`
// Region is the geographic region.
Region string `json:"region,omitempty"`
// Sector is the sector of the company.
Sector string `json:"sector,omitempty"`
// Industry is the industry of the company.
Industry string `json:"industry,omitempty"`
// Currency is the trading currency.
Currency string `json:"currency,omitempty"`
// MarketState is the current market state (PRE, REGULAR, POST, CLOSED).
MarketState string `json:"marketState,omitempty"`
// RegularMarketPrice is the current/last regular market price.
RegularMarketPrice float64 `json:"regularMarketPrice,omitempty"`
// RegularMarketChange is the price change.
RegularMarketChange float64 `json:"regularMarketChange,omitempty"`
// RegularMarketChangePercent is the percentage change.
RegularMarketChangePercent float64 `json:"regularMarketChangePercent,omitempty"`
// RegularMarketVolume is the trading volume.
RegularMarketVolume int64 `json:"regularMarketVolume,omitempty"`
// RegularMarketDayHigh is the day's high price.
RegularMarketDayHigh float64 `json:"regularMarketDayHigh,omitempty"`
// RegularMarketDayLow is the day's low price.
RegularMarketDayLow float64 `json:"regularMarketDayLow,omitempty"`
// RegularMarketOpen is the opening price.
RegularMarketOpen float64 `json:"regularMarketOpen,omitempty"`
// RegularMarketPreviousClose is the previous close price.
RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose,omitempty"`
// MarketCap is the market capitalization.
MarketCap int64 `json:"marketCap,omitempty"`
// FiftyTwoWeekHigh is the 52-week high price.
FiftyTwoWeekHigh float64 `json:"fiftyTwoWeekHigh,omitempty"`
// FiftyTwoWeekLow is the 52-week low price.
FiftyTwoWeekLow float64 `json:"fiftyTwoWeekLow,omitempty"`
// FiftyTwoWeekChange is the 52-week change percentage.
FiftyTwoWeekChange float64 `json:"fiftyTwoWeekChangePercent,omitempty"`
// FiftyDayAverage is the 50-day average price.
FiftyDayAverage float64 `json:"fiftyDayAverage,omitempty"`
// TwoHundredDayAverage is the 200-day average price.
TwoHundredDayAverage float64 `json:"twoHundredDayAverage,omitempty"`
// AverageVolume is the average trading volume.
AverageVolume int64 `json:"averageDailyVolume3Month,omitempty"`
// TrailingPE is the trailing P/E ratio.
TrailingPE float64 `json:"trailingPE,omitempty"`
// ForwardPE is the forward P/E ratio.
ForwardPE float64 `json:"forwardPE,omitempty"`
// PriceToBook is the price to book ratio.
PriceToBook float64 `json:"priceToBook,omitempty"`
// DividendYield is the dividend yield.
DividendYield float64 `json:"dividendYield,omitempty"`
// TrailingEPS is the trailing earnings per share.
TrailingEPS float64 `json:"epsTrailingTwelveMonths,omitempty"`
// BookValue is the book value per share.
BookValue float64 `json:"bookValue,omitempty"`
}
type ScreenerResponse
ScreenerResponse represents the raw API response from Yahoo Finance screener.
type ScreenerResponse struct {
Finance struct {
Result []struct {
Total int `json:"total"`
Count int `json:"count"`
Quotes []map[string]interface{} `json:"quotes"`
} `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error"`
} `json:"finance"`
}
type ScreenerResult
ScreenerResult represents the result from a stock screener query.
Example:
result, err := screener.Screen(screener.DayGainers, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d stocks\n", result.Total)
for _, quote := range result.Quotes {
fmt.Printf("%s: %.2f%%\n", quote.Symbol, quote.PercentChange)
}
type ScreenerResult struct {
// Total is the total number of matching results.
Total int `json:"total"`
// Count is the number of results returned in this batch.
Count int `json:"count"`
// Offset is the offset used for pagination.
Offset int `json:"offset"`
// Quotes contains the matching stocks.
Quotes []ScreenerQuote `json:"quotes"`
}
type SearchList
SearchList represents a Yahoo Finance list from search results.
type SearchList struct {
// ID is the list identifier.
ID string `json:"id"`
// Name is the list name.
Name string `json:"name"`
// Description is the list description.
Description string `json:"description,omitempty"`
// SymbolCount is the number of symbols in the list.
SymbolCount int `json:"symbolCount,omitempty"`
// URL is the link to the list.
URL string `json:"url,omitempty"`
}
type SearchNav
SearchNav represents a navigation link from search results.
type SearchNav struct {
// Name is the navigation item name.
Name string `json:"name"`
// URL is the navigation URL.
URL string `json:"url"`
}
type SearchNews
SearchNews represents a news article from search results.
type SearchNews struct {
// UUID is the unique identifier for the news article.
UUID string `json:"uuid"`
// Title is the headline of the article.
Title string `json:"title"`
// Publisher is the source of the article.
Publisher string `json:"publisher"`
// Link is the URL to the article.
Link string `json:"link"`
// PublishTime is the Unix timestamp when the article was published.
PublishTime int64 `json:"providerPublishTime"`
// Type is the news type (e.g., "STORY").
Type string `json:"type,omitempty"`
// Thumbnail contains thumbnail image information.
Thumbnail *SearchThumbnail `json:"thumbnail,omitempty"`
// RelatedTickers contains symbols related to this news.
RelatedTickers []string `json:"relatedTickers,omitempty"`
}
type SearchParams
SearchParams represents parameters for the Search function.
type SearchParams struct {
// Query is the search query (required).
Query string
// MaxResults is the maximum number of stock quotes to return (default 8).
MaxResults int
// NewsCount is the number of news articles to return (default 8).
NewsCount int
// ListsCount is the number of lists to return (default 8).
ListsCount int
// IncludeResearch includes research reports in results.
IncludeResearch bool
// IncludeNav includes navigation links in results.
IncludeNav bool
// EnableFuzzyQuery enables fuzzy matching for typos.
EnableFuzzyQuery bool
}
func DefaultSearchParams
DefaultSearchParams returns default search parameters.
type SearchQuote
SearchQuote represents a single quote result from search.
type SearchQuote struct {
// Symbol is the ticker symbol.
Symbol string `json:"symbol"`
// ShortName is the short company name.
ShortName string `json:"shortname"`
// LongName is the full company name.
LongName string `json:"longname,omitempty"`
// Exchange is the exchange where the asset is traded.
Exchange string `json:"exchange"`
// ExchangeDisp is the display name of the exchange.
ExchangeDisp string `json:"exchDisp,omitempty"`
// QuoteType is the type of asset (EQUITY, ETF, MUTUALFUND, etc.).
QuoteType string `json:"quoteType"`
// TypeDisp is the display name of the asset type.
TypeDisp string `json:"typeDisp,omitempty"`
// Score is the relevance score of this result.
Score float64 `json:"score,omitempty"`
// IsYahooFinance indicates if this is a Yahoo Finance asset.
IsYahooFinance bool `json:"isYahooFinance,omitempty"`
// Industry is the industry of the company.
Industry string `json:"industry,omitempty"`
// Sector is the sector of the company.
Sector string `json:"sector,omitempty"`
}
type SearchResearch
SearchResearch represents a research report from search results.
type SearchResearch struct {
// ReportID is the unique identifier.
ReportID string `json:"reportId"`
// Title is the report title.
Title string `json:"title"`
// Provider is the research provider.
Provider string `json:"provider"`
// Ticker is the related ticker symbol.
Ticker string `json:"ticker,omitempty"`
// PublishDate is the publication date.
PublishDate string `json:"publishDate,omitempty"`
}
type SearchResponse
SearchResponse represents the raw API response from Yahoo Finance search.
type SearchResponse struct {
Quotes []map[string]interface{} `json:"quotes"`
News []map[string]interface{} `json:"news"`
Lists []map[string]interface{} `json:"lists,omitempty"`
Research []map[string]interface{} `json:"researchReports,omitempty"`
Nav []map[string]interface{} `json:"nav,omitempty"`
Count int `json:"count,omitempty"`
}
type SearchResult
SearchResult represents the complete search response from Yahoo Finance.
This includes quotes (stock matches), news articles, lists, and research reports.
Example:
result, err := search.Search("AAPL")
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %s\n", quote.Symbol, quote.ShortName)
}
type SearchResult struct {
// Quotes contains matching stock/asset quotes.
Quotes []SearchQuote `json:"quotes"`
// News contains related news articles.
News []SearchNews `json:"news,omitempty"`
// Lists contains Yahoo Finance lists.
Lists []SearchList `json:"lists,omitempty"`
// Research contains research reports (if requested).
Research []SearchResearch `json:"research,omitempty"`
// Nav contains navigation links (if requested).
Nav []SearchNav `json:"nav,omitempty"`
// TotalCount is the total number of matching results.
TotalCount int `json:"totalCount,omitempty"`
}
type SearchThumbnail
SearchThumbnail represents thumbnail image information.
type SectorData
SectorData contains all data for a sector.
This includes overview information, top companies, industries, top ETFs, and top mutual funds.
Example:
s, err := sector.New("technology")
if err != nil {
log.Fatal(err)
}
data, err := s.Data()
fmt.Printf("Sector: %s has %d companies\n", data.Name, data.Overview.CompaniesCount)
type SectorData struct {
// Key is the sector identifier.
Key string `json:"key"`
// Name is the display name of the sector.
Name string `json:"name"`
// Symbol is the associated symbol (e.g., index symbol).
Symbol string `json:"symbol,omitempty"`
// Overview contains sector overview information.
Overview SectorOverview `json:"overview"`
// TopCompanies lists the top companies in the sector.
TopCompanies []SectorTopCompany `json:"top_companies,omitempty"`
// Industries lists the industries within the sector.
Industries []SectorIndustry `json:"industries,omitempty"`
// TopETFs maps ETF symbols to names.
TopETFs map[string]string `json:"top_etfs,omitempty"`
// TopMutualFunds maps mutual fund symbols to names.
TopMutualFunds map[string]string `json:"top_mutual_funds,omitempty"`
// ResearchReports contains research reports for the sector.
ResearchReports []ResearchReport `json:"research_reports,omitempty"`
}
type SectorIndustry
SectorIndustry represents an industry within a sector.
type SectorIndustry struct {
// Key is the unique identifier for the industry.
Key string `json:"key"`
// Name is the display name of the industry.
Name string `json:"name"`
// Symbol is the associated symbol.
Symbol string `json:"symbol,omitempty"`
// MarketWeight is the industry's weight within the sector.
MarketWeight float64 `json:"market_weight,omitempty"`
}
type SectorOverview
SectorOverview contains overview information for a sector.
type SectorOverview struct {
// CompaniesCount is the number of companies in the sector.
CompaniesCount int `json:"companies_count,omitempty"`
// MarketCap is the total market capitalization of the sector.
MarketCap float64 `json:"market_cap,omitempty"`
// MessageBoardID is the Yahoo Finance message board identifier.
MessageBoardID string `json:"message_board_id,omitempty"`
// Description is a text description of the sector.
Description string `json:"description,omitempty"`
// IndustriesCount is the number of industries in the sector.
IndustriesCount int `json:"industries_count,omitempty"`
// MarketWeight is the sector's weight in the market.
MarketWeight float64 `json:"market_weight,omitempty"`
// EmployeeCount is the total number of employees in the sector.
EmployeeCount int64 `json:"employee_count,omitempty"`
}
type SectorResponse
SectorResponse represents the raw API response for sector data.
type SectorResponse struct {
Data struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
Overview map[string]interface{} `json:"overview"`
TopCompanies []map[string]interface{} `json:"topCompanies"`
Industries []map[string]interface{} `json:"industries"`
TopETFs []map[string]interface{} `json:"topETFs"`
TopMutualFunds []map[string]interface{} `json:"topMutualFunds"`
ResearchReports []map[string]interface{} `json:"researchReports"`
} `json:"data"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error,omitempty"`
}
type SectorTopCompany
SectorTopCompany represents a top company within a sector.
type SectorTopCompany struct {
// Symbol is the stock ticker symbol.
Symbol string `json:"symbol"`
// Name is the company name.
Name string `json:"name"`
// Rating is the analyst rating.
Rating string `json:"rating,omitempty"`
// MarketWeight is the company's weight within the sector.
MarketWeight float64 `json:"market_weight,omitempty"`
}
type Split
Split represents a stock split.
type Split struct {
Date time.Time `json:"date"`
Numerator float64 `json:"numerator"`
Denominator float64 `json:"denominator"`
Ratio string `json:"ratio"` // e.g., "4:1"
}
type SplitEvent
SplitEvent represents a stock split event in chart response.
type SplitEvent struct {
Date int64 `json:"date"`
Numerator float64 `json:"numerator"`
Denominator float64 `json:"denominator"`
SplitRatio string `json:"splitRatio"`
}
type ThumbnailResolution
ThumbnailResolution represents a single thumbnail resolution.
type ThumbnailResolution struct {
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
Tag string `json:"tag,omitempty"`
}
type TimeseriesDataPoint
TimeseriesDataPoint represents a single data point in the timeseries.
type TimeseriesDataPoint struct {
AsOfDate string `json:"asOfDate"`
CurrencyCode string `json:"currencyCode"`
DataID int `json:"dataId"`
PeriodType string `json:"periodType"`
ReportedValue struct {
Fmt string `json:"fmt"`
Raw float64 `json:"raw"`
} `json:"reportedValue"`
}
type TimeseriesResponse
TimeseriesResponse represents the API response from fundamentals-timeseries endpoint.
type TimeseriesResponse struct {
Timeseries struct {
Result []TimeseriesResult `json:"result"`
Error *struct {
Code string `json:"code"`
Description string `json:"description"`
} `json:"error"`
} `json:"timeseries"`
}
type TimeseriesResult
TimeseriesResult represents a single result item in the timeseries response. The actual data is in a dynamically named field matching the type (e.g., "annualTotalRevenue").
type TimeseriesResult struct {
Meta struct {
Symbol []string `json:"symbol"`
Type []string `json:"type"`
} `json:"meta"`
Timestamp []int64 `json:"timestamp"`
// Raw data - we'll unmarshal this separately
RawData []TimeseriesDataPoint `json:"-"`
}
type TransactionStats
TransactionStats represents statistics for a type of transaction.
type TransactionStats struct {
// Shares is the number of shares involved.
Shares int64 `json:"shares"`
// Transactions is the number of transactions.
Transactions int `json:"transactions"`
}
multi
Package multi provides functionality for downloading data for multiple tickers.
Overview
The multi package allows you to efficiently download historical data for multiple stock symbols at once, with optional parallel processing.
Basic Usage
result, err := multi.Download([]string{"AAPL", "MSFT", "GOOGL"}, nil)
if err != nil {
log.Fatal(err)
}
for symbol, bars := range result.Data {
fmt.Printf("%s: %d bars\n", symbol, len(bars))
}
With Parameters
params := &models.DownloadParams{
Period: "3mo",
Interval: "1d",
Threads: 4,
}
result, err := multi.Download([]string{"AAPL", "MSFT"}, params)
Tickers Class
tickers, err := multi.NewTickers([]string{"AAPL", "MSFT", "GOOGL"})
if err != nil {
log.Fatal(err)
}
defer tickers.Close()
// Access individual ticker
aapl := tickers.Get("AAPL")
info, _ := aapl.Info()
// Download history for all
result, _ := tickers.History(nil)
Thread Safety
All multi package functions are safe for concurrent use.
Index
- func Download(symbols []string, params *models.DownloadParams) (*models.MultiTickerResult, error)
- func DownloadString(tickerStr string, params *models.DownloadParams) (*models.MultiTickerResult, error)
- type Option
- func WithClient(c *client.Client) Option
- type Tickers
- func NewTickers(symbols []string, opts ...Option) (*Tickers, error)
- func NewTickersFromString(tickerStr string, opts ...Option) (*Tickers, error)
- func (t *Tickers) Close()
- func (t *Tickers) Count() int
- func (t *Tickers) Download() (*models.MultiTickerResult, error)
- func (t *Tickers) Get(symbol string) *ticker.Ticker
- func (t *Tickers) History(params *models.DownloadParams) (*models.MultiTickerResult, error)
- func (t *Tickers) Symbols() []string
func Download
Download is a convenience function to download data for multiple tickers.
Example:
result, err := multi.Download([]string{"AAPL", "MSFT"}, nil)
if err != nil {
log.Fatal(err)
}
for symbol, bars := range result.Data {
fmt.Printf("%s: %d bars\n", symbol, len(bars))
}
func DownloadString
func DownloadString(tickerStr string, params *models.DownloadParams) (*models.MultiTickerResult, error)
DownloadString is like Download but accepts a space/comma separated string.
Example:
type Option
Option is a function that configures Tickers.
func WithClient
WithClient sets a custom HTTP client.
type Tickers
Tickers represents a collection of multiple ticker symbols.
func NewTickers
NewTickers creates a new Tickers instance for multiple symbols.
Symbols can be provided as a slice of strings.
Example:
tickers, err := multi.NewTickers([]string{"AAPL", "MSFT", "GOOGL"})
if err != nil {
log.Fatal(err)
}
defer tickers.Close()
func NewTickersFromString
NewTickersFromString creates Tickers from a space or comma separated string.
Example:
tickers, err := multi.NewTickersFromString("AAPL MSFT GOOGL")
// or
tickers, err := multi.NewTickersFromString("AAPL,MSFT,GOOGL")
func (*Tickers) Close
Close releases all resources used by Tickers.
func (*Tickers) Count
Count returns the number of tickers.
func (*Tickers) Download
Download downloads historical data for all tickers with default parameters.
func (*Tickers) Get
Get returns the Ticker instance for a specific symbol.
Returns nil if the symbol is not found.
func (*Tickers) History
History downloads historical data for all tickers.
Example:
func (*Tickers) Symbols
Symbols returns the list of ticker symbols.
repair
Package repair provides price data repair functionality for financial time series.
This package detects and corrects common data quality issues in Yahoo Finance data, including 100x currency errors, bad stock split adjustments, dividend double-counting, capital gains double-counting, and missing/zero values.
Overview
Yahoo Finance data sometimes contains errors that need to be repaired:
- 100x errors: Price appears in cents instead of dollars (or vice versa)
- Bad stock splits: Split adjustments not applied or applied incorrectly
- Bad dividends: Dividend adjustments not applied correctly
- Capital gains double-counting: For ETFs/MutualFunds, capital gains counted twice
- Zero/missing values: Prices showing as 0 or NaN
Usage
Create a Repairer and call Repair on your bar data:
opts := repair.DefaultOptions()
opts.Interval = "1d"
opts.QuoteType = "ETF"
repairer := repair.New(opts)
repairedBars, err := repairer.Repair(bars)
Repair Options
Individual repair functions can be enabled/disabled:
opts := repair.Options{
FixUnitMixups: true, // Fix 100x errors
FixZeroes: true, // Fix zero/missing values
FixSplits: true, // Fix stock split errors
FixDividends: true, // Fix dividend adjustment errors
FixCapitalGains: true, // Fix capital gains double-counting
}
Capital Gains Repair \(v1.1.0\)
For ETFs and Mutual Funds, Yahoo Finance sometimes double-counts capital gains in the Adjusted Close calculation. This repair detects and corrects this issue:
// Only applies to ETF and MUTUALFUND quote types
opts.QuoteType = "ETF"
opts.FixCapitalGains = true
The algorithm compares price drops on distribution days against expected drops based on dividend vs dividend+capital_gains to detect double-counting.
Stock Split Repair
Detects when Yahoo fails to apply stock split adjustments to historical data:
Uses IQR-based outlier detection to identify suspicious price changes that match the split ratio, then applies corrections.
This package is designed to match the behavior of Python yfinance's price repair functionality.
Index
- func CountRepaired(bars []models.Bar) int
- func DetectBadDividends(bars []models.Bar, currency string) []int
- func DetectBadSplits(bars []models.Bar) []int
- func DetectUnitMixups(bars []models.Bar) []int
- func DetectZeroes(bars []models.Bar) []int
- func HasCapitalGains(bars []models.Bar) bool
- func HasDividends(bars []models.Bar) bool
- func HasSplits(bars []models.Bar) bool
- type CapitalGainsRepairStats
- type DividendInfo
- type DividendRepairStats
- type Options
- func DefaultOptions() Options
- type QuoteType
- type Repairer
- func New(opts Options) *Repairer
- func (r *Repairer) AnalyzeCapitalGains(bars []models.Bar) CapitalGainsRepairStats
- func (r *Repairer) AnalyzeDividends(bars []models.Bar) DividendRepairStats
- func (r *Repairer) AnalyzeSplits(bars []models.Bar) SplitRepairStats
- func (r *Repairer) AnalyzeUnitMixups(bars []models.Bar) UnitMixupStats
- func (r *Repairer) AnalyzeZeroes(bars []models.Bar) ZeroRepairStats
- func (r *Repairer) Repair(bars []models.Bar) ([]models.Bar, error)
- type SplitInfo
- type SplitRepairStats
- type UnitMixupStats
- type ZeroRepairStats
func CountRepaired
CountRepaired counts how many bars have been repaired.
func DetectBadDividends
DetectBadDividends checks if there are dividend issues in the data. Returns indices of bars with suspected dividend problems.
func DetectBadSplits
DetectBadSplits checks if there are unadjusted splits in the data.
func DetectUnitMixups
DetectUnitMixups checks if there are 100x errors in the data. Returns indices of bars with suspected 100x errors.
func DetectZeroes
DetectZeroes checks for bars with zero/missing values. Returns indices of bars that may need repair.
func HasCapitalGains
HasCapitalGains checks if any bar has capital gains data.
func HasDividends
HasDividends checks if any bar has dividend data.
func HasSplits
HasSplits checks if any bar has split data.
type CapitalGainsRepairStats
CapitalGainsRepairStats returns statistics about capital gains repair.
type CapitalGainsRepairStats struct {
TotalEvents int // Number of capital gains events
DoubleCountEvents int // Number detected as double-counted
DoubleCountRatio float64 // Ratio of double-counted events
RepairApplied bool // Whether repair was applied
BarsRepaired int // Number of bars that were repaired
}
type DividendInfo
DividendInfo contains information about a single dividend.
type DividendInfo struct {
Date time.Time
Amount float64
IsMissingAdj bool
IsTooSmall bool
IsTooLarge bool
IsPhantom bool
WasRepaired bool
}
type DividendRepairStats
DividendRepairStats contains statistics about dividend repairs.
type DividendRepairStats struct {
TotalDividends int // Number of dividend events found
MissingAdj int // Dividends with missing adjustment
TooSmall int // Dividends 100x too small
TooLarge int // Dividends 100x too big
Phantoms int // Phantom (duplicate) dividends
BarsRepaired int // Total bars modified
Dividends []DividendInfo // Details of each dividend
}
type Options
Options configures the repair behavior.
type Options struct {
// Data context
Ticker string // Ticker symbol
Interval string // Data interval (1d, 1wk, 1mo, etc.)
Timezone string // Exchange timezone
Currency string // Price currency
QuoteType QuoteType // Type of instrument (EQUITY, ETF, MUTUALFUND, etc.)
// Feature flags - which repairs to apply
FixUnitMixups bool // Fix 100x currency errors ($/cents, £/pence)
FixZeroes bool // Fix missing/zero values
FixSplits bool // Fix bad stock split adjustments
FixDividends bool // Fix bad dividend adjustments
FixCapitalGains bool // Fix capital gains double-counting (ETF/MutualFund only)
}
func DefaultOptions
DefaultOptions returns options with all repairs enabled.
type QuoteType
QuoteType represents the type of financial instrument.
const (
QuoteTypeEquity QuoteType = "EQUITY"
QuoteTypeETF QuoteType = "ETF"
QuoteTypeMutualFund QuoteType = "MUTUALFUND"
QuoteTypeIndex QuoteType = "INDEX"
QuoteTypeCurrency QuoteType = "CURRENCY"
QuoteTypeCrypto QuoteType = "CRYPTOCURRENCY"
)
type Repairer
Repairer handles price data repair operations.
func New
New creates a new Repairer with the given options.
func (*Repairer) AnalyzeCapitalGains
AnalyzeCapitalGains analyzes bars for capital gains issues without modifying. Useful for debugging and understanding the data.
func (*Repairer) AnalyzeDividends
AnalyzeDividends analyzes bars for dividend issues without modifying.
func (*Repairer) AnalyzeSplits
AnalyzeSplits analyzes bars for split issues without modifying.
func (*Repairer) AnalyzeUnitMixups
AnalyzeUnitMixups analyzes bars for 100x errors without modifying.
func (*Repairer) AnalyzeZeroes
AnalyzeZeroes analyzes bars for zero/missing values without modifying.
func (*Repairer) Repair
Repair applies all enabled repair operations to the bar data. The order of operations matters:
- Fix dividend adjustments (must come before price-level errors)
- Fix 100x unit errors
- Fix stock split errors
- Fix zero/missing values
- Fix capital gains double-counting (last, needs clean adjustment data)
Returns the repaired bars and any error encountered.
type SplitInfo
SplitInfo contains information about a single split.
type SplitRepairStats
SplitRepairStats contains statistics about split repair.
type SplitRepairStats struct {
TotalSplits int // Number of split events found
SplitsRepaired int // Number of splits that were repaired
BarsRepaired int // Total bars modified
Splits []SplitInfo // Details of each split
}
type UnitMixupStats
UnitMixupStats contains statistics about unit mixup repairs.
type UnitMixupStats struct {
TotalBars int // Total bars analyzed
BarsRepaired int // Bars with 100x errors fixed
HasUnitSwitch bool // Whether a permanent unit switch was detected
SwitchIndex int // Index where unit switch occurred (-1 if none)
RandomMixupCount int // Number of random 100x errors found
}
type ZeroRepairStats
ZeroRepairStats contains statistics about zero value repairs.
type ZeroRepairStats struct {
TotalBars int // Total bars analyzed
ZeroBars int // Bars with zero prices
PartialZeroBars int // Bars with some zero values
ZeroVolumeBars int // Bars with zero volume but price changed
BarsRepaired int // Total bars repaired
}
screener
Package screener provides Yahoo Finance stock screener functionality.
Overview
The screener package allows you to filter stocks based on various criteria using Yahoo Finance's predefined screeners or custom queries.
Predefined Screeners
Yahoo Finance provides several predefined screeners:
- day_gainers: Stocks with highest percentage gain today
- day_losers: Stocks with highest percentage loss today
- most_actives: Stocks with highest trading volume
- aggressive_small_caps: Aggressive small cap stocks
- growth_technology_stocks: Growth technology stocks
- undervalued_growth_stocks: Undervalued growth stocks
- undervalued_large_caps: Undervalued large cap stocks
- most_shorted_stocks: Most shorted stocks
- small_cap_gainers: Small cap gainers
Basic Usage
s, err := screener.New()
if err != nil {
log.Fatal(err)
}
defer s.Close()
result, err := s.DayGainers(10)
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %.2f%%\n", quote.Symbol, quote.RegularMarketChangePercent)
}
Screener Methods
The Screener struct provides the following methods:
Predefined Screeners:
- Screener.Screen: Use any predefined screener
- Screener.DayGainers: Top gaining stocks
- Screener.DayLosers: Top losing stocks
- Screener.MostActives: Most actively traded stocks
Custom Queries:
- Screener.ScreenWithQuery: Use custom query criteria
Custom Queries
Build custom queries using [models.ScreenerQuery]:
// Find US tech stocks with price > $50
query := models.NewEquityQuery(models.OpAND, []interface{}{
models.NewEquityQuery(models.OpEQ, []interface{}{"region", "us"}),
models.NewEquityQuery(models.OpEQ, []interface{}{"sector", "Technology"}),
models.NewEquityQuery(models.OpGT, []interface{}{"intradayprice", 50}),
})
result, err := s.ScreenWithQuery(query, nil)
Query Operators
Available operators for custom queries:
- OpEQ: Equals
- OpGT: Greater than
- OpLT: Less than
- OpGTE: Greater than or equal
- OpLTE: Less than or equal
- OpBTWN: Between (requires min and max values)
- OpAND: All conditions must match
- OpOR: Any condition can match
Thread Safety
All Screener methods are safe for concurrent use from multiple goroutines.
Package screener provides Yahoo Finance stock screener functionality.
Overview
The screener package allows you to filter stocks based on various criteria using Yahoo Finance's predefined screeners or custom queries.
Predefined Screeners
Yahoo Finance provides several predefined screeners:
- day_gainers: Stocks with highest percentage gain today
- day_losers: Stocks with highest percentage loss today
- most_actives: Stocks with highest trading volume
- aggressive_small_caps: Aggressive small cap stocks
- growth_technology_stocks: Growth technology stocks
- undervalued_growth_stocks: Undervalued growth stocks
- undervalued_large_caps: Undervalued large cap stocks
- most_shorted_stocks: Most shorted stocks
- small_cap_gainers: Small cap gainers
Basic Usage
s, err := screener.New()
if err != nil {
log.Fatal(err)
}
defer s.Close()
// Use predefined screener
result, err := s.Screen(models.ScreenerDayGainers, nil)
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %.2f%%\n", quote.Symbol, quote.RegularMarketChangePercent)
}
Custom Queries
// Find US tech stocks with price > $50
query := models.NewEquityQuery(models.OpAND, []interface{}{
models.NewEquityQuery(models.OpEQ, []interface{}{"region", "us"}),
models.NewEquityQuery(models.OpEQ, []interface{}{"sector", "Technology"}),
models.NewEquityQuery(models.OpGT, []interface{}{"intradayprice", 50}),
})
result, err := s.ScreenWithQuery(query, nil)
Thread Safety
All Screener methods are safe for concurrent use from multiple goroutines.
Index
- type Option
- func WithClient(c *client.Client) Option
- type Screener
- func New(opts ...Option) (*Screener, error)
- func (s *Screener) Close()
- func (s *Screener) DayGainers(count int) (*models.ScreenerResult, error)
- func (s *Screener) DayLosers(count int) (*models.ScreenerResult, error)
- func (s *Screener) MostActives(count int) (*models.ScreenerResult, error)
- func (s *Screener) Screen(screener models.PredefinedScreener, params *models.ScreenerParams) (*models.ScreenerResult, error)
- func (s *Screener) ScreenWithQuery(query *models.ScreenerQuery, params *models.ScreenerParams) (*models.ScreenerResult, error)
type Option
Option is a function that configures a Screener instance.
func WithClient
WithClient sets a custom HTTP client.
type Screener
Screener provides Yahoo Finance stock screener functionality.
func New
New creates a new Screener instance.
Example:
func (*Screener) Close
Close releases resources used by the Screener instance.
func (*Screener) DayGainers
DayGainers returns stocks with the highest percentage gain today.
Example:
result, err := s.DayGainers(10)
for _, quote := range result.Quotes {
fmt.Printf("%s: +%.2f%%\n", quote.Symbol, quote.RegularMarketChangePercent)
}
func (*Screener) DayLosers
DayLosers returns stocks with the highest percentage loss today.
Example:
result, err := s.DayLosers(10)
for _, quote := range result.Quotes {
fmt.Printf("%s: %.2f%%\n", quote.Symbol, quote.RegularMarketChangePercent)
}
func (*Screener) MostActives
MostActives returns stocks with the highest trading volume today.
Example:
result, err := s.MostActives(10)
for _, quote := range result.Quotes {
fmt.Printf("%s: %d shares\n", quote.Symbol, quote.RegularMarketVolume)
}
func (*Screener) Screen
func (s *Screener) Screen(screener models.PredefinedScreener, params *models.ScreenerParams) (*models.ScreenerResult, error)
Screen uses a predefined screener to find matching stocks.
Example:
result, err := s.Screen(models.ScreenerDayGainers, nil)
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %.2f%%\n", quote.Symbol, quote.RegularMarketChangePercent)
}
func (*Screener) ScreenWithQuery
func (s *Screener) ScreenWithQuery(query *models.ScreenerQuery, params *models.ScreenerParams) (*models.ScreenerResult, error)
ScreenWithQuery uses a custom query to find matching stocks.
Example:
// Find US stocks with market cap > $10B
query := models.NewEquityQuery(models.OpAND, []interface{}{
models.NewEquityQuery(models.OpEQ, []interface{}{"region", "us"}),
models.NewEquityQuery(models.OpGT, []interface{}{"intradaymarketcap", 10000000000}),
})
result, err := s.ScreenWithQuery(query, nil)
search
Package search provides Yahoo Finance search functionality.
Overview
The search package allows you to search for stock symbols, company names, and other financial assets on Yahoo Finance. It also retrieves related news articles, lists, and research reports.
Basic Usage
s, err := search.New()
if err != nil {
log.Fatal(err)
}
defer s.Close()
result, err := s.Search("AAPL")
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %s (%s)\n", quote.Symbol, quote.ShortName, quote.Exchange)
}
Search Methods
The Search struct provides the following methods:
- Search.Search: Simple search with default parameters
- Search.SearchWithParams: Search with custom parameters
- Search.Quotes: Get only quote results
- Search.News: Get only news results
Search Parameters
Use [models.SearchParams] to customize your search:
params := models.SearchParams{
Query: "Apple",
MaxResults: 10,
NewsCount: 5,
EnableFuzzyQuery: true,
}
result, err := s.SearchWithParams(params)
Thread Safety
All Search methods are safe for concurrent use from multiple goroutines.
Package search provides Yahoo Finance search functionality.
Overview
The search package allows you to search for stock symbols, company names, and other financial assets on Yahoo Finance. It also retrieves related news articles, lists, and research reports.
Basic Usage
s, err := search.New()
if err != nil {
log.Fatal(err)
}
defer s.Close()
result, err := s.Search("AAPL")
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %s (%s)\n", quote.Symbol, quote.ShortName, quote.Exchange)
}
Search with Parameters
params := models.SearchParams{
Query: "Apple",
MaxResults: 10,
NewsCount: 5,
EnableFuzzyQuery: true,
}
result, err := s.SearchWithParams(params)
Thread Safety
All Search methods are safe for concurrent use from multiple goroutines.
Index
- type Option
- func WithClient(c *client.Client) Option
- type Search
- func New(opts ...Option) (*Search, error)
- func (s *Search) Close()
- func (s *Search) News(query string, newsCount int) ([]models.SearchNews, error)
- func (s *Search) Quotes(query string, maxResults int) ([]models.SearchQuote, error)
- func (s *Search) Search(query string) (*models.SearchResult, error)
- func (s *Search) SearchWithParams(params models.SearchParams) (*models.SearchResult, error)
type Option
Option is a function that configures a Search instance.
func WithClient
WithClient sets a custom HTTP client.
type Search
Search provides Yahoo Finance search functionality.
func New
New creates a new Search instance.
Example:
func (*Search) Close
Close releases resources used by the Search instance.
func (*Search) News
News returns only the news results for a search query.
Example:
news, err := s.News("Apple", 10)
for _, n := range news {
fmt.Printf("%s: %s\n", n.Publisher, n.Title)
}
func (*Search) Quotes
Quotes returns only the quote results for a search query.
Example:
quotes, err := s.Quotes("Apple", 10)
for _, q := range quotes {
fmt.Printf("%s: %s\n", q.Symbol, q.ShortName)
}
func (*Search) Search
Search searches for symbols and returns matching quotes.
This is a convenience method that uses default parameters.
Example:
result, err := s.Search("AAPL")
if err != nil {
log.Fatal(err)
}
for _, quote := range result.Quotes {
fmt.Printf("%s: %s\n", quote.Symbol, quote.ShortName)
}
func (*Search) SearchWithParams
SearchWithParams searches with custom parameters.
Example:
params := models.SearchParams{
Query: "Apple",
MaxResults: 10,
NewsCount: 5,
EnableFuzzyQuery: true,
}
result, err := s.SearchWithParams(params)
sector
Package sector provides Yahoo Finance sector data functionality.
Overview
The sector package allows retrieving financial sector information including overview data, top companies, industries within the sector, top ETFs, and top mutual funds. This is useful for sector-based analysis and screening.
Basic Usage
s, err := sector.New("technology")
if err != nil {
log.Fatal(err)
}
defer s.Close()
// Get sector overview
overview, err := s.Overview()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Companies: %d\n", overview.CompaniesCount)
fmt.Printf("Market Cap: $%.2f\n", overview.MarketCap)
Top Companies
Get the top companies within a sector:
companies, err := s.TopCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: %s (Weight: %.4f)\n",
c.Symbol, c.Name, c.MarketWeight)
}
Industries
Get industries within the sector:
industries, err := s.Industries()
if err != nil {
log.Fatal(err)
}
for _, i := range industries {
fmt.Printf("%s: %s\n", i.Key, i.Name)
}
Top ETFs and Mutual Funds
Get top ETFs and mutual funds for the sector:
Predefined Sectors
Common sector identifiers are available as constants:
s, _ := sector.NewWithPredefined(models.SectorTechnology)
s, _ := sector.NewWithPredefined(models.SectorHealthcare)
s, _ := sector.NewWithPredefined(models.SectorFinancialServices)
Available predefined sectors:
- SectorBasicMaterials: Basic Materials
- SectorCommunicationServices: Communication Services
- SectorConsumerCyclical: Consumer Cyclical
- SectorConsumerDefensive: Consumer Defensive
- SectorEnergy: Energy
- SectorFinancialServices: Financial Services
- SectorHealthcare: Healthcare
- SectorIndustrials: Industrials
- SectorRealEstate: Real Estate
- SectorTechnology: Technology
- SectorUtilities: Utilities
Caching
Sector data is cached after the first fetch. To refresh:
Custom Client
Provide a custom HTTP client:
Thread Safety
All Sector methods are safe for concurrent use from multiple goroutines.
Python Compatibility
This package implements the same functionality as Python yfinance's Sector class:
Python | Go
--------------------------------|--------------------------------
yf.Sector("technology") | sector.New("technology")
sector.key | s.Key()
sector.name | s.Name()
sector.symbol | s.Symbol()
sector.overview | s.Overview()
sector.top_companies | s.TopCompanies()
sector.industries | s.Industries()
sector.top_etfs | s.TopETFs()
sector.top_mutual_funds | s.TopMutualFunds()
sector.research_reports | s.ResearchReports()
Index
- type Option
- func WithClient(c *client.Client) Option
- type Sector
- func New(key string, opts ...Option) (*Sector, error)
- func NewWithPredefined(sector models.PredefinedSector, opts ...Option) (*Sector, error)
- func (s *Sector) ClearCache()
- func (s *Sector) Close()
- func (s *Sector) Data() (*models.SectorData, error)
- func (s *Sector) Industries() ([]models.SectorIndustry, error)
- func (s *Sector) Key() string
- func (s *Sector) Name() (string, error)
- func (s *Sector) Overview() (models.SectorOverview, error)
- func (s *Sector) ResearchReports() ([]models.ResearchReport, error)
- func (s *Sector) Symbol() (string, error)
- func (s *Sector) TopCompanies() ([]models.SectorTopCompany, error)
- func (s *Sector) TopETFs() (map[string]string, error)
- func (s *Sector) TopMutualFunds() (map[string]string, error)
type Option
Option is a function that configures a Sector instance.
func WithClient
WithClient sets a custom HTTP client for the Sector instance.
type Sector
Sector provides access to financial sector data from Yahoo Finance.
Sector allows retrieving sector-related information such as overview, top companies, industries, top ETFs, and top mutual funds.
func New
New creates a new Sector instance for the given sector key.
Sector keys are lowercase with hyphens, e.g., "technology", "basic-materials". Use predefined constants from models package for convenience.
Example:
s, err := sector.New("technology")
if err != nil {
log.Fatal(err)
}
defer s.Close()
overview, err := s.Overview()
fmt.Printf("Sector has %d companies\n", overview.CompaniesCount)
func NewWithPredefined
NewWithPredefined creates a new Sector instance using a predefined sector constant.
Example:
func (*Sector) ClearCache
ClearCache clears the cached sector data. The next call to any data method will fetch fresh data.
func (*Sector) Close
Close releases resources used by the Sector instance.
func (*Sector) Data
Data returns all sector data.
This fetches and returns the complete sector information including overview, top companies, industries, top ETFs, and mutual funds.
Example:
data, err := s.Data()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sector: %s\n", data.Name)
fmt.Printf("Companies: %d\n", data.Overview.CompaniesCount)
func (*Sector) Industries
Industries returns the industries within the sector.
Example:
industries, err := s.Industries()
if err != nil {
log.Fatal(err)
}
for _, i := range industries {
fmt.Printf("%s: %s\n", i.Key, i.Name)
}
func (*Sector) Key
Key returns the sector key.
func (*Sector) Name
Name returns the sector name.
Example:
func (*Sector) Overview
Overview returns the sector overview information.
Example:
overview, err := s.Overview()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Companies: %d\n", overview.CompaniesCount)
fmt.Printf("Market Cap: $%.2f\n", overview.MarketCap)
func (*Sector) ResearchReports
ResearchReports returns research reports for the sector.
Example:
reports, err := s.ResearchReports()
if err != nil {
log.Fatal(err)
}
for _, r := range reports {
fmt.Printf("%s: %s\n", r.Provider, r.Title)
}
func (*Sector) Symbol
Symbol returns the sector symbol.
func (*Sector) TopCompanies
TopCompanies returns the top companies in the sector.
Example:
companies, err := s.TopCompanies()
if err != nil {
log.Fatal(err)
}
for _, c := range companies {
fmt.Printf("%s: %s (Weight: %.2f%%)\n",
c.Symbol, c.Name, c.MarketWeight*100)
}
func (*Sector) TopETFs
TopETFs returns the top ETFs for the sector.
Returns a map of ETF symbols to names.
Example:
etfs, err := s.TopETFs()
if err != nil {
log.Fatal(err)
}
for symbol, name := range etfs {
fmt.Printf("%s: %s\n", symbol, name)
}
func (*Sector) TopMutualFunds
TopMutualFunds returns the top mutual funds for the sector.
Returns a map of mutual fund symbols to names.
Example:
funds, err := s.TopMutualFunds()
if err != nil {
log.Fatal(err)
}
for symbol, name := range funds {
fmt.Printf("%s: %s\n", symbol, name)
}
stats
Package stats provides statistical utility functions for price repair operations.
This package includes functions for percentile calculations, z-score computations, median filtering, and outlier detection. These utilities are essential for detecting and correcting data quality issues in financial time series.
Percentile Functions
The package provides percentile calculation using linear interpolation:
Z\-Score Functions
Z-score calculations for standardization and outlier detection:
Filtering Functions
Median filter and outlier detection for noise reduction:
These functions are designed to match the behavior of numpy and scipy functions used in the Python yfinance implementation.
Index
- func Abs(data []float64) []float64
- func All(mask []bool) bool
- func Any(mask []bool) bool
- func ClipOutliers(data []float64, multiplier float64) []float64
- func CountTrue(mask []bool) int
- func DetectOutliersByZScore(data []float64, threshold float64) []bool
- func Diff(data []float64) []float64
- func FilterByMask(data []float64, mask []bool) []float64
- func FindBlocks(mask []bool) [][2]int
- func IQR(data []float64) (q1, q3, iqr float64)
- func InlierMask(data []float64, multiplier float64) []bool
- func Mean(data []float64) float64
- func Median(data []float64) float64
- func MedianFilter(data []float64, windowSize int) []float64
- func MedianFilter2D(data [][]float64, windowSize int) [][]float64
- func MedianOfSlice(data []float64) float64
- func OHLCMedian(open, high, low, close float64) float64
- func OutlierBounds(data []float64, multiplier float64) (lower, upper float64)
- func OutlierMask(data []float64, multiplier float64) []bool
- func PctChange(data []float64) []float64
- func Percentile(data []float64, p float64) float64
- func RemoveNaN(data []float64) []float64
- func RollingMean(data []float64, windowSize int) []float64
- func RollingStd(data []float64, windowSize int) []float64
- func Std(data []float64, ddof int) float64
- func WeightedMean(data, weights []float64) float64
- func ZScore(value, mean, std float64) float64
- func ZScoreSlice(data []float64) []float64
- func ZScoreWithParams(data []float64, mean, std float64) []float64
func Abs
Abs returns absolute values of the data.
func All
All returns true if all values in the mask are true.
func Any
Any returns true if any value in the mask is true.
func ClipOutliers
ClipOutliers replaces outliers with boundary values.
func CountTrue
CountTrue counts the number of true values in a boolean slice.
func DetectOutliersByZScore
DetectOutliersByZScore identifies outliers based on z-score threshold. Returns a boolean mask where true indicates an outlier.
Parameters:
- data: slice of float64 values
- threshold: z-score threshold (typically 2.0 or 3.0)
func Diff
Diff calculates the difference between consecutive elements. Returns slice of length n-1.
func FilterByMask
FilterByMask returns elements where mask is true.
func FindBlocks
FindBlocks identifies contiguous blocks of True values in a boolean mask. Returns slice of [start, end) pairs.
func IQR
IQR calculates the interquartile range (Q3 - Q1). Returns Q1, Q3, and IQR.
The interquartile range is used for outlier detection:
- Lower bound: Q1 - 1.5 * IQR
- Upper bound: Q3 + 1.5 * IQR
func InlierMask
InlierMask creates a boolean mask for inliers (non-outliers). Returns true for values that are NOT outliers.
func Mean
Mean calculates the arithmetic mean of the data. Returns NaN for empty data.
func Median
Median calculates the median (50th percentile) of the data.
func MedianFilter
MedianFilter applies a 1D median filter to the data. This is similar to scipy.ndimage.median_filter for 1D arrays.
Parameters:
- data: input slice
- windowSize: filter window size (should be odd)
Returns filtered data with same length as input. Edge values use smaller windows.
func MedianFilter2D
MedianFilter2D applies a 2D median filter to the data matrix. This is similar to scipy.ndimage.median_filter for 2D arrays.
Parameters:
- data: 2D slice [rows][cols]
- windowSize: filter window size for both dimensions
Returns filtered 2D data.
func MedianOfSlice
MedianOfSlice calculates the median without sorting the original slice.
func OHLCMedian
OHLC calculates the median of Open, High, Low, Close values. This provides a robust estimate of the "typical" price.
func OutlierBounds
OutlierBounds calculates the lower and upper bounds for outlier detection using the IQR method with a configurable multiplier.
Parameters:
- data: slice of float64 values
- multiplier: IQR multiplier (typically 1.5 for outliers, 3.0 for extreme outliers)
Returns lower bound, upper bound.
func OutlierMask
OutlierMask creates a boolean mask for outliers using the IQR method. Returns true for values that are outliers.
Parameters:
- data: slice of float64 values
- multiplier: IQR multiplier (typically 1.5)
func PctChange
PctChange calculates the percentage change between consecutive elements. Returns slice of length n-1.
func Percentile
Percentile calculates the p-th percentile of the given data using linear interpolation. This matches numpy.percentile with default interpolation method.
Parameters:
- data: slice of float64 values
- p: percentile to compute (0-100)
Returns the percentile value. Returns NaN for empty data.
func RemoveNaN
RemoveNaN returns a new slice with NaN values removed.
func RollingMean
RollingMean calculates a rolling (moving) mean with the specified window size. Uses center alignment. Returns NaN for positions where window is incomplete.
func RollingStd
RollingStd calculates a rolling (moving) standard deviation. Uses center alignment and sample std (ddof=1).
func Std
Std calculates the standard deviation of the data. Uses n-1 denominator (sample standard deviation) by default.
Parameters:
- data: slice of float64 values
- ddof: delta degrees of freedom (0 for population, 1 for sample)
func WeightedMean
WeightedMean calculates the weighted arithmetic mean. Returns NaN if weights sum to zero or if slices have different lengths.
func ZScore
ZScore calculates the z-score (standard score) for a single value.
Z-score = (value - mean) / std
Returns NaN if std is zero or NaN.
func ZScoreSlice
ZScoreSlice calculates z-scores for all values in the data. Uses sample standard deviation (ddof=1).
func ZScoreWithParams
ZScoreWithParams calculates z-scores using provided mean and std.
ticker
Package ticker provides the main interface for accessing Yahoo Finance data.
Overview
The ticker package is the primary entry point for go-yfinance. It provides a Ticker type that represents a single stock, ETF, or fund, and offers methods to fetch various types of financial data.
Quick Start
import "github.com/wnjoon/go-yfinance/pkg/ticker"
// Create a ticker
t, err := ticker.New("AAPL")
if err != nil {
log.Fatal(err)
}
defer t.Close()
// Get current quote
quote, err := t.Quote()
// Get historical data
history, err := t.History(models.HistoryParams{
Period: "1mo",
Interval: "1d",
})
Available Data
The Ticker type provides methods for:
- Ticker.Quote: Real-time quote data
- Ticker.History: Historical OHLCV data
- Ticker.Info: Company information and key statistics
- Ticker.FastInfo: Quick-access subset of info data
- Ticker.Dividends: Dividend history
- Ticker.Splits: Stock split history
- Ticker.Actions: Combined dividends and splits
- Ticker.Options: Available option expiration dates
- Ticker.OptionChain: Full option chain data
- Ticker.IncomeStatement: Income statement data
- Ticker.BalanceSheet: Balance sheet data
- Ticker.CashFlow: Cash flow statement data
- Ticker.Recommendations: Analyst recommendations
- Ticker.AnalystPriceTargets: Analyst price targets
- Ticker.EarningsEstimate: Earnings estimates
- Ticker.RevenueEstimate: Revenue estimates
- Ticker.EPSTrend: EPS trend data
- Ticker.EPSRevisions: EPS revision data
- Ticker.EarningsHistory: Historical earnings data
- Ticker.GrowthEstimates: Growth estimates
- Ticker.MajorHolders: Major shareholders breakdown
- Ticker.InstitutionalHolders: Institutional holder list
- Ticker.MutualFundHolders: Mutual fund holder list
- Ticker.InsiderTransactions: Insider transaction history
- Ticker.InsiderRosterHolders: Company insiders list
- Ticker.InsiderPurchases: Insider purchase activity summary
- Ticker.Calendar: Upcoming events (earnings, dividends)
Caching
The Ticker automatically caches API responses to minimize redundant requests. Use Ticker.ClearCache to force a refresh of cached data.
Thread Safety
All Ticker methods are safe for concurrent use from multiple goroutines.
Package ticker provides the main Ticker interface for accessing Yahoo Finance data.
Index
- type Option
- func WithClient(c *client.Client) Option
- type Ticker
- func New(symbol string, opts ...Option) (*Ticker, error)
- func (t *Ticker) Actions() (*models.Actions, error)
- func (t *Ticker) AnalystPriceTargets() (*models.PriceTarget, error)
- func (t *Ticker) BalanceSheet(freq string) (*models.FinancialStatement, error)
- func (t *Ticker) Calendar() (*models.Calendar, error)
- func (t *Ticker) CashFlow(freq string) (*models.FinancialStatement, error)
- func (t *Ticker) ClearCache()
- func (t *Ticker) Close()
- func (t *Ticker) Dividends() ([]models.Dividend, error)
- func (t *Ticker) EPSRevisions() ([]models.EPSRevision, error)
- func (t *Ticker) EPSTrend() ([]models.EPSTrend, error)
- func (t *Ticker) EarningsEstimate() ([]models.EarningsEstimate, error)
- func (t *Ticker) EarningsEstimates() ([]models.EarningsEstimate, error)
- func (t *Ticker) EarningsHistory() (*models.EarningsHistory, error)
- func (t *Ticker) FastInfo() (*models.FastInfo, error)
- func (t *Ticker) FinancialsJSON(statementType, freq string) ([]byte, error)
- func (t *Ticker) GetHistoryMetadata() *models.ChartMeta
- func (t *Ticker) GetNews() ([]models.NewsArticle, error)
- func (t *Ticker) GrowthEstimates() ([]models.GrowthEstimate, error)
- func (t *Ticker) History(params models.HistoryParams) ([]models.Bar, error)
- func (t *Ticker) HistoryPeriod(period string) ([]models.Bar, error)
- func (t *Ticker) HistoryRange(start, end time.Time, interval string) ([]models.Bar, error)
- func (t *Ticker) IncomeStatement(freq string) (*models.FinancialStatement, error)
- func (t *Ticker) Info() (*models.Info, error)
- func (t *Ticker) InsiderPurchases() (*models.InsiderPurchases, error)
- func (t *Ticker) InsiderRoster() ([]models.InsiderHolder, error)
- func (t *Ticker) InsiderRosterHolders() ([]models.InsiderHolder, error)
- func (t *Ticker) InsiderTransactions() ([]models.InsiderTransaction, error)
- func (t *Ticker) InstitutionalHolders() ([]models.Holder, error)
- func (t *Ticker) MajorHolders() (*models.MajorHolders, error)
- func (t *Ticker) MutualFundHolders() ([]models.Holder, error)
- func (t *Ticker) News(count int, tab models.NewsTab) ([]models.NewsArticle, error)
- func (t *Ticker) OptionChain(date string) (*models.OptionChain, error)
- func (t *Ticker) OptionChainAtExpiry(date time.Time) (*models.OptionChain, error)
- func (t *Ticker) Options() ([]time.Time, error)
- func (t *Ticker) OptionsJSON() ([]byte, error)
- func (t *Ticker) PriceTarget() (*models.PriceTarget, error)
- func (t *Ticker) Quote() (*models.Quote, error)
- func (t *Ticker) Recommendations() (*models.RecommendationTrend, error)
- func (t *Ticker) RevenueEstimate() ([]models.RevenueEstimate, error)
- func (t *Ticker) RevenueEstimates() ([]models.RevenueEstimate, error)
- func (t *Ticker) Splits() ([]models.Split, error)
- func (t *Ticker) Strikes() ([]float64, error)
- func (t *Ticker) Symbol() string
type Option
Option is a function that configures a Ticker.
func WithClient
WithClient sets a custom client for the Ticker.
type Ticker
Ticker represents a single stock/ETF/fund ticker.
func New
New creates a new Ticker for the given symbol.
func (*Ticker) Actions
Actions returns both dividends and splits for the ticker.
This is a convenience method that combines Ticker.Dividends and Ticker.Splits into a single response.
func (*Ticker) AnalystPriceTargets
AnalystPriceTargets returns analyst price targets. This method name matches Python yfinance's ticker.analyst_price_targets property.
func (*Ticker) BalanceSheet
BalanceSheet returns the balance sheet data.
Parameters:
- freq: "annual", "yearly", or "quarterly" (default: "annual")
Note: "yearly" is accepted as an alias for "annual" for Python yfinance compatibility.
The returned [models.FinancialStatement] contains fields like TotalAssets, TotalLiabilities, TotalEquity, CashAndCashEquivalents, TotalDebt, and WorkingCapital.
Example:
balance, err := ticker.BalanceSheet("quarterly")
if assets, ok := balance.GetLatest("TotalAssets"); ok {
fmt.Printf("Total Assets: %.2f\n", assets)
}
func (*Ticker) Calendar
Calendar returns upcoming calendar events for the ticker.
This includes dividend dates, earnings dates, and earnings estimates.
Example:
calendar, err := ticker.Calendar()
if err != nil {
log.Fatal(err)
}
if calendar.ExDividendDate != nil {
fmt.Printf("Ex-Dividend: %s\n", calendar.ExDividendDate.Format("2006-01-02"))
}
for _, date := range calendar.EarningsDate {
fmt.Printf("Earnings: %s\n", date.Format("2006-01-02"))
}
func (*Ticker) CashFlow
CashFlow returns the cash flow statement data.
Parameters:
- freq: "annual", "yearly", or "quarterly" (default: "annual")
Note: "yearly" is accepted as an alias for "annual" for Python yfinance compatibility.
The returned [models.FinancialStatement] contains fields like OperatingCashFlow, InvestingCashFlow, FinancingCashFlow, FreeCashFlow, and CapitalExpenditure.
Example:
cashFlow, err := ticker.CashFlow("annual")
if fcf, ok := cashFlow.GetLatest("FreeCashFlow"); ok {
fmt.Printf("Free Cash Flow: %.2f\n", fcf)
}
func (*Ticker) ClearCache
ClearCache clears all cached data.
func (*Ticker) Close
Close releases resources used by the Ticker. If the client was created by the Ticker, it will be closed.
func (*Ticker) Dividends
Dividends returns the dividend history for the ticker.
Returns all historical dividend payments with dates and amounts.
func (*Ticker) EPSRevisions
EPSRevisions returns EPS revision data.
func (*Ticker) EPSTrend
EPSTrend returns EPS trend data.
func (*Ticker) EarningsEstimate
EarningsEstimate returns earnings estimates for upcoming periods. This method name matches Python yfinance's ticker.earnings_estimate property.
func (*Ticker) EarningsEstimates
EarningsEstimates is a deprecated alias for EarningsEstimate. Deprecated: Use EarningsEstimate() instead for Python yfinance compatibility.
func (*Ticker) EarningsHistory
EarningsHistory returns historical earnings data.
func (*Ticker) FastInfo
FastInfo returns a FastInfo struct with commonly used data. This fetches data from the history endpoint which can be faster for some fields.
func (*Ticker) FinancialsJSON
FinancialsJSON returns raw JSON for debugging.
func (*Ticker) GetHistoryMetadata
GetHistoryMetadata returns the cached history metadata.
func (*Ticker) GetNews
GetNews is an alias for News with default parameters. It fetches 10 news articles of type "news".
Example:
func (*Ticker) GrowthEstimates
GrowthEstimates returns growth estimates comparing stock to industry/sector/index.
func (*Ticker) History
History fetches historical OHLCV data for the ticker.
The method returns a slice of [models.Bar] containing Open, High, Low, Close, Adjusted Close, and Volume data for each period.
Parameters can be configured via [models.HistoryParams]:
- Period: Time range (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
- Interval: Data granularity (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo)
- Start/End: Specific date range (overrides Period)
- PrePost: Include pre/post market data
- AutoAdjust: Adjust prices for splits/dividends
- Actions: Include dividend and split data in bars
Example:
func (*Ticker) HistoryPeriod
HistoryPeriod is a convenience method to fetch history with just a period string.
Valid periods: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
Uses daily interval with auto-adjustment enabled.
func (*Ticker) HistoryRange
HistoryRange fetches history for a specific date range.
Parameters:
- start: Start date (inclusive)
- end: End date (exclusive)
- interval: Data granularity (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo)
Uses auto-adjustment enabled by default.
func (*Ticker) IncomeStatement
IncomeStatement returns the income statement data.
Parameters:
- freq: "annual", "yearly", or "quarterly" (default: "annual")
Note: "yearly" is accepted as an alias for "annual" for Python yfinance compatibility.
The returned [models.FinancialStatement] contains fields like TotalRevenue, GrossProfit, OperatingIncome, NetIncome, EBITDA, BasicEPS, and DilutedEPS.
Example:
income, err := ticker.IncomeStatement("annual")
if revenue, ok := income.GetLatest("TotalRevenue"); ok {
fmt.Printf("Revenue: %.2f\n", revenue)
}
func (*Ticker) Info
Info fetches comprehensive company information for the ticker.
func (*Ticker) InsiderPurchases
InsiderPurchases returns insider purchase activity summary.
This summarizes net share purchases/sales by insiders over a period.
Example:
purchases, err := ticker.InsiderPurchases()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Net shares: %d (%s)\n", purchases.Net.Shares, purchases.Period)
func (*Ticker) InsiderRoster
InsiderRoster returns the list of company insiders.
Deprecated: Use InsiderRosterHolders instead.
func (*Ticker) InsiderRosterHolders
InsiderRosterHolders returns the list of company insiders.
This includes insider names, positions, and their holdings.
Example:
roster, err := ticker.InsiderRosterHolders()
if err != nil {
log.Fatal(err)
}
for _, insider := range roster {
fmt.Printf("%s (%s): %d shares\n",
insider.Name, insider.Position, insider.TotalShares())
}
func (*Ticker) InsiderTransactions
InsiderTransactions returns the list of insider transactions.
This includes purchases, sales, and other transactions by company insiders.
Example:
transactions, err := ticker.InsiderTransactions()
if err != nil {
log.Fatal(err)
}
for _, tx := range transactions {
fmt.Printf("%s: %s %d shares on %s\n",
tx.Insider, tx.Transaction, tx.Shares, tx.StartDate.Format("2006-01-02"))
}
func (*Ticker) InstitutionalHolders
InstitutionalHolders returns the list of institutional holders.
Each holder includes the institution name, shares held, value, and percentage.
Example:
holders, err := ticker.InstitutionalHolders()
if err != nil {
log.Fatal(err)
}
for _, h := range holders {
fmt.Printf("%s: %d shares (%.2f%%)\n", h.Holder, h.Shares, h.PctHeld*100)
}
func (*Ticker) MajorHolders
MajorHolders returns the major holders breakdown.
This includes percentages held by insiders, institutions, and institutional count.
Example:
holders, err := ticker.MajorHolders()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Insiders: %.2f%%\n", holders.InsidersPercentHeld*100)
fmt.Printf("Institutions: %.2f%%\n", holders.InstitutionsPercentHeld*100)
func (*Ticker) MutualFundHolders
MutualFundHolders returns the list of mutual fund holders.
Each holder includes the fund name, shares held, value, and percentage.
Example:
holders, err := ticker.MutualFundHolders()
if err != nil {
log.Fatal(err)
}
for _, h := range holders {
fmt.Printf("%s: %d shares\n", h.Holder, h.Shares)
}
func (*Ticker) News
News fetches news articles for the ticker.
Parameters:
- count: Number of articles to fetch (default: 10)
- tab: Type of news to fetch (default: NewsTabNews)
Example:
news, err := ticker.News(10, models.NewsTabNews)
if err != nil {
log.Fatal(err)
}
for _, article := range news {
fmt.Printf("%s: %s\n", article.Publisher, article.Title)
}
func (*Ticker) OptionChain
OptionChain returns the option chain for a specific expiration date. If date is empty, returns the nearest expiration.
func (*Ticker) OptionChainAtExpiry
OptionChainAtExpiry is an alias for OptionChain with a specific date.
func (*Ticker) Options
Options returns all available expiration dates for options.
func (*Ticker) OptionsJSON
OptionsJSON returns raw JSON response for debugging.
func (*Ticker) PriceTarget
PriceTarget is a deprecated alias for AnalystPriceTargets. Deprecated: Use AnalystPriceTargets() instead for Python yfinance compatibility.
func (*Ticker) Quote
Quote fetches the current quote for the ticker.
func (*Ticker) Recommendations
Recommendations returns analyst recommendation trends.
func (*Ticker) RevenueEstimate
RevenueEstimate returns revenue estimates for upcoming periods. This method name matches Python yfinance's ticker.revenue_estimate property.
func (*Ticker) RevenueEstimates
RevenueEstimates is a deprecated alias for RevenueEstimate. Deprecated: Use RevenueEstimate() instead for Python yfinance compatibility.
func (*Ticker) Splits
Splits returns the stock split history for the ticker.
Returns all historical stock splits with dates and ratios.
func (*Ticker) Strikes
Strikes returns available strike prices for options.
func (*Ticker) Symbol
Symbol returns the ticker symbol.
utils
Package utils provides utility functions for go-yfinance.
Overview
The utils package contains helper functions for common operations such as timezone handling, MIC code mapping, and exchange-specific utilities.
MIC Code Mapping \(v1.1.0\)
ISO 10383 Market Identifier Code (MIC) to Yahoo Finance suffix mapping:
suffix := utils.GetYahooSuffix("XLON") // Returns "L"
mic := utils.GetMIC("T") // Returns "XTKS"
ticker := utils.FormatYahooTicker("7203", "XTKS") // Returns "7203.T"
base, suffix := utils.ParseYahooTicker("AAPL.L") // Returns "AAPL", "L"
Check if an exchange is US-based:
List all supported exchanges:
mics := utils.AllMICs() // []string{"XNYS", "XNAS", "XLON", ...}
suffixes := utils.AllYahooSuffixes() // []string{"", "L", "T", ...}
Timezone Functions
Exchange timezone lookup:
tz := utils.GetTimezone("NYQ") // Returns "America/New_York"
tz := utils.GetTimezone("TYO") // Returns "Asia/Tokyo"
Timezone validation and conversion:
if utils.IsValidTimezone("America/New_York") {
loc := utils.LoadLocation("America/New_York")
t := utils.ConvertToTimezone(time.Now(), "America/New_York")
}
Exchange Mappings
The package includes timezone mappings for major exchanges:
- US: NYSE (NYQ), NASDAQ (NMS, NGM, NCM), BATS, OTC
- Europe: London (LSE), Frankfurt (FRA), Paris (PAR), etc.
- Asia: Tokyo (TYO), Hong Kong (HKG), Shanghai (SHH), etc.
- Others: TSX (Toronto), ASX (Sydney), etc.
Market Hours
Basic market hours check (simplified, no holiday support):
Thread Safety
All utility functions are thread-safe.
Package utils provides utility functions for yfinance.
Package utils provides utility functions for go-yfinance.
Index
- Variables
- func AllMICs() []string
- func AllYahooSuffixes() []string
- func CacheTimezone(exchange, timezone string)
- func ConvertToTimezone(t time.Time, timezone string) time.Time
- func FormatYahooTicker(baseTicker, mic string) string
- func GetMIC(suffix string) string
- func GetTimezone(exchange string) string
- func GetYahooSuffix(mic string) string
- func IsUSExchange(mic string) bool
- func IsValidTimezone(name string) bool
- func LoadLocation(name string) *time.Location
- func MarketIsOpen(exchange string) bool
- func ParseTimestamp(timestamp int64, timezone string) time.Time
- func ParseYahooTicker(ticker string) (baseTicker, suffix string)
Variables
MICToYahooSuffix maps ISO 10383 Market Identifier Codes (MIC) to Yahoo Finance ticker suffixes. This allows converting standard exchange codes to the format used by Yahoo Finance.
Reference:
- Yahoo Finance suffixes: https://help.yahoo.com/kb/finance-for-web/SLN2310.html
- ISO 10383 MIC codes: https://www.iso20022.org/market-identifier-codes
Example: "XLON" (London Stock Exchange) maps to "L", so AAPL traded on LSE would be "AAPL.L"
var MICToYahooSuffix = map[string]string{
"XCBT": "CBT",
"XCME": "CME",
"IFUS": "NYB",
"CECS": "CMX",
"XNYM": "NYM",
"XNYS": "",
"XNAS": "",
"XBUE": "BA",
"XVIE": "VI",
"XASX": "AX",
"XAUS": "XA",
"XBRU": "BR",
"BVMF": "SA",
"CNSX": "CN",
"NEOE": "NE",
"XTSE": "TO",
"XTSX": "V",
"XSGO": "SN",
"XSHG": "SS",
"XSHE": "SZ",
"XBOG": "CL",
"XPRA": "PR",
"XCSE": "CO",
"XCAI": "CA",
"XTAL": "TL",
"CEUX": "XD",
"XEUR": "NX",
"XHEL": "HE",
"XPAR": "PA",
"XBER": "BE",
"XBMS": "BM",
"XDUS": "DU",
"XFRA": "F",
"XHAM": "HM",
"XHAN": "HA",
"XMUN": "MU",
"XSTU": "SG",
"XETR": "DE",
"XATH": "AT",
"XHKG": "HK",
"XBUD": "BD",
"XICE": "IC",
"XBOM": "BO",
"XNSE": "NS",
"XIDX": "JK",
"XDUB": "IR",
"XTAE": "TA",
"MTAA": "MI",
"EUTL": "TI",
"XTKS": "T",
"XKFE": "KW",
"XRIS": "RG",
"XVIL": "VS",
"XKLS": "KL",
"XMEX": "MX",
"XAMS": "AS",
"XNZE": "NZ",
"XOSL": "OL",
"XPHS": "PS",
"XWAR": "WA",
"XLIS": "LS",
"XQAT": "QA",
"XBSE": "RO",
"XSES": "SI",
"XJSE": "JO",
"XKRX": "KS",
"KQKS": "KQ",
"BMEX": "MC",
"XSAU": "SR",
"XSTO": "ST",
"XSWX": "SW",
"ROCO": "TWO",
"XTAI": "TW",
"XBKK": "BK",
"XIST": "IS",
"XDFM": "AE",
"AQXE": "AQ",
"XCHI": "XC",
"XLON": "L",
"ILSE": "IL",
"XCAR": "CR",
"XSTC": "VN",
}
YahooSuffixToMIC is the reverse mapping from Yahoo Finance suffix to MIC code. Note: Some Yahoo suffixes may map to multiple MIC codes. In such cases, the primary/most common exchange is used.
func AllMICs
AllMICs returns all supported MIC codes.
func AllYahooSuffixes
AllYahooSuffixes returns all supported Yahoo Finance suffixes (excluding empty for US).
func CacheTimezone
CacheTimezone stores a timezone for an exchange in the cache.
func ConvertToTimezone
ConvertToTimezone converts a UTC time to the specified timezone.
func FormatYahooTicker
FormatYahooTicker formats a base ticker symbol with the appropriate Yahoo Finance suffix for the given MIC code.
Example:
FormatYahooTicker("AAPL", "XLON") returns "AAPL.L"
FormatYahooTicker("AAPL", "XNYS") returns "AAPL" (no suffix for US)
func GetMIC
GetMIC returns the MIC code for a given Yahoo Finance ticker suffix. Returns an empty string if the suffix is not found.
func GetTimezone
GetTimezone returns the timezone for a given exchange code. It first checks the cache, then falls back to the known exchange timezones. Returns "America/New_York" as default if exchange is unknown.
func GetYahooSuffix
GetYahooSuffix returns the Yahoo Finance ticker suffix for a given MIC code. Returns an empty string if the MIC code is not found or maps to a US exchange.
func IsUSExchange
IsUSExchange returns true if the MIC code represents a US exchange.
func IsValidTimezone
IsValidTimezone checks if a timezone name is valid.
func LoadLocation
LoadLocation loads a timezone location by name. Returns nil if the timezone is invalid.
func MarketIsOpen
MarketIsOpen checks if a market is currently open based on typical trading hours. This is a simplified check and doesn't account for holidays.
func ParseTimestamp
ParseTimestamp parses a Unix timestamp and converts to the specified timezone.
func ParseYahooTicker
ParseYahooTicker parses a Yahoo Finance ticker into base ticker and suffix.
Example:
Generated by gomarkdoc