models
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.
Index
- Constants
- Variables
- 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 CapitalGain
- 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 ETFQuery
- func NewETFQuery(operator string, operands []any) (*ETFQuery, error)
- func (q *ETFQuery) QuoteType() string
- func (q *ETFQuery) String() string
- func (q *ETFQuery) ToDict() map[string]any
- type EarningsEstimate
- type EarningsEvent
- type EarningsHistory
- type EarningsHistoryItem
- type EconomicEvent
- type EquityQuery
- func NewEquityQuery(operator string, operands []any) (*EquityQuery, error)
- func (q *EquityQuery) QuoteType() string
- func (q *EquityQuery) String() string
- func (q *EquityQuery) ToDict() map[string]any
- 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 FundQuery
- func NewFundQuery(operator string, operands []any) (*FundQuery, error)
- func (q *FundQuery) QuoteType() string
- func (q *FundQuery) String() string
- func (q *FundQuery) ToDict() map[string]any
- 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 MarketRegion
- 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 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 ScreenerQueryBuilder
- 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
- type ValuationMeasureRow
- type ValuationMeasures
- func (v *ValuationMeasures) Empty() bool
- func (v *ValuationMeasures) Value(rowName, columnName string) (string, bool)
Constants
Screener query operator constants. These are case-insensitive when passed to NewEquityQuery/NewFundQuery/NewETFQuery (auto-uppercased).
const (
// Comparison operators
OpEQ = "eq" // Equals
OpGT = "gt" // Greater than
OpLT = "lt" // Less than
OpGTE = "gte" // Greater than or equal
OpLTE = "lte" // Less than or equal
OpBTWN = "btwn" // Between
OpISIN = "is-in" // Is in (expanded to OR of EQ)
// Logical operators
OpAND = "and" // All conditions must match
OpOR = "or" // Any condition can match
)
Variables
var (
ETFScreenerEconomicMoats = []string{"Wide", "Narrow", "None"}
ETFScreenerStewardship = []string{"Exemplary", "Standard", "Poor"}
ETFScreenerUncertainty = []string{"Low", "Medium", "High", "Very High", "Extreme"}
ETFScreenerMoatTrend = []string{"Stable", "Positive", "Negative"}
ETFScreenerRatingChange = []string{"Upgrade", "Downgrade"}
)
ETFScreenerCategories is the set of valid categoryname values for ETF screener.
var ETFScreenerCategories = []string{
"Allocation--15% to 30% Equity", "Allocation--30% to 50% Equity",
"Allocation--50% to 70% Equity", "Allocation--70% to 85% Equity",
"Allocation--85%+ Equity", "Bank Loan", "Bear Market", "China Region",
"Commodities Agriculture", "Commodities Broad Basket", "Convertibles",
"Corporate Bond", "Diversified Emerging Mkts", "Diversified Pacific/Asia",
"Emerging Markets Bond", "Emerging-Markets Local-Currency Bond",
"Energy Limited Partnership", "Equity Energy", "Equity Precious Metals",
"Europe Stock", "Financial", "Foreign Large Blend", "Foreign Large Growth",
"Foreign Large Value", "Foreign Small/Mid Blend", "Foreign Small/Mid Growth",
"Foreign Small/Mid Value", "Global Real Estate", "Health", "High Yield Bond",
"High Yield Muni", "Inflation-Protected Bond", "Infrastructure",
"Intermediate Government", "Intermediate-Term Bond", "Japan Stock",
"Large Blend", "Large Growth", "Large Value", "Long Government",
"Long-Short Credit", "Long-Short Equity", "Long-Term Bond", "Managed Futures",
"Market Neutral", "Mid-Cap Blend", "Mid-Cap Growth", "Mid-Cap Value",
"Miscellaneous Region", "Multialternative", "Multicurrency",
"Multisector Bond", "Muni California Intermediate", "Muni California Long",
"Muni Massachusetts", "Muni Minnesota", "Muni National Interim",
"Muni National Long", "Muni National Short", "Muni New Jersey",
"Muni New York Intermediate", "Muni New York Long", "Muni Ohio",
"Muni Pennsylvania", "Muni Single State Interim", "Muni Single State Long",
"Muni Single State Short", "Natural Resources", "Nontraditional Bond",
"Option Writing", "Other", "Other Allocation", "Pacific/Asia ex-Japan Stk",
"Preferred Stock", "Real Estate", "Short Government", "Short-Term Bond",
"Small Blend", "Small Growth", "Small Value", "Tactical Allocation",
"Target-Date 2000-2010", "Target-Date 2015", "Target-Date 2020",
"Target-Date 2025", "Target-Date 2030", "Target-Date 2035",
"Target-Date 2040", "Target-Date 2045", "Target-Date 2050",
"Target-Date 2055", "Target-Date 2060+", "Target-Date Retirement",
"Technology", "Trading - Leveraged/Inverse Commodities",
"Trading - Leveraged/Inverse Equity", "Trading--Inverse Equity",
"Trading--Leveraged Equity", "Ultrashort Bond", "Utilities",
"World Allocation", "World Bond", "World Stock",
}
ETFScreenerExchangeMap maps region codes to valid exchange codes for ETF screener. Matches Python's ETF_SCREENER_EQ_MAP["exchange"] from yfinance v1.3.0.
var ETFScreenerExchangeMap = map[string][]string{
"ae": {"DFM"},
"ar": {"BUE"},
"at": {"VIE"},
"au": {"ASX", "CXA"},
"be": {"BRU"},
"br": {"SAO"},
"ca": {"CNQ", "NEO", "TOR", "VAN"},
"ch": {"EBS"},
"cl": {"SGO"},
"cn": {"SHH", "SHZ"},
"co": {"BVC"},
"cz": {"PRA"},
"de": {"BER", "DUS", "EUX", "FRA", "HAM", "HAN", "GER", "MUN", "STU"},
"dk": {"CPH"},
"ee": {"TAL"},
"eg": {"CAI"},
"es": {"MAD", "MCE"},
"fi": {"HEL"},
"fr": {"ENX", "PAR"},
"gb": {"AQS", "CXE", "IOB", "LSE"},
"gr": {"ATH"},
"hk": {"HKG"},
"hu": {"BUD"},
"id": {"JKT"},
"ie": {"ISE"},
"il": {"TLV"},
"in": {"BSE", "NSI"},
"is": {"ICE"},
"it": {"MDD", "MIL", "TLO"},
"jp": {"FKA", "JPX", "OSA", "SAP"},
"kr": {"KOE", "KSC"},
"kw": {"KUW"},
"lk": {"CSE"},
"lt": {"LIT"},
"lv": {"RIS"},
"mx": {"MEX"},
"my": {"KLS"},
"nl": {"AMS", "DXE"},
"no": {"OSL"},
"nz": {"NZE"},
"pe": {},
"ph": {"PHP", "PHS"},
"pk": {"KAR"},
"pl": {"WSE"},
"pt": {"LIS"},
"qa": {"DOH"},
"ro": {"BVB"},
"ru": {"MCX"},
"sa": {"SAU"},
"se": {"STO"},
"sg": {"SES"},
"sr": {},
"th": {"SET"},
"tr": {"IST"},
"tw": {"TAI", "TWO"},
"us": {"ASE", "BTS", "CXI", "NAE", "NCM", "NGM", "NMS", "NYQ", "OEM", "OQB", "OQX", "PCX", "PNK", "YHD"},
"ve": {"CCS"},
"vn": {"VSE"},
"za": {"JNB"},
}
ETFScreenerFields defines valid field names by category for ETF screener. After merging with CommonScreenerFields, matches Python's ETF_SCREENER_FIELDS.
var ETFScreenerFields = map[string][]string{
"eq_fields": {
"categoryname", "fundfamilyname", "region", "primary_sector",
"morningstar_economic_moat", "morningstar_stewardship",
"morningstar_uncertainty", "morningstar_moat_trend",
"morningstar_rating_change",
},
"fundamentals": {"fundnetassets", "ticker"},
"feesandexpenses": {
"annualreportgrossexpenseratio", "annualreportnetexpenseratio", "turnoverratio",
},
"historicalperformance": {
"annualreturnnavy1", "annualreturnnavy1categoryrank",
"annualreturnnavy3", "annualreturnnavy5",
},
"keystats": {
"avgdailyvol3m", "dayvolume", "eodvolume", "fiftytwowkpercentchange",
"percentchange",
},
"morningstar_rating": {
"morningstar_last_close_price_to_fair_value", "morningstar_rating",
"morningstar_rating_updated_time",
},
"portfoliostatistics": {"marketcapitalvaluelong"},
"purchasedetails": {"initialinvestment"},
"trailingperformance": {
"performanceratingoverall", "quarterendtrailingreturnytd",
"riskratingoverall", "trailing_3m_return", "trailing_ytd_return",
},
"price": {"eodprice", "intradaypricechange", "intradayprice"},
}
ETFScreenerFundFamilies is the set of valid fundfamilyname values for ETF screener.
var ETFScreenerFundFamilies = []string{
"ALPS", "AMG Funds", "AQR Funds", "Aberdeen", "Alger", "AllianceBernstein",
"Allianz Funds", "American Beacon", "American Century Investments",
"American Funds", "Aquila", "Artisan", "BMO Funds", "BNY Mellon Funds",
"Baird", "Barclays Funds", "Barings Funds", "Baron Capital Group",
"BlackRock", "Brown Advisory Funds", "Calamos", "Calvert Investments",
"Catalyst Mutual Funds", "Cohen & Steers", "Columbia",
"Commerz Funds Solutions SA", "Commerzbank AG, Frankfurt am Main",
"Davis Funds", "Delaware Investments", "Deutsche Asset Management",
"Deutsche Bank AG", "Diamond Hill Funds", "Dimensional Fund Advisors",
"Direxion Funds", "DoubleLine", "Dreyfus", "Dunham Funds", "Eagle Funds",
"Eaton Vance", "Federated", "Fidelity Investments", "First Investors",
"First Trust", "Flexshares Trust", "Franklin Templeton Investments", "GMO",
"Gabelli", "Global X Funds", "Goldman Sachs", "Great-West Funds",
"Guggenheim Investments", "GuideStone Funds", "HSBC", "Hancock Horizon",
"Harbor", "Hartford Mutual Funds", "Henderson Global", "Hennessy",
"Highland Funds", "ICON Funds", "Invesco", "Ivy Funds", "JPMorgan",
"Janus", "John Hancock", "Lazard", "Legg Mason", "Lord Abbett", "MFS",
"Madison Funds", "MainStay", "Manning & Napier", "Market Vectors",
"MassMutual", "Matthews Asia Funds", "Morgan Stanley", "Nationwide",
"Natixis Funds", "Neuberger Berman", "Northern Funds", "Nuveen",
"OppenheimerFunds", "PNC Funds", "Pacific funds series trust", "Pax World",
"Paydenfunds", "Pimco", "Pioneer Investments", "PowerShares",
"Principal Funds", "ProFunds", "ProShares", "Prudential Investments",
"Putnam", "RBC Global Asset Management.", "RidgeWorth", "Royce", "Russell",
"Rydex Funds", "SEI", "SPDR State Street Global Advisors", "Salient Funds",
"Saratoga", "Schwab Funds", "Sentinel", "Shelton Capital Management",
"State Farm", "State Street Global Advisors (Chicago)", "Sterling Capital Funds",
"SunAmerica", "T. Rowe Price", "TCW", "TIAA-CREF Asset Management",
"Teton Westwood Funds", "Thornburg", "Thrivent", "Timothy Plan", "Touchstone",
"Transamerica", "UBS", "UBS Group AG", "USAA", "VALIC", "Vanguard",
"Vantagepoint Funds", "Victory", "Virtus", "Voya", "Waddell & Reed",
"Wasatch", "Wells Fargo Funds", "William Blair", "WisdomTree", "iShares",
}
EquityScreenerExchangeMap maps region codes to valid exchange codes for equity screener. Matches Python's EQUITY_SCREENER_EQ_MAP["exchange"].
var EquityScreenerExchangeMap = map[string][]string{
"ae": {"DFM"},
"ar": {"BUE"},
"at": {"VIE"},
"au": {"ASX", "CXA"},
"be": {"BRU"},
"br": {"SAO"},
"ca": {"CNQ", "NEO", "TOR", "VAN"},
"ch": {"EBS"},
"cl": {"SGO"},
"cn": {"SHH", "SHZ"},
"co": {"BVC"},
"cz": {"PRA"},
"de": {"BER", "DUS", "EUX", "FRA", "HAM", "HAN", "GER", "MUN", "STU"},
"dk": {"CPH"},
"ee": {"TAL"},
"eg": {"CAI"},
"es": {"MAD", "MCE"},
"fi": {"HEL"},
"fr": {"ENX", "PAR"},
"gb": {"AQS", "CXE", "IOB", "LSE"},
"gr": {"ATH"},
"hk": {"HKG"},
"hu": {"BUD"},
"id": {"JKT"},
"ie": {"ISE"},
"il": {"TLV"},
"in": {"BSE", "NSI"},
"is": {"ICE"},
"it": {"MDD", "MIL", "TLO"},
"jp": {"FKA", "JPX", "OSA", "SAP"},
"kr": {"KOE", "KSC"},
"kw": {"KUW"},
"lk": {"CSE"},
"lt": {"LIT"},
"lv": {"RIS"},
"mx": {"MEX"},
"my": {"KLS"},
"nl": {"AMS", "DXE"},
"no": {"OSL"},
"nz": {"NZE"},
"pe": {},
"ph": {"PHP", "PHS"},
"pk": {"KAR"},
"pl": {"WSE"},
"pt": {"LIS"},
"qa": {"DOH"},
"ro": {"BVB"},
"ru": {"MCX"},
"sa": {"SAU"},
"se": {"STO"},
"sg": {"SES"},
"sr": {},
"th": {"SET"},
"tr": {"IST"},
"tw": {"TAI", "TWO"},
"us": {"ASE", "BTS", "CXI", "NAE", "NCM", "NGM", "NMS", "NYQ", "OEM", "OQB", "OQX", "PCX", "PNK", "YHD"},
"ve": {"CCS"},
"vn": {"VSE"},
"za": {"JNB"},
}
EquityScreenerFields defines valid field names by category for equity screener. After merging with CommonScreenerFields, matches Python's EQUITY_SCREENER_FIELDS.
var EquityScreenerFields = map[string][]string{
"eq_fields": {"region", "sector", "peer_group", "industry", "exchange"},
"price": {
"lastclosemarketcap.lasttwelvemonths", "percentchange",
"lastclose52weekhigh.lasttwelvemonths", "fiftytwowkpercentchange",
"lastclose52weeklow.lasttwelvemonths", "intradaymarketcap",
"eodprice", "intradaypricechange", "intradayprice",
},
"trading": {"beta", "avgdailyvol3m", "pctheldinsider", "pctheldinst", "dayvolume", "eodvolume"},
"short_interest": {
"short_percentage_of_shares_outstanding.value", "short_interest.value",
"short_percentage_of_float.value", "days_to_cover_short.value",
"short_interest_percentage_change.value",
},
"valuation": {
"bookvalueshare.lasttwelvemonths", "lastclosemarketcaptotalrevenue.lasttwelvemonths",
"lastclosetevtotalrevenue.lasttwelvemonths", "pricebookratio.quarterly",
"peratio.lasttwelvemonths", "lastclosepricetangiblebookvalue.lasttwelvemonths",
"lastclosepriceearnings.lasttwelvemonths", "pegratio_5y",
},
"profitability": {
"consecutive_years_of_dividend_growth_count", "returnonassets.lasttwelvemonths",
"returnonequity.lasttwelvemonths", "forward_dividend_per_share",
"forward_dividend_yield", "returnontotalcapital.lasttwelvemonths",
},
"leverage": {
"lastclosetevebit.lasttwelvemonths", "netdebtebitda.lasttwelvemonths",
"totaldebtequity.lasttwelvemonths", "ltdebtequity.lasttwelvemonths",
"ebitinterestexpense.lasttwelvemonths", "ebitdainterestexpense.lasttwelvemonths",
"lastclosetevebitda.lasttwelvemonths", "totaldebtebitda.lasttwelvemonths",
},
"liquidity": {
"quickratio.lasttwelvemonths",
"altmanzscoreusingtheaveragestockinformationforaperiod.lasttwelvemonths",
"currentratio.lasttwelvemonths",
"operatingcashflowtocurrentliabilities.lasttwelvemonths",
},
"income_statement": {
"totalrevenues.lasttwelvemonths", "netincomemargin.lasttwelvemonths",
"grossprofit.lasttwelvemonths", "ebitda1yrgrowth.lasttwelvemonths",
"dilutedepscontinuingoperations.lasttwelvemonths", "quarterlyrevenuegrowth.quarterly",
"epsgrowth.lasttwelvemonths", "netincomeis.lasttwelvemonths",
"ebitda.lasttwelvemonths", "dilutedeps1yrgrowth.lasttwelvemonths",
"totalrevenues1yrgrowth.lasttwelvemonths", "operatingincome.lasttwelvemonths",
"netincome1yrgrowth.lasttwelvemonths", "grossprofitmargin.lasttwelvemonths",
"ebitdamargin.lasttwelvemonths", "ebit.lasttwelvemonths",
"basicepscontinuingoperations.lasttwelvemonths",
"netepsbasic.lasttwelvemonthsnetepsdiluted.lasttwelvemonths",
},
"balance_sheet": {
"totalassets.lasttwelvemonths", "totalcommonsharesoutstanding.lasttwelvemonths",
"totaldebt.lasttwelvemonths", "totalequity.lasttwelvemonths",
"totalcurrentassets.lasttwelvemonths",
"totalcashandshortterminvestments.lasttwelvemonths",
"totalcommonequity.lasttwelvemonths",
"totalcurrentliabilities.lasttwelvemonths", "totalsharesoutstanding",
},
"cash_flow": {
"forward_dividend_yield", "leveredfreecashflow.lasttwelvemonths",
"capitalexpenditure.lasttwelvemonths", "cashfromoperations.lasttwelvemonths",
"leveredfreecashflow1yrgrowth.lasttwelvemonths",
"unleveredfreecashflow.lasttwelvemonths",
"cashfromoperations1yrgrowth.lasttwelvemonths",
},
"esg": {"esg_score", "environmental_score", "governance_score", "social_score", "highest_controversy"},
}
EquityScreenerPeerGroups is the set of valid peer group names for equity screener.
var EquityScreenerPeerGroups = []string{
"US Fund Equity Energy", "US CE Convertibles", "EAA CE UK Large-Cap Equity",
"EAA CE Other", "US Fund Financial", "India CE Multi-Cap",
"US Fund Foreign Large Blend", "US Fund Consumer Cyclical",
"EAA Fund Global Equity Income",
"China Fund Sector Equity Financial and Real Estate",
"US Fund Equity Precious Metals", "EAA Fund RMB Bond - Onshore",
"China Fund QDII Greater China Equity", "US Fund Large Growth",
"EAA Fund Germany Equity", "EAA Fund Hong Kong Equity",
"EAA CE UK Small-Cap Equity", "US Fund Natural Resources",
"US CE Preferred Stock", "India Fund Sector - Financial Services",
"US Fund Diversified Emerging Mkts",
"EAA Fund South Africa & Namibia Equity",
"China Fund QDII Sector Equity", "EAA CE Sector Equity Biotechnology",
"EAA Fund Switzerland Equity", "US Fund Large Value",
"EAA Fund Asia ex-Japan Equity", "US Fund Health", "US Fund China Region",
"EAA Fund Emerging Europe ex-Russia Equity",
"EAA Fund Sector Equity Industrial Materials",
"EAA Fund Japan Large-Cap Equity", "EAA Fund EUR Corporate Bond",
"US Fund Technology", "EAA CE Global Large-Cap Blend Equity",
"Mexico Fund Mexico Equity", "US Fund Trading--Leveraged Equity",
"EAA Fund Sector Equity Consumer Goods & Services", "US Fund Large Blend",
"EAA Fund Global Flex-Cap Equity",
"EAA Fund EUR Aggressive Allocation - Global", "EAA Fund China Equity",
"EAA Fund Global Large-Cap Growth Equity", "US CE Options-based",
"EAA Fund Sector Equity Financial Services",
"EAA Fund Europe Large-Cap Blend Equity",
"EAA Fund China Equity - A Shares", "EAA Fund USD Corporate Bond",
"EAA Fund Eurozone Large-Cap Equity",
"China Fund Aggressive Allocation Fund",
"EAA Fund Sector Equity Technology",
"EAA Fund Global Emerging Markets Equity",
"EAA Fund EUR Moderate Allocation - Global", "EAA Fund Other Bond",
"EAA Fund Denmark Equity", "EAA Fund US Large-Cap Blend Equity",
"India Fund Large-Cap", "Paper & Forestry", "Containers & Packaging",
"US Fund Miscellaneous Region", "Energy Services", "EAA Fund Other Equity",
"Homebuilders", "Construction Materials", "China Fund Equity Funds",
"Steel", "Consumer Durables", "EAA Fund Global Large-Cap Blend Equity",
"Transportation Infrastructure", "Precious Metals", "Building Products",
"Traders & Distributors", "Electrical Equipment", "Auto Components",
"Construction & Engineering", "Aerospace & Defense",
"Refiners & Pipelines", "Diversified Metals", "Textiles & Apparel",
"Industrial Conglomerates", "Household Products", "Commercial Services",
"Food Retailers", "Semiconductors", "Media", "Automobiles",
"Consumer Services", "Technology Hardware", "Transportation",
"Telecommunication Services", "Oil & Gas Producers", "Machinery",
"Retailing", "Healthcare", "Chemicals", "Food Products",
"Diversified Financials", "Real Estate", "Insurance", "Utilities",
"Pharmaceuticals", "Software & Services", "Banks",
}
EquityScreenerSectors is the set of valid sector names for equity screener.
var EquityScreenerSectors = []string{
"Basic Materials", "Industrials", "Communication Services", "Healthcare",
"Real Estate", "Technology", "Energy", "Utilities", "Financial Services",
"Consumer Defensive", "Consumer Cyclical",
}
FundScreenerExchangeMap maps region codes to valid exchange codes for fund screener. Matches Python's FUND_SCREENER_EQ_MAP["exchange"].
var FundScreenerExchangeMap = map[string][]string{
"ae": {"DFM"},
"ar": {"BUE"},
"at": {"VIE"},
"au": {"ASX", "CXA"},
"be": {"BRU"},
"br": {"SAO"},
"ca": {"CNQ", "NEO", "TOR", "VAN"},
"ch": {"EBS"},
"cl": {"SGO"},
"co": {"BVC"},
"cn": {"SHH", "SHZ"},
"cz": {"PRA"},
"de": {"BER", "DUS", "EUX", "FRA", "GER", "HAM", "HAN", "MUN", "STU"},
"dk": {"CPH"},
"ee": {"TAL"},
"eg": {"CAI"},
"es": {"BAR", "MAD", "MCE"},
"fi": {"HEL"},
"fr": {"ENX", "PAR"},
"gb": {"CXE", "IOB", "LSE"},
"gr": {"ATH"},
"hk": {"HKG"},
"hu": {"BUD"},
"id": {"JKT"},
"ie": {"ISE"},
"il": {"TLV"},
"in": {"BSE", "NSI"},
"is": {"ICE"},
"it": {"MIL"},
"jp": {"FKA", "JPX", "OSA", "SAP"},
"kr": {"KOE", "KSC"},
"kw": {"KUW"},
"lk": {"CSE"},
"lt": {"LIT"},
"lv": {"RIS"},
"mx": {"MEX"},
"my": {"KLS"},
"nl": {"AMS"},
"no": {"OSL"},
"nz": {"NZE"},
"pe": {""},
"ph": {"PHP", "PHS"},
"pk": {"KAR"},
"pl": {"WSE"},
"pt": {"LIS"},
"qa": {"DOH"},
"ro": {"BVB"},
"ru": {"MCX"},
"sa": {"SAU"},
"se": {"STO"},
"sg": {"SES"},
"sr": {""},
"th": {"SET"},
"tr": {"IST"},
"tw": {"TAI", "TWO"},
"us": {"ASE", "NAS", "NCM", "NGM", "NMS", "NYQ", "OEM", "OGM", "OQB", "PNK", "WCB"},
"ve": {"CCS"},
"vn": {"VSE"},
"za": {"JNB"},
}
FundScreenerFields defines valid field names by category for fund screener. After merging with CommonScreenerFields, matches Python's FUND_SCREENER_FIELDS.
var FundScreenerFields = map[string][]string{
"eq_fields": {
"categoryname", "performanceratingoverall", "initialinvestment",
"annualreturnnavy1categoryrank", "riskratingoverall", "exchange",
},
"price": {"eodprice", "intradaypricechange", "intradayprice"},
}
SectorIndustryMapping maps sector names to their industries. Matches Python's SECTOR_INDUSTY_MAPPING from yfinance/const.py.
var SectorIndustryMapping = map[string][]string{
"Basic Materials": {
"Specialty Chemicals", "Gold", "Building Materials", "Copper", "Steel",
"Agricultural Inputs", "Chemicals", "Other Industrial Metals & Mining",
"Lumber & Wood Production", "Aluminum", "Other Precious Metals & Mining",
"Coking Coal", "Paper & Paper Products", "Silver",
},
"Communication Services": {
"Advertising Agencies", "Broadcasting", "Electronic Gaming & Multimedia",
"Entertainment", "Internet Content & Information", "Publishing", "Telecom Services",
},
"Consumer Cyclical": {
"Apparel Manufacturing", "Apparel Retail", "Auto & Truck Dealerships",
"Auto Manufacturers", "Auto Parts", "Department Stores", "Footwear & Accessories",
"Furnishings, Fixtures & Appliances", "Gambling", "Home Improvement Retail",
"Internet Retail", "Leisure", "Lodging", "Luxury Goods",
"Packaging & Containers", "Personal Services", "Recreational Vehicles",
"Residential Construction", "Resorts & Casinos", "Restaurants",
"Specialty Retail", "Textile Manufacturing", "Travel Services",
},
"Consumer Defensive": {
"Beverages—Brewers", "Beverages—Non-Alcoholic", "Beverages—Wineries & Distilleries",
"Confectioners", "Discount Stores", "Education & Training Services",
"Farm Products", "Food Distribution", "Grocery Stores",
"Household & Personal Products", "Packaged Foods", "Tobacco",
},
"Energy": {
"Oil & Gas Drilling", "Oil & Gas E&P", "Oil & Gas Equipment & Services",
"Oil & Gas Integrated", "Oil & Gas Midstream", "Oil & Gas Refining & Marketing",
"Thermal Coal", "Uranium",
},
"Financial Services": {
"Asset Management", "Banks—Diversified", "Banks—Regional", "Capital Markets",
"Credit Services", "Financial Conglomerates", "Financial Data & Stock Exchanges",
"Insurance Brokers", "Insurance—Diversified", "Insurance—Life",
"Insurance—Property & Casualty", "Insurance—Reinsurance", "Insurance—Specialty",
"Mortgage Finance", "Shell Companies",
},
"Healthcare": {
"Biotechnology", "Diagnostics & Research", "Drug Manufacturers—General",
"Drug Manufacturers—Specialty & Generic", "Health Information Services",
"Healthcare Plans", "Medical Care Facilities", "Medical Devices",
"Medical Instruments & Supplies", "Medical Distribution", "Pharmaceutical Retailers",
},
"Industrials": {
"Aerospace & Defense", "Airlines", "Airports & Air Services",
"Building Products & Equipment", "Business Equipment & Supplies", "Conglomerates",
"Consulting Services", "Electrical Equipment & Parts", "Engineering & Construction",
"Farm & Heavy Construction Machinery", "Industrial Distribution",
"Infrastructure Operations", "Integrated Freight & Logistics", "Marine Shipping",
"Metal Fabrication", "Pollution & Treatment Controls", "Railroads",
"Rental & Leasing Services", "Security & Protection Services",
"Specialty Business Services", "Specialty Industrial Machinery",
"Staffing & Employment Services", "Tools & Accessories", "Trucking", "Waste Management",
},
"Real Estate": {
"Real Estate—Development", "Real Estate Services", "Real Estate—Diversified",
"REIT—Healthcare Facilities", "REIT—Hotel & Motel", "REIT—Industrial",
"REIT—Office", "REIT—Residential", "REIT—Retail", "REIT—Mortgage",
"REIT—Specialty", "REIT—Diversified",
},
"Technology": {
"Communication Equipment", "Computer Hardware", "Consumer Electronics",
"Electronic Components", "Electronics & Computer Distribution",
"Information Technology Services", "Scientific & Technical Instruments",
"Semiconductor Equipment & Materials", "Semiconductors",
"Software—Application", "Software—Infrastructure", "Solar",
},
"Utilities": {
"Utilities—Diversified", "Utilities—Independent Power Producers",
"Utilities—Regulated Electric", "Utilities—Regulated Gas",
"Utilities—Regulated Water", "Utilities—Renewable",
},
}
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"`
CapitalGains []CapitalGain `json:"capitalGains,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"`
// DividendCurrency is present when Yahoo returns dividend events in a separate currency.
DividendCurrency string `json:"dividendCurrency,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 CapitalGain
CapitalGain represents a capital gain distribution.
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 Dividend struct {
Date time.Time `json:"date"`
Amount float64 `json:"amount"`
Currency string `json:"currency,omitempty"`
}
type DividendEvent
DividendEvent represents a dividend event in chart response.
type DividendEvent struct {
Amount float64 `json:"amount"`
Date int64 `json:"date"`
Currency string `json:"currency,omitempty"`
}
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"`
Currency string `json:"currency,omitempty"`
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"`
Currency string `json:"currency,omitempty"`
Current float64 `json:"current"`
SevenDays float64 `json:"7daysAgo"`
ThirtyDays float64 `json:"30daysAgo"`
SixtyDays float64 `json:"60daysAgo"`
NinetyDays float64 `json:"90daysAgo"`
}
type ETFQuery
ETFQuery represents a validated ETF screener query.
func NewETFQuery
NewETFQuery creates a new validated ETF screener query. Same operator rules as NewEquityQuery.
func (*ETFQuery) QuoteType
QuoteType returns "ETF".
func (*ETFQuery) String
String returns a human-readable representation of the query.
func (*ETFQuery) ToDict
ToDict serializes the ETFQuery to a map for JSON encoding.
type EarningsEstimate
EarningsEstimate represents earnings estimates for a period.
type EarningsEstimate struct {
Period string `json:"period"` // "0q", "+1q", "0y", "+1y"
EndDate string `json:"endDate"`
Currency string `json:"currency,omitempty"`
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 EquityQuery
EquityQuery represents a validated equity screener query.
func NewEquityQuery
NewEquityQuery creates a new validated equity screener query. Operator is case-insensitive and will be uppercased. Valid operators: "EQ", "GT", "LT", "GTE", "LTE", "BTWN", "AND", "OR", "IS-IN"
Example:
q, err := models.NewEquityQuery("and", []any{
mustEquityQuery("eq", []any{"region", "us"}),
mustEquityQuery("gt", []any{"intradayprice", 10}),
})
func (*EquityQuery) QuoteType
QuoteType returns "EQUITY".
func (*EquityQuery) String
String returns a human-readable representation of the query.
func (*EquityQuery) ToDict
ToDict serializes the EquityQuery to a map for JSON encoding. IS-IN is expanded to OR of EQ queries.
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 FundQuery
FundQuery represents a validated fund screener query.
func NewFundQuery
NewFundQuery creates a new validated fund screener query. Same operator rules as NewEquityQuery.
func (*FundQuery) QuoteType
QuoteType returns "MUTUALFUND".
func (*FundQuery) String
String returns a human-readable representation of the query.
func (*FundQuery) ToDict
ToDict serializes the FundQuery to a map for JSON encoding.
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 MarketRegion
MarketRegion represents Yahoo market regions accepted by the market summary endpoint.
const (
// MarketRegionUS represents U.S. markets.
MarketRegionUS MarketRegion = "US"
// MarketRegionGB represents Great Britain markets.
MarketRegionGB MarketRegion = "GB"
// MarketRegionAsia represents Asian markets.
MarketRegionAsia MarketRegion = "ASIA"
// MarketRegionEurope represents European markets.
MarketRegionEurope MarketRegion = "EUROPE"
// MarketRegionRates represents rates markets.
MarketRegionRates MarketRegion = "RATES"
// MarketRegionCommodities represents commodities markets.
MarketRegionCommodities MarketRegion = "COMMODITIES"
// MarketRegionCurrencies represents currencies markets.
MarketRegionCurrencies MarketRegion = "CURRENCIES"
// MarketRegionCryptocurrencies represents cryptocurrency markets.
MarketRegionCryptocurrencies MarketRegion = "CRYPTOCURRENCIES"
)
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 legacy market identifiers. New code can use MarketRegion with market.NewWithRegion for Python v1.4.0 parity.
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"
// ETF Screeners
ScreenerTopETFsUS PredefinedScreener = "top_etfs_us"
ScreenerTopPerformingETF PredefinedScreener = "top_performing_etfs"
ScreenerTechnologyETFs PredefinedScreener = "technology_etfs"
ScreenerBondETFs PredefinedScreener = "bond_etfs"
)
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 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"`
Currency string `json:"currency,omitempty"`
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
// UserID is the user identifier (default "").
UserID string
// UserIDType is the type of user ID (default "guid").
UserIDType string
}
func DefaultScreenerParams
DefaultScreenerParams returns default screener parameters.
type ScreenerQueryBuilder
ScreenerQueryBuilder is the interface for EquityQuery, FundQuery, and ETFQuery. It provides methods for serializing queries and identifying the quote type.
type ScreenerQueryBuilder interface {
// ToDict serializes the query to a map suitable for JSON encoding.
// IS-IN operators are expanded to OR-of-EQ queries.
ToDict() map[string]any
// QuoteType returns "EQUITY", "MUTUALFUND", or "ETF".
QuoteType() string
}
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"`
// FundNetAssets is the fund's total net assets.
FundNetAssets float64 `json:"fundNetAssets,omitempty"`
// CategoryName is the fund category name.
CategoryName string `json:"categoryName,omitempty"`
// PerformanceRatingOverall is the overall performance rating (1-5).
PerformanceRatingOverall int `json:"performanceRatingOverall,omitempty"`
// RiskRatingOverall is the overall risk rating (1-5).
RiskRatingOverall int `json:"riskRatingOverall,omitempty"`
// InitialInvestment is the minimum initial investment amount.
InitialInvestment float64 `json:"initialInvestment,omitempty"`
// AnnualReturnNavY1CategoryRank is the 1-year annual return category rank.
AnnualReturnNavY1CategoryRank float64 `json:"annualReturnNavY1CategoryRank,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]any `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"`
}
type ValuationMeasureRow
ValuationMeasureRow represents one row in the valuation measures table.
type ValuationMeasureRow struct {
// Name is the valuation measure label, such as "Market Cap".
Name string `json:"name"`
// Values maps each column name to the displayed Yahoo Finance value.
Values map[string]string `json:"values"`
}
type ValuationMeasures
ValuationMeasures represents Yahoo Finance's key-statistics valuation table.
type ValuationMeasures struct {
// Columns are the table value columns, such as "Current" and quarter-end dates.
Columns []string `json:"columns"`
// Rows contains one row per valuation measure.
Rows []ValuationMeasureRow `json:"rows"`
}
func (*ValuationMeasures) Empty
Empty reports whether the valuation table has no rows.
func (*ValuationMeasures) Value
Value returns a value by row name and column name.