package module
v1.1.0 Latest Latest

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

Go to latest
Published: May 8, 2023 License: MIT Imports: 12 Imported by: 205



GoDoc Build Status Coverage Status


This go package aims to provide a go application with access to current and historical financial markets data in streamlined, well-formatted structures.

Check out the qtrn cli application, which is intended as a living example of this package. It prints quotes/options info in your favorite command-line in a few keystrokes!

Description Source
Quote(s) Yahoo finance
Equity quote(s) Yahoo finance
Index quote(s) Yahoo finance
Option quote(s) Yahoo finance
Forex pair quote(s) Yahoo finance
Cryptocurrency pair quote(s) Yahoo finance
Futures quote(s) Yahoo finance
ETF quote(s) Yahoo finance
Mutual fund quote(s) Yahoo finance
Historical quotes Yahoo finance
Options straddles Yahoo finance


A neatly formatted detailed list of implementation instructions and examples will be available on the piquette website.

For now, for details on all the functionality in this library, see the GoDoc documentation.


This project supports modules and Go 1.13+. Add finance-go to your own project the usual way -

go get

Usage example

Library usage is meant to be very specific about the user's intentions.

q, err := quote.Get("AAPL")
if err != nil {
  // Uh-oh.  

// Success!
Equity quote (more fields)
q, err := equity.Get("AAPL")
if err != nil {
  // Uh-oh.  

// Success!
Historical quotes (OHLCV)
params := &chart.Params{
  Symbol:   "TWTR",
  Interval: datetime.OneHour,
iter := chart.Get(params)

for iter.Next() {
if err := iter.Err(); err != nil {


Pull requests from the community are welcome. If you submit one, please keep the following guidelines in mind:

  1. All types, structs and funcs should be documented.
  2. Ensure that make test succeeds.


The test suite needs testify's require package to run:

It also depends on a running instance of a test server finance-mock, so make sure to fetch that project and run the application from another terminal session (finance-mock's README contains more information).

  docker run -p 12111:12111 piquette/finance-mock:latest
brew tap piquette/finance-mock
brew install finance-mock
go get -u

Run all tests:

go test ./...

Run tests for one package:

go test ./equity

Run a single test:

go test ./equity -run TestGet

For any requests, bug or comments, please open an issue or submit a pull request. Also please email or tweet me as needed.


  • Yahoo changes their finance APIs without warning, which is their right to do so. However, its annoying and leads to some instability in this project..
  • Big shoutout to Stripe and the team working on the stripe-go project, I took a lot of library design / implementation hints from them.




View Source
const (
	// YFinBackend is a constant representing the yahoo service backend.
	YFinBackend SupportedBackend = "yahoo"
	// YFinURL is the URL of the yahoo service backend.
	YFinURL string = ""
	// BATSBackend is a constant representing the uploads service backend.
	BATSBackend SupportedBackend = "bats"
	// BATSURL is the URL of the uploads service backend.
	BATSURL string = ""
View Source
const (
	// QuoteTypeEquity the returned quote should be an equity.
	QuoteTypeEquity QuoteType = "EQUITY"
	// QuoteTypeIndex the returned quote should be an index.
	QuoteTypeIndex QuoteType = "INDEX"
	// QuoteTypeOption the returned quote should be an option contract.
	QuoteTypeOption QuoteType = "OPTION"
	// QuoteTypeForexPair the returned quote should be a forex pair.
	QuoteTypeForexPair QuoteType = "CURRENCY"
	// QuoteTypeCryptoPair the returned quote should be a crypto pair.
	QuoteTypeCryptoPair QuoteType = "CRYPTOCURRENCY"
	// QuoteTypeFuture the returned quote should be a futures contract.
	QuoteTypeFuture QuoteType = "FUTURE"
	// QuoteTypeETF the returned quote should be an etf.
	QuoteTypeETF QuoteType = "ETF"
	// QuoteTypeMutualFund the returned quote should be an mutual fund.
	QuoteTypeMutualFund QuoteType = "MUTUALFUND"

	// MarketStatePrePre pre-pre market state.
	MarketStatePrePre MarketState = "PREPRE"
	// MarketStatePre pre market state.
	MarketStatePre MarketState = "PRE"
	// MarketStateRegular regular market state.
	MarketStateRegular MarketState = "REGULAR"
	// MarketStatePost post market state.
	MarketStatePost MarketState = "POST"
	// MarketStatePostPost post-post market state.
	MarketStatePostPost MarketState = "POSTPOST"
	// MarketStateClosed closed market state.
	MarketStateClosed MarketState = "CLOSED"


This section is empty.


func CreateArgumentError

func CreateArgumentError() error

CreateArgumentError returns an error with a message about missing arguments.

func CreateChartTimeError

func CreateChartTimeError() error

CreateChartTimeError returns an error with a message improper chart arguments.

func CreateRemoteError

func CreateRemoteError(e error) error

CreateRemoteError returns an error with a message about a remote api problem.

func CreateRemoteErrorS

func CreateRemoteErrorS(str string) error

CreateRemoteErrorS returns an error with a message about a remote api problem.

func SetBackend

func SetBackend(backend SupportedBackend, b Backend)

SetBackend sets the backend used in the binding.

func SetHTTPClient

func SetHTTPClient(client *http.Client)

SetHTTPClient overrides the default HTTP client. This is useful if you're running in a Google AppEngine environment where the http.DefaultClient is not available.


type Backend

type Backend interface {
	Call(path string, body *form.Values, ctx *context.Context, v interface{}) error

Backend is an interface for making calls against an api service. This interface exists to enable mocking for during testing if needed.

func GetBackend

func GetBackend(backend SupportedBackend) Backend

GetBackend returns the currently used backend in the binding.

type BackendConfiguration

type BackendConfiguration struct {
	Type       SupportedBackend
	URL        string
	HTTPClient *http.Client

BackendConfiguration is the internal implementation for making HTTP calls.

func (*BackendConfiguration) Call

func (s *BackendConfiguration) Call(path string, form *form.Values, ctx *context.Context, v interface{}) error

Call is the Backend.Call implementation for invoking market data APIs.

func (*BackendConfiguration) Do

func (s *BackendConfiguration) Do(req *http.Request, v interface{}) error

Do is used by Call to execute an API request and parse the response. It uses the backend's HTTP client to execute the request and unmarshals the response into v. It also handles unmarshaling errors returned by the API.

func (*BackendConfiguration) NewRequest

func (s *BackendConfiguration) NewRequest(method, path string, ctx *context.Context) (*http.Request, error)

NewRequest is used by Call to generate an http.Request.

type Backends

type Backends struct {
	YFin, Bats Backend
	// contains filtered or unexported fields

Backends are the currently supported endpoints.

func NewBackends

func NewBackends(httpClient *http.Client) *Backends

NewBackends creates a new set of backends with the given HTTP client. You should only need to use this for testing purposes or on App Engine.

type ChartBar

type ChartBar struct {
	Open      decimal.Decimal
	Low       decimal.Decimal
	High      decimal.Decimal
	Close     decimal.Decimal
	AdjClose  decimal.Decimal
	Volume    int
	Timestamp int

ChartBar is a single instance of a chart bar.

type ChartMeta

type ChartMeta struct {
	Currency             string    `json:"currency" csv:"currency"`
	Symbol               string    `json:"symbol" csv:"symbol"`
	ExchangeName         string    `json:"exchangeName" csv:"exchangeName"`
	QuoteType            QuoteType `json:"instrumentType" csv:"instrumentType"`
	FirstTradeDate       int       `json:"firstTradeDate" csv:"firstTradeDate"`
	Gmtoffset            int       `json:"gmtoffset" csv:"gmtoffset"`
	Timezone             string    `json:"timezone" csv:"timezone"`
	ExchangeTimezoneName string    `json:"exchangeTimezoneName" csv:"exchangeTimezoneName"`
	ChartPreviousClose   float64   `json:"chartPreviousClose" csv:"chartPreviousClose"`
	CurrentTradingPeriod struct {
		Pre struct {
			Timezone  string `json:"timezone" csv:"timezone"`
			Start     int    `json:"start" csv:"start"`
			End       int    `json:"end" csv:"end"`
			Gmtoffset int    `json:"gmtoffset" csv:"gmtoffset"`
		} `json:"pre" csv:"pre_,inline"`
		Regular struct {
			Timezone  string `json:"timezone" csv:"timezone"`
			Start     int    `json:"start" csv:"start"`
			End       int    `json:"end" csv:"end"`
			Gmtoffset int    `json:"gmtoffset" csv:"gmtoffset"`
		} `json:"regular" csv:"regular_,inline"`
		Post struct {
			Timezone  string `json:"timezone" csv:"timezone"`
			Start     int    `json:"start" csv:"start"`
			End       int    `json:"end" csv:"end"`
			Gmtoffset int    `json:"gmtoffset" csv:"gmtoffset"`
		} `json:"post" csv:"post_,inline"`
	} `json:"currentTradingPeriod" csv:"currentTradingPeriod_,inline"`
	DataGranularity string   `json:"dataGranularity" csv:"dataGranularity"`
	ValidRanges     []string `json:"validRanges" csv:"-"`

ChartMeta is meta data associated with a chart response.

type Contract

type Contract struct {
	Symbol            string  `json:"contractSymbol" csv:"contractSymbol"`
	Strike            float64 `json:"strike" csv:"strike"`
	Currency          string  `json:"currency" csv:"currency"`
	LastPrice         float64 `json:"lastPrice" csv:"lastPrice"`
	Change            float64 `json:"change" csv:"change"`
	PercentChange     float64 `json:"percentChange" csv:"percentChange"`
	Volume            int     `json:"volume" csv:"volume"`
	OpenInterest      int     `json:"openInterest" csv:"openInterest"`
	Bid               float64 `json:"bid" csv:"bid"`
	Ask               float64 `json:"ask" csv:"ask"`
	Size              string  `json:"contractSize" csv:"contractSize"`
	Expiration        int     `json:"expiration" csv:"expiration"`
	LastTradeDate     int     `json:"lastTradeDate" csv:"lastTradeDate"`
	ImpliedVolatility float64 `json:"impliedVolatility" csv:"impliedVolatility"`
	InTheMoney        bool    `json:"inTheMoney" csv:"inTheMoney"`

Contract is a struct containing a single option contract, usually part of a chain.

type CryptoPair

type CryptoPair struct {
	// Cryptocurrency-only fields.
	Algorithm           string `json:"algorithm" csv:"algorithm"`
	StartDate           int    `json:"startDate" csv:"startDate"`
	MaxSupply           int    `json:"maxSupply" csv:"maxSupply"`
	CirculatingSupply   int    `json:"circulatingSupply" csv:"circulatingSupply"`
	VolumeLastDay       int    `json:"volume24Hr" csv:"volume24Hr"`
	VolumeAllCurrencies int    `json:"volumeAllCurrencies" csv:"volumeAllCurrencies"`

CryptoPair represents a single crypto currency pair quote.

type ETF

type ETF struct {
	// MutualFund/ETF-only fields.
	YTDReturn                    float64 `json:"ytdReturn" csv:"ytdReturn"`
	TrailingThreeMonthReturns    float64 `json:"trailingThreeMonthReturns" csv:"trailingThreeMonthReturns"`
	TrailingThreeMonthNavReturns float64 `json:"trailingThreeMonthNavReturns" csv:"trailingThreeMonthNavReturns"`

ETF represents a single etf quote.

type Equity

type Equity struct {
	// Equity-only fields.
	LongName                    string  `json:"longName" csv:"longName"`
	EpsTrailingTwelveMonths     float64 `json:"epsTrailingTwelveMonths" csv:"epsTrailingTwelveMonths"`
	EpsForward                  float64 `json:"epsForward" csv:"epsForward"`
	EarningsTimestamp           int     `json:"earningsTimestamp" csv:"earningsTimestamp"`
	EarningsTimestampStart      int     `json:"earningsTimestampStart" csv:"earningsTimestampStart"`
	EarningsTimestampEnd        int     `json:"earningsTimestampEnd" csv:"earningsTimestampEnd"`
	TrailingAnnualDividendRate  float64 `json:"trailingAnnualDividendRate" csv:"trailingAnnualDividendRate"`
	DividendDate                int     `json:"dividendDate" csv:"dividendDate"`
	TrailingAnnualDividendYield float64 `json:"trailingAnnualDividendYield" csv:"trailingAnnualDividendYield"`
	TrailingPE                  float64 `json:"trailingPE" csv:"trailingPE"`
	ForwardPE                   float64 `json:"forwardPE" csv:"forwardPE"`
	BookValue                   float64 `json:"bookValue" csv:"bookValue"`
	PriceToBook                 float64 `json:"priceToBook" csv:"priceToBook"`
	SharesOutstanding           int     `json:"sharesOutstanding" csv:"sharesOutstanding"`
	MarketCap                   int64   `json:"marketCap" csv:"marketCap"`

Equity representa a single equity quote.

type ForexPair

type ForexPair struct {

ForexPair represents a single forex currency pair quote.

type Future

type Future struct {
	// Options/Futures-only fields.
	UnderlyingSymbol         string  `json:"underlyingSymbol" csv:"underlyingSymbol"`
	OpenInterest             int     `json:"openInterest" csv:"openInterest"`
	ExpireDate               int     `json:"expireDate" csv:"expireDate"`
	Strike                   float64 `json:"strike" csv:"strike"`
	UnderlyingExchangeSymbol string  `json:"underlyingExchangeSymbol" csv:"underlyingExchangeSymbol"`
	HeadSymbolAsString       string  `json:"headSymbolAsString" csv:"headSymbolAsString"`
	IsContractSymbol         bool    `json:"contractSymbol" csv:"contractSymbol"`

Future represents a single futures contract quote for a specified strike and expiration.

type Index

type Index struct {

Index represents a single market Index quote. The term `quote` here doesn't really apply in a practical sense, as indicies themselves are by definition not tradable assets.

type MarketState

type MarketState string

MarketState alias for market state.

type MutualFund

type MutualFund struct {
	// MutualFund/ETF-only fields.
	YTDReturn                    float64 `json:"ytdReturn" csv:"ytdReturn"`
	TrailingThreeMonthReturns    float64 `json:"trailingThreeMonthReturns" csv:"trailingThreeMonthReturns"`
	TrailingThreeMonthNavReturns float64 `json:"trailingThreeMonthNavReturns" csv:"trailingThreeMonthNavReturns"`

MutualFund represents a single mutual fund share quote.

type OHLCHistoric added in v1.1.0

type OHLCHistoric struct {
	Open      float64
	Low       float64
	High      float64
	Close     float64
	AdjClose  float64
	Volume    int
	Timestamp int

OHLCHistoric is a historical quotation.

type Option

type Option struct {
	// Options/Futures-only fields.
	UnderlyingSymbol         string  `json:"underlyingSymbol" csv:"underlyingSymbol"`
	OpenInterest             int     `json:"openInterest" csv:"openInterest"`
	ExpireDate               int     `json:"expireDate" csv:"expireDate"`
	Strike                   float64 `json:"strike" csv:"strike"`
	UnderlyingExchangeSymbol string  `json:"underlyingExchangeSymbol" csv:"underlyingExchangeSymbol"`

Option represents a single option contract quote for a specified strike and expiration.

type OptionsMeta

type OptionsMeta struct {
	UnderlyingSymbol   string    `json:"underlyingSymbol" csv:"underlyingSymbol"`
	ExpirationDate     int       `json:"expirationDate" csv:"expirationDate"`
	AllExpirationDates []int     `json:"allExpirationDates" csv:"-"`
	Strikes            []float64 `json:"strikes" csv:"-"`
	HasMiniOptions     bool      `json:"hasMiniOptions"`
	Quote              *Quote    `json:"quote,omitempty" csv:"quote_,inline"`

OptionsMeta is meta data associated with an options response.

type Params

type Params struct {
	// Context used for request. It may carry deadlines, cancelation signals,
	// and other request-scoped values across API boundaries and between
	// processes.
	// Note that a cancelled or timed out context does not provide any
	// guarantee whether the operation was or was not completed.
	Context *context.Context `form:"-"`

Params used as a parameter to many api functions.

type Printfer

type Printfer interface {
	Printf(format string, v ...interface{})

Printfer is an interface to be implemented by Logger.

var (
	// LogLevel is the logging level for this library.
	// 0: no logging
	// 1: errors only
	// 2: errors + informational (default)
	// 3: errors + informational + debug
	LogLevel = 0

	// Logger controls how this library performs logging at a package level. It is useful
	// to customise if you need it prefixed for your application to meet other
	// requirements
	Logger Printfer

type Quote

type Quote struct {
	// Quote classifying fields.
	Symbol      string      `json:"symbol" csv:"symbol"`
	MarketState MarketState `json:"marketState" csv:"marketState"`
	QuoteType   QuoteType   `json:"quoteType" csv:"quoteType"`
	ShortName   string      `json:"shortName" csv:"shortName"`

	// Regular session quote data.
	RegularMarketChangePercent float64 `json:"regularMarketChangePercent" csv:"regularMarketChangePercent"`
	RegularMarketPreviousClose float64 `json:"regularMarketPreviousClose" csv:"regularMarketPreviousClose"`
	RegularMarketPrice         float64 `json:"regularMarketPrice" csv:"regularMarketPrice"`
	RegularMarketTime          int     `json:"regularMarketTime" csv:"regularMarketTime"`
	RegularMarketChange        float64 `json:"regularMarketChange" csv:"regularMarketChange"`
	RegularMarketOpen          float64 `json:"regularMarketOpen" csv:"regularMarketOpen"`
	RegularMarketDayHigh       float64 `json:"regularMarketDayHigh" csv:"regularMarketDayHigh"`
	RegularMarketDayLow        float64 `json:"regularMarketDayLow" csv:"regularMarketDayLow"`
	RegularMarketVolume        int     `json:"regularMarketVolume" csv:"regularMarketVolume"`

	// Quote depth.
	Bid     float64 `json:"bid" csv:"bid"`
	Ask     float64 `json:"ask" csv:"ask"`
	BidSize int     `json:"bidSize" csv:"bidSize"`
	AskSize int     `json:"askSize" csv:"askSize"`

	// Pre-market quote data.
	PreMarketPrice         float64 `json:"preMarketPrice" csv:"preMarketPrice"`
	PreMarketChange        float64 `json:"preMarketChange" csv:"preMarketChange"`
	PreMarketChangePercent float64 `json:"preMarketChangePercent" csv:"preMarketChangePercent"`
	PreMarketTime          int     `json:"preMarketTime" csv:"preMarketTime"`

	// Post-market quote data.
	PostMarketPrice         float64 `json:"postMarketPrice" csv:"postMarketPrice"`
	PostMarketChange        float64 `json:"postMarketChange" csv:"postMarketChange"`
	PostMarketChangePercent float64 `json:"postMarketChangePercent" csv:"postMarketChangePercent"`
	PostMarketTime          int     `json:"postMarketTime" csv:"postMarketTime"`

	// 52wk ranges.
	FiftyTwoWeekLowChange         float64 `json:"fiftyTwoWeekLowChange" csv:"fiftyTwoWeekLowChange"`
	FiftyTwoWeekLowChangePercent  float64 `json:"fiftyTwoWeekLowChangePercent" csv:"fiftyTwoWeekLowChangePercent"`
	FiftyTwoWeekHighChange        float64 `json:"fiftyTwoWeekHighChange" csv:"fiftyTwoWeekHighChange"`
	FiftyTwoWeekHighChangePercent float64 `json:"fiftyTwoWeekHighChangePercent" csv:"fiftyTwoWeekHighChangePercent"`
	FiftyTwoWeekLow               float64 `json:"fiftyTwoWeekLow" csv:"fiftyTwoWeekLow"`
	FiftyTwoWeekHigh              float64 `json:"fiftyTwoWeekHigh" csv:"fiftyTwoWeekHigh"`

	// Averages.
	FiftyDayAverage                   float64 `json:"fiftyDayAverage" csv:"fiftyDayAverage"`
	FiftyDayAverageChange             float64 `json:"fiftyDayAverageChange" csv:"fiftyDayAverageChange"`
	FiftyDayAverageChangePercent      float64 `json:"fiftyDayAverageChangePercent" csv:"fiftyDayAverageChangePercent"`
	TwoHundredDayAverage              float64 `json:"twoHundredDayAverage" csv:"twoHundredDayAverage"`
	TwoHundredDayAverageChange        float64 `json:"twoHundredDayAverageChange" csv:"twoHundredDayAverageChange"`
	TwoHundredDayAverageChangePercent float64 `json:"twoHundredDayAverageChangePercent" csv:"twoHundredDayAverageChangePercent"`

	// Volume metrics.
	AverageDailyVolume3Month int `json:"averageDailyVolume3Month" csv:"averageDailyVolume3Month"`
	AverageDailyVolume10Day  int `json:"averageDailyVolume10Day" csv:"averageDailyVolume10Day"`

	// Quote meta-data.
	QuoteSource               string `json:"quoteSourceName" csv:"quoteSourceName"`
	CurrencyID                string `json:"currency" csv:"currency"`
	IsTradeable               bool   `json:"tradeable" csv:"tradeable"`
	QuoteDelay                int    `json:"exchangeDataDelayedBy" csv:"exchangeDataDelayedBy"`
	FullExchangeName          string `json:"fullExchangeName" csv:"fullExchangeName"`
	SourceInterval            int    `json:"sourceInterval" csv:"sourceInterval"`
	ExchangeTimezoneName      string `json:"exchangeTimezoneName" csv:"exchangeTimezoneName"`
	ExchangeTimezoneShortName string `json:"exchangeTimezoneShortName" csv:"exchangeTimezoneShortName"`
	GMTOffSetMilliseconds     int    `json:"gmtOffSetMilliseconds" csv:"gmtOffSetMilliseconds"`
	MarketID                  string `json:"market" csv:"market"`
	ExchangeID                string `json:"exchange" csv:"exchange"`

Quote is the basic quote structure shared across asset classes.

Contains most fields that are common across all possible assets.

type QuoteType

type QuoteType string

QuoteType alias for asset classification.

type Straddle

type Straddle struct {
	Strike float64   `json:"strike" csv:"strike"`
	Call   *Contract `json:"call,omitempty" csv:"call_,inline"`
	Put    *Contract `json:"put,omitempty" csv:"put_,inline"`

Straddle is a put/call straddle for a particular strike.

type SupportedBackend

type SupportedBackend string

SupportedBackend is an enumeration of supported api endpoints.

type YfinError

type YfinError struct {
	Code        string `json:"code"`
	Description string `json:"description"`

YfinError represents information returned in an error response.

func (*YfinError) Error

func (e *YfinError) Error() string

Error serializes the error object to JSON and returns it as a string.


Path Synopsis

Jump to

Keyboard shortcuts

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