yfi

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2022 License: MIT Imports: 9 Imported by: 0

README

Go Reference

yfi provides an unofficial Go wrapper for the Yahoo Finance API.

Disclaimer: yfi is not affiliated with or produced by Yahoo. Data obtained through yfi should be used only for personal, non-commercial applications.

yfi attempts to unify several versions of the Yahoo Finance API, each of which is sparsely documented and not guaranteed to be stable. Presently, there are 3 main representations of an asset, each providing different information:

  1. Ticker contains historical data in a simple and straightforward manner
  2. Quote contains current market data about an asset
  3. QuoteSummary contains extensive data about an asset based on the selected QueryParam. Because of how varied the data can be, the response is returned as a map[string]any. The plan is eventually to provide individual structs for each response type.

Documentation

Overview

Package yfi provides an unofficial wrapper for the Yahoo Finance API.

Disclaimer: yfi is not affiliated with or produced by Yahoo. Data obtained through yfi should be used only for personal, non-commercial applications.

yfi attempts to unify several versions of the Yahoo Finance API, each of which is sparsely documented and not guaranteed to be stable. Presently, there are 3 main representations of an asset, each providing different information:

  1. Ticker contains historical data in a simple and straightforward manner.
  2. Quote contains current market data about an asset.
  3. QuoteSummary contains extensive data about an asset based on the selected QueryParam. Because of how varied the data can be, the response is returned as a map[string]any. The plan is eventually to provide individual structs for each response type.

Index

Constants

View Source
const (
	V1      = `https://query2.finance.yahoo.com/v1/finance/`
	V6      = `https://query2.finance.yahoo.com/v6/finance/`
	V7      = `https://query2.finance.yahoo.com/v7/finance/`
	V10     = `https://query2.finance.yahoo.com/v10/finance/`
	TIMEOUT = 5 * time.Second
	// The default net/http user-agent is blocked for some Yahoo Finance endpoints
	YFI_USER_AGENT = `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0`
)

Variables

View Source
var (
	ErrUnauthReq     = errors.New("request error 401")
	ErrNotFound      = errors.New("request error 404")
	ErrServer        = errors.New("request error 500")
	ErrMalformedResp = errors.New("malformed response")
	ErrInterval      = errors.New("invalid interval")
	ErrRange         = errors.New("invalid time range")
	ErrQuoteParam    = errors.New("invalid quote param")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	TimeOut     time.Duration
	HttpClient  http.Client
	WaitPeriod  time.Duration
	HardTimeOut bool
	Verbose     bool
	UserAgent   string
}

func NewClient

func NewClient() Client

func (*Client) GetCurrencies

func (c *Client) GetCurrencies() ([]Currency, error)

func (*Client) GetMarketsSummary

func (c *Client) GetMarketsSummary() ([]MarketSummary, error)

func (*Client) GetQuoteSummary

func (c *Client) GetQuoteSummary(symbol string, quoteParams []QuoteParam) (map[string]any, error)

func (*Client) GetQuotes

func (c *Client) GetQuotes(symbols []string) (map[string]Quote, error)

GetQuotes returns a map[string]Quote of all responses provided by the Yahoo Finance API. The API silently ignores queries for invalid symbols.

func (*Client) GetTicker added in v0.4.0

func (c *Client) GetTicker(symbol string, interval TimeSpan, startDate, endDate time.Time) (Ticker, error)

Retrieve historical data for a given ticker. The response is a Ticker and an error.

func (*Client) GetTickers added in v0.4.0

func (c *Client) GetTickers(symbols []string, interval TimeSpan, startDate, endDate time.Time) []Ticker

Returns historical data for multiple tickers. Each request is followed by a WaitPeriod to reduce the risk of rate limiting. errors are included in each Ticker and are not returned separately.

func (*Client) GetTickersBurst added in v0.4.0

func (c *Client) GetTickersBurst(symbols []string, interval TimeSpan, startDate, endDate time.Time) []Ticker

GetTickersBurst sends requests to the Yahoo Finance API that are spaced out by the WaitPeriod, regardless of whether reponses to previous requests have been received. errors are included in the body of the Ticker and are not returned separately. The context timeout for each request is set to the greater of 30 seconds or the current Client.TimeOut to avoid excessive errors when a large number of requests are made. This behavior can be disabled by setting the Client.HardTimeOut value to true.

type Currency

type Currency struct {
	ShortName     string `json:"shortName"`
	LongName      string `json:"longName"`
	Symbol        string `json:"symbol"`
	LocalLongName string `json:"localLongName"`
}

Currency represents the Yahoo Finance curency response

type MarketSummary

type MarketSummary struct {
	FullExchangeName            string   `json:"fullExchangeName"`
	Symbol                      string   `json:"symbol"`
	GmtOffSetMilliseconds       int64    `json:"gmtOffSetMilliseconds"`
	RegularMarketTime           yfiTime  `json:"regularMarketTime"`
	RegularMarketChangePercent  yfiFloat `json:"regularMarketChangePercent"`
	QuoteType                   string   `json:"quoteType"`
	TypeDisp                    string   `json:"typeDisp"`
	Tradeable                   bool     `json:"tradeable"`
	RegularMarketPreviousClose  yfiFloat `json:"regularMarketPreviousClose"`
	RegularMarketChange         yfiFloat `json:"regularMarketChange"`
	CryptoTradeable             bool     `json:"cryptoTradeable"`
	FirstTradeDateMilliseconds  int64    `json:"firstTradeDateMilliseconds"`
	ExchangeDataDelayedBy       int64    `json:"exchangeDataDelayedBy"`
	ExchangeTimezoneShortName   string   `json:"exchangeTimezoneShortName"`
	CustomePriceAlertConfidence string   `json:"customePriceAlertConfidence"`
	RegularMarketPrice          yfiFloat `json:"regularMarketPrice"`
	MarketState                 string   `json:"marketState"`
	Market                      string   `json:"market"`
	QuoteSourceName             string   `json:"quoteSourceName"`
	PriceHint                   int64    `json:"priceHint"`
	Exchange                    string   `json:"exchange"`
	SourceInterval              int64    `json:"sourceInterval"`
	ShortName                   string   `json:"shortName"`
	Region                      string   `json:"region"`
	Triggerable                 bool     `json:"triggerable"`
}

MarketSummary represents the current state of a particular exchange

type Quote

type Quote 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"`
	Curency                           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             int     `json:"gmtOffSetMilliseconds"`
	Market                            string  `json:"market"`
	EsgPopulated                      bool    `json:"esgPopulated"`
	RegularMarketChangePercent        float64 `json:"regularMarketChangePercent"`
	RegularMarketPrice                float64 `json:"regularMarketPrice"`
	MarketState                       string  `json:"marketState"`
	YtdReturn                         float64 `json:"ytdReturn"`
	TrailingThreeMonthReturns         float64 `json:"trailingThreeMonthReturns"`
	TrailingThreeMonthNavReturns      float64 `json:"trailingThreeMonthNavReturns"`
	EpsTrailingTwelveMonths           float64 `json:"epsTrailingTwelveMonths"`
	SharesOutstanding                 int     `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                         int     `json:"marketCap"`
	PriceToBook                       float64 `json:"priceToBook"`
	SourceInterval                    int     `json:"sourceInterval"`
	ExchangeDataDelayedBy             int     `json:"exchangeDataDelayedBy"`
	Tradeable                         bool    `json:"tradeable"`
	CryptoTradeable                   bool    `json:"cryptoTradeable"`
	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          int     `json:"averageDailyVolume3Month"`
	AverageDailyVolume10Day           int     `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"`
	TrailingAnnualDividendRate        float64 `json:"trailingAnnualDividendRate"`
	TrailingPE                        float64 `json:"trailingPE"`
	TrailingAnnualDividendYield       float64 `json:"trailingAnnualDividendYield"`
	FirstTradeDateMilliseconds        int     `json:"firstTradeDateMilliseconds"`
	PriceHint                         int     `json:"priceHint"`
	PostMarketChangePercent           float64 `json:"postMarketChangePercent"`
	PostMarketTime                    int     `json:"postMarketTime"`
	PostMarketPrice                   float64 `json:"postMarketPrice"`
	PostMarketChange                  float64 `json:"postMarketChange"`
	RegularMarketChange               float64 `json:"regularMarketChange"`
	RegularMarketTime                 int     `json:"regularMarketTime"`
	RegularMarketDayHigh              float64 `json:"regularMarketDayHigh"`
	RegularMarketDayRange             string  `json:"regularMarketDayRange"`
	RegularMarketDayLow               float64 `json:"regularMarketDayLow"`
	RegularMarketVolume               int     `json:"regularMarketVolume"`
	Symbol                            string  `json:"symbol"`
}

type QuoteParam

type QuoteParam string
const (
	AssetProfile                      QuoteParam = "assetProfile"
	BalanceSheetHistory               QuoteParam = "balanceSheetHistory"
	BalanceSheetHistoryQuarterly      QuoteParam = "balanceSheetHistoryQuarterly"
	CalendarEvents                    QuoteParam = "calendarEvents"
	CashflowStatementHistory          QuoteParam = "cashflowStatementHistory"
	CashflowStatementHistoryQuarterly QuoteParam = "cashflowStatementHistoryQuarterly"
	DefaultKeyStatistics              QuoteParam = "defaultKeyStatistics"
	Earnings                          QuoteParam = "earnings"
	EarningsHistory                   QuoteParam = "earningsHistory"
	EarningsTrend                     QuoteParam = "earningsTrend"
	EsgScores                         QuoteParam = "esgScores"
	FinancialData                     QuoteParam = "financialData"
	FundOwnership                     QuoteParam = "fundOwnership"
	FundPerformance                   QuoteParam = "fundPerformance"
	FundProfile                       QuoteParam = "fundProfile"
	IndexTrend                        QuoteParam = "indexTrend"
	IncomeStatementHistory            QuoteParam = "incomeStatementHistory"
	IncomeStatementHistoryQuarterly   QuoteParam = "incomeStatementHistoryQuarterly"
	IndustryTrend                     QuoteParam = "industryTrend"
	InsiderHolders                    QuoteParam = "insiderHolders"
	InstitutionOwnership              QuoteParam = "institutionOwnership"
	MajorHoldersBreakdown             QuoteParam = "majorHoldersBreakdown"
	PageViews                         QuoteParam = "pageViews"
	Price                             QuoteParam = "price"
	QuoteType                         QuoteParam = "quoteType"
	RecommendationTrend               QuoteParam = "recommendationTrend"
	SecFilings                        QuoteParam = "secFilings"
	NetSharePurchaseActivity          QuoteParam = "netSharePurchaseActivity"
	SectorTrend                       QuoteParam = "sectorTrend"
	SummaryDetail                     QuoteParam = "summaryDetail"
	SummaryProfile                    QuoteParam = "summaryProfile"
	TopHoldings                       QuoteParam = "topHoldings"
	UpgradeDowngradeHistory           QuoteParam = "upgradeDowngradeHistory"
)

type Ticker

type Ticker struct {
	Symbol           string
	Interval         TimeSpan
	HistoricDates    []int64
	HistoricOpen     []float64
	HistoricHigh     []float64
	HistoricLow      []float64
	HistoricClose    []float64
	HistoricAdjClose []float64
	HistoricVolume   []int
	Err              error
}

Tickers represent historical data for a given asset.

func (*Ticker) ToCsv

func (t *Ticker) ToCsv(filename string) error

Save Ticker to .csv file

func (*Ticker) ToJson

func (t *Ticker) ToJson(filename string) error

Save Ticker to .json file

type TimeSpan

type TimeSpan string
const (
	OneMinute      TimeSpan = "1m"
	TwoMinutes     TimeSpan = "2m"
	FiveMinutes    TimeSpan = "5m"
	FifteenMinutes TimeSpan = "15m"
	ThirtyMinutes  TimeSpan = "30m"
	SixtyMinutes   TimeSpan = "60m"
	NinetyMinutes  TimeSpan = "90m"
	OneHour        TimeSpan = "1h"
	OneDay         TimeSpan = "1d"
	FiveDays       TimeSpan = "5d"
	OneWeek        TimeSpan = "1wk"
	OneMonth       TimeSpan = "1mo"
	ThreeMonths    TimeSpan = "3mo"
	SixMonths      TimeSpan = "6mo"
	OneYear        TimeSpan = "1y"
	TwoYears       TimeSpan = "2y"
	FiveYears      TimeSpan = "5y"
	TenYears       TimeSpan = "10y"
	YTD            TimeSpan = "ytd"
	Max            TimeSpan = "max"
)

Jump to

Keyboard shortcuts

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