yahoofinanceapi

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 12 Imported by: 0

README

yahoo-finance-api

Motivation

  • I used to write Python programs and use Yahoo Finance data. The yfinance library is an awesome library which I enjoyed a lot.
  • Could not find similar packages in Go.
  • Learn Go
  • Able to use this package on my other Go projects

If you love this project, please consider giving it a ⭐.

Installation

go get github.com/oscarli916/yahoo-finance-api

Example

package main

import (
	"fmt"

	yfa "github.com/oscarli916/yahoo-finance-api"
)

func main() {
	t := yfa.NewTicker("AAPL")

	// get the latest PriceData
	quote, err := t.Quote()
	if err != nil {
		fmt.Println("Error fetching quote:", err)
		return
	}
	fmt.Println(quote.Close)

	// history data
	history, err := t.History(yfa.HistoryQuery{Range: "1d", Interval: "1m"})
	if err != nil {
		fmt.Println("Error fetching history:", err)
		return
	}
	fmt.Println(history)

	// option chain
	e := t.ExpirationDates()
	oc := t.OptionChainByExpiration(e[2])
	fmt.Println(oc)
	
	// Ticker Information
	info, err := t.GetInfo()
	if err != nil {
		fmt.Println("GetInfo returned error:", err)
	}
	fmt.Println(info)
}

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BASE_URL = "https://query2.finance.yahoo.com"
View Source
var USER_AGENTS = []string{
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (X11; Linux i686; rv:135.0) Gecko/20100101 Firefox/135.0",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3 Safari/605.1.15",
	"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/131.0.2903.86",
}

Functions

This section is empty.

Types

type Client

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

func (*Client) Get

func (c *Client) Get(url string, params url.Values) (*http.Response, error)

type History

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

func (*History) GetHistory

func (h *History) GetHistory(symbol string) (YahooHistoryRespose, error)

returns the price/volume history of the given symbol as a YahooHistoryResponse If you want to adjust the query range change h.query.Range = "6mo" for 6 month

func (*History) SetQuery

func (h *History) SetQuery(query HistoryQuery)

type HistoryQuery

type HistoryQuery struct {
	Range     string
	Interval  string
	Start     string
	End       string
	UserAgent string
}

func (*HistoryQuery) SetDefault

func (hq *HistoryQuery) SetDefault()

type Information

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

Information holds the HTTP client

func (*Information) GetInfo

func (i *Information) GetInfo(symbol string) (YahooTickerInfo, error)

GetInfo fetches metadata information for a given ticker

type Option

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

func (*Option) GetExpirationDates

func (o *Option) GetExpirationDates(symbol string) []string

func (*Option) GetOptionChain

func (o *Option) GetOptionChain(symbol string) YahooOptionResponse

func (*Option) GetOptionChainByExpiration

func (o *Option) GetOptionChainByExpiration(symbol string, expirationDate string) YahooOptionResponse

type OptionData

type OptionData struct {
	ExpirationDate string         `json:"expirationDate"`
	HasMiniOptions bool           `json:"hasMiniOptions"`
	Calls          []OptionDetail `json:"calls"`
	Puts           []OptionDetail `json:"puts"`
}

type OptionDetail

type OptionDetail 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        string  `json:"expiration"`
	LastTradeDate     string  `json:"lastTradeDate"`
	ImpliedVolatility float64 `json:"impliedVolatility"`
	InTheMoney        bool    `json:"inTheMoney"`
}

type PriceData

type PriceData struct {
	Open   float64
	High   float64
	Low    float64
	Close  float64
	Volume int64
}

type PriceValue

type PriceValue struct {
	Raw     float64 `json:"raw"`
	Fmt     string  `json:"fmt"`
	LongFmt string  `json:"longFmt,omitempty"`
}

PriceValue represents a price value with raw and formatted representations

type Ticker

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

func NewTicker

func NewTicker(symbol string) *Ticker

NewTicker creates a new Ticker instance for the given symbol. It initializes the history, option, and information components needed to fetch historical price data, options data, and ticker information.

func (*Ticker) ExpirationDates

func (t *Ticker) ExpirationDates() []string

ExpirationDates retrieves a list of available expiration dates for options on the Ticker's symbol. It returns a slice of strings representing the expiration dates.

func (*Ticker) History

func (t *Ticker) History(query HistoryQuery) (map[string]PriceData, error)

History retrieves the historical price data for the Ticker's symbol based on the provided query. It returns a map of date strings to PriceData structs. The query can specify the range, interval, and other parameters for the historical data.

func (*Ticker) Info

func (t *Ticker) Info() (YahooTickerInfo, error)

Info retrieves the ticker information for the Ticker's symbol. It returns a YahooTickerInfo struct containing metadata such as the symbol, name, currency, and market state. If no information is found, it returns an error.

func (*Ticker) OptionChain

func (t *Ticker) OptionChain() OptionData

OptionChain retrieves the option chain for the Ticker's symbol. It returns an OptionData struct containing the options available for the ticker. If no options are found, it returns an empty OptionData struct.

func (*Ticker) OptionChainByExpiration

func (t *Ticker) OptionChainByExpiration(expiration string) OptionData

OptionChainByExpiration retrieves the option chain for the Ticker's symbol filtered by a specific expiration date. It returns an OptionData struct containing the options available for the ticker on that expiration date. If no options are found for the specified expiration, it returns an empty OptionData struct.

func (*Ticker) Quote

func (t *Ticker) Quote() (PriceData, error)

Quote returns the latest PriceData for the Ticker's symbol. This is a convenience wrapper around the History function. It fetches the historical price data for the symbol, sorts the dates, and returns the most recent entry. If you need more control or access to the full historical data, use the History method directly.

type YahooChart

type YahooChart struct {
	Result []YahooHistoryResult `json:"result"`
}

type YahooHistoryRespose

type YahooHistoryRespose struct {
	Chart YahooChart `json:"chart"`
}

type YahooHistoryResult

type YahooHistoryResult struct {
	Meta       YahooMeta      `json:"meta"`
	Timestamp  []int64        `json:"timestamp"`
	Indicators YahooIndicator `json:"indicators"`
}

type YahooIndicator

type YahooIndicator struct {
	Quote []YahooQuote `json:"quote"`
}

type YahooInfoResponse

type YahooInfoResponse struct {
	QuoteSummary struct {
		Result []struct {
			Price YahooTickerInfo `json:"price"`
		} `json:"result"`
		Error interface{} `json:"error"`
	} `json:"quoteSummary"`
}

YahooInfoResponse --> Struct to hold the result from the Yahoo Finance quoteSummary endpoint

type YahooMeta

type YahooMeta struct {
	Currency             string                 `json:"currency"`
	Symbol               string                 `json:"symbol"`
	ExchangeName         string                 `json:"exchangeName"`
	FullExchangeName     string                 `json:"fullExchangeName"`
	InstrumentType       string                 `json:"instrumentType"`
	FirstTradeDate       int64                  `json:"firstTradeDate"`
	RegularMarketTime    int64                  `json:"regularMarketTime"`
	HasPrePostMarketData bool                   `json:"hasPrePostMarketData"`
	GmtOffset            int                    `json:"gmtoffset"`
	Timezone             string                 `json:"timezone"`
	ExchangeTimezoneName string                 `json:"exchangeTimezoneName"`
	RegularMarketPrice   float64                `json:"regularMarketPrice"`
	FiftyTwoWeekHigh     float64                `json:"fiftyTwoWeekHigh"`
	FiftyTwoWeekLow      float64                `json:"fiftyTwoWeekLow"`
	RegularMarketDayHigh float64                `json:"regularMarketDayHigh"`
	RegularMarketDayLow  float64                `json:"regularMarketDayLow"`
	RegularMarketVolume  int64                  `json:"regularMarketVolume"`
	LongName             string                 `json:"longName"`
	ShortName            string                 `json:"shortName"`
	ChartPreviousClose   float64                `json:"chartPreviousClose"`
	PreviousClose        float64                `json:"previousClose"`
	Scale                int                    `json:"scale"`
	PriceHint            int                    `json:"priceHint"`
	CurrentTradingPeriod YahooTradingPeriod     `json:"currentTradingPeriod"`
	TradingPeriods       [][]YahooTradingPeriod `json:"tradingPeriods"`
	DataGranularity      string                 `json:"dataGranularity"`
	Range                string                 `json:"range"`
	ValidRanges          []string               `json:"validRanges"`
}

type YahooOption

type YahooOption 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"`
}

type YahooOptionChain

type YahooOptionChain struct {
	Result []YahooOptionResult `json:"result"`
	Error  any                 `json:"error"`
}

type YahooOptionQuote

type YahooOptionQuote 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"`
	MarketState                       string  `json:"marketState"`
	RegularMarketChangePercent        float64 `json:"regularMarketChangePercent"`
	RegularMarketPrice                float64 `json:"regularMarketPrice"`
	ShortName                         string  `json:"shortName"`
	LongName                          string  `json:"longName"`
	Exchange                          string  `json:"exchange"`
	MessageBoardId                    string  `json:"messageBoardId"`
	ExchangeTimezoneName              string  `json:"exchangeTimezoneName"`
	ExchangeTimezoneShortName         string  `json:"exchangeTimezoneShortName"`
	GmtOffSetMilliseconds             int64   `json:"gmtOffSetMilliseconds"`
	Market                            string  `json:"market"`
	EsgPopulated                      bool    `json:"esgPopulated"`
	Currency                          string  `json:"currency"`
	HasPrePostMarketData              bool    `json:"hasPrePostMarketData"`
	FirstTradeDateMilliseconds        int64   `json:"firstTradeDateMilliseconds"`
	PriceHint                         int     `json:"priceHint"`
	PostMarketChangePercent           float64 `json:"postMarketChangePercent"`
	PostMarketPrice                   float64 `json:"postMarketPrice"`
	PostMarketChange                  float64 `json:"postMarketChange"`
	RegularMarketChange               float64 `json:"regularMarketChange"`
	RegularMarketDayHigh              float64 `json:"regularMarketDayHigh"`
	RegularMarketDayRange             string  `json:"regularMarketDayRange"`
	RegularMarketDayLow               float64 `json:"regularMarketDayLow"`
	RegularMarketVolume               int64   `json:"regularMarketVolume"`
	RegularMarketPreviousClose        float64 `json:"regularMarketPreviousClose"`
	Bid                               float64 `json:"bid"`
	Ask                               float64 `json:"ask"`
	BidSize                           int     `json:"bidSize"`
	AskSize                           int     `json:"askSize"`
	FullExchangeName                  string  `json:"fullExchangeName"`
	FinancialCurrency                 string  `json:"financialCurrency"`
	RegularMarketOpen                 float64 `json:"regularMarketOpen"`
	AverageDailyVolume3Month          int64   `json:"averageDailyVolume3Month"`
	AverageDailyVolume10Day           int64   `json:"averageDailyVolume10Day"`
	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"`
	EarningsCallTimestampStart        int64   `json:"earningsCallTimestampStart"`
	EarningsCallTimestampEnd          int64   `json:"earningsCallTimestampEnd"`
	IsEarningsDateEstimate            bool    `json:"isEarningsDateEstimate"`
	TrailingAnnualDividendRate        float64 `json:"trailingAnnualDividendRate"`
	TrailingPE                        float64 `json:"trailingPE"`
	DividendRate                      float64 `json:"dividendRate"`
	TrailingAnnualDividendYield       float64 `json:"trailingAnnualDividendYield"`
	DividendYield                     float64 `json:"dividendYield"`
	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"`
	SourceInterval                    int     `json:"sourceInterval"`
	ExchangeDataDelayedBy             int     `json:"exchangeDataDelayedBy"`
	AverageAnalystRating              string  `json:"averageAnalystRating"`
	Tradeable                         bool    `json:"tradeable"`
	CryptoTradeable                   bool    `json:"cryptoTradeable"`
	CorporateActions                  []any   `json:"corporateActions"`
	PostMarketTime                    int64   `json:"postMarketTime"`
	RegularMarketTime                 int64   `json:"regularMarketTime"`
	DisplayName                       string  `json:"displayName"`
	Symbol                            string  `json:"symbol"`
}

type YahooOptionResponse

type YahooOptionResponse struct {
	OptionChain YahooOptionChain `json:"optionChain"`
}

type YahooOptionResult

type YahooOptionResult struct {
	UnderlyingSymbol string           `json:"underlyingSymbol"`
	ExpirationDates  []int64          `json:"expirationDates"`
	Strikes          []float64        `json:"strikes"`
	HasMiniOptions   bool             `json:"hasMiniOptions"`
	Quote            YahooOptionQuote `json:"quote"`
	Options          []YahooOptions   `json:"options"`
}

type YahooOptions

type YahooOptions struct {
	ExpirationDate int64         `json:"expirationDate"`
	HasMiniOptions bool          `json:"hasMiniOptions"`
	Calls          []YahooOption `json:"calls"`
	Puts           []YahooOption `json:"puts"`
}

type YahooQuote

type YahooQuote struct {
	Open   []float64 `json:"open"`
	High   []float64 `json:"high"`
	Low    []float64 `json:"low"`
	Close  []float64 `json:"close"`
	Volume []int64   `json:"volume"`
}

type YahooTickerInfo

type YahooTickerInfo struct {
	MaxAge                     int         `json:"maxAge"`
	PreMarketChange            *PriceValue `json:"preMarketChange"`
	PreMarketPrice             *PriceValue `json:"preMarketPrice"`
	PreMarketSource            string      `json:"preMarketSource"`
	PostMarketChangePercent    *PriceValue `json:"postMarketChangePercent"`
	PostMarketChange           *PriceValue `json:"postMarketChange"`
	PostMarketTime             int64       `json:"postMarketTime"`
	PostMarketPrice            *PriceValue `json:"postMarketPrice"`
	PostMarketSource           string      `json:"postMarketSource"`
	RegularMarketChangePercent *PriceValue `json:"regularMarketChangePercent"`
	RegularMarketChange        *PriceValue `json:"regularMarketChange"`
	RegularMarketTime          int64       `json:"regularMarketTime"`
	PriceHint                  *PriceValue `json:"priceHint"`
	RegularMarketPrice         *PriceValue `json:"regularMarketPrice"`
	RegularMarketDayHigh       *PriceValue `json:"regularMarketDayHigh"`
	RegularMarketDayLow        *PriceValue `json:"regularMarketDayLow"`
	RegularMarketVolume        *PriceValue `json:"regularMarketVolume"`
	AverageDailyVolume10Day    *PriceValue `json:"averageDailyVolume10Day"`
	AverageDailyVolume3Month   *PriceValue `json:"averageDailyVolume3Month"`
	RegularMarketPreviousClose *PriceValue `json:"regularMarketPreviousClose"`
	RegularMarketSource        string      `json:"regularMarketSource"`
	RegularMarketOpen          *PriceValue `json:"regularMarketOpen"`
	StrikePrice                *PriceValue `json:"strikePrice"`
	OpenInterest               *PriceValue `json:"openInterest"`
	Exchange                   string      `json:"exchange"`
	ExchangeName               string      `json:"exchangeName"`
	ExchangeDataDelayedBy      int         `json:"exchangeDataDelayedBy"`
	MarketState                string      `json:"marketState"`
	QuoteType                  string      `json:"quoteType"`
	Symbol                     string      `json:"symbol"`
	UnderlyingSymbol           *string     `json:"underlyingSymbol"`
	ShortName                  string      `json:"shortName"`
	LongName                   string      `json:"longName"`
	Currency                   string      `json:"currency"`
	QuoteSourceName            string      `json:"quoteSourceName"`
	CurrencySymbol             string      `json:"currencySymbol"`
	FromCurrency               *string     `json:"fromCurrency"`
	ToCurrency                 *string     `json:"toCurrency"`
	LastMarket                 *string     `json:"lastMarket"`
	Volume24Hr                 *PriceValue `json:"volume24Hr"`
	VolumeAllCurrencies        *PriceValue `json:"volumeAllCurrencies"`
	CirculatingSupply          *PriceValue `json:"circulatingSupply"`
	MarketCap                  *PriceValue `json:"marketCap"`
}

YahooTickerInfo --> Struct to hold key metadata about the ticker

type YahooTradingPeriod

type YahooTradingPeriod struct {
	Timezone  string `json:"timezone"`
	End       int64  `json:"end"`
	Start     int64  `json:"start"`
	GmtOffset int    `json:"gmtoffset"`
}

Jump to

Keyboard shortcuts

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