README

finance-go

GoDoc Build Status Coverage Status

Summary

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!

Features
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

Documentation

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.

Installation

It is best to use a dependency management tool, but if you want to retrieve it manually, use -

go get github.com/piquette/finance-go

Usage example

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

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

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

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

for iter.Next() {
  fmt.Println(iter.Bar())
}
if err := iter.Err(); err != nil {
  fmt.Println(err)
}

Development

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.

Test

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

github.com/stretchr/testify/require

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
  docker run -p 12111:12111 piquette/finance-mock:latest
Brew
brew tap piquette/finance-mock
brew install finance-mock
finance-mock
Go
go get -u github.com/piquette/finance-mock
finance-mock

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.

Notes

  • 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.

Documentation

Index

Constants

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 = "https://query2.finance.yahoo.com"
	// 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"
)

Variables

This section is empty.

Functions

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.

Types

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"`
	Symbol               string    `json:"symbol"`
	ExchangeName         string    `json:"exchangeName"`
	QuoteType            QuoteType `json:"instrumentType"`
	FirstTradeDate       int       `json:"firstTradeDate"`
	Gmtoffset            int       `json:"gmtoffset"`
	Timezone             string    `json:"timezone"`
	ExchangeTimezoneName string    `json:"exchangeTimezoneName"`
	ChartPreviousClose   float64   `json:"chartPreviousClose"`
	CurrentTradingPeriod struct {
		Pre struct {
			Timezone  string `json:"timezone"`
			Start     int    `json:"start"`
			End       int    `json:"end"`
			Gmtoffset int    `json:"gmtoffset"`
		} `json:"pre"`
		Regular struct {
			Timezone  string `json:"timezone"`
			Start     int    `json:"start"`
			End       int    `json:"end"`
			Gmtoffset int    `json:"gmtoffset"`
		} `json:"regular"`
		Post struct {
			Timezone  string `json:"timezone"`
			Start     int    `json:"start"`
			End       int    `json:"end"`
			Gmtoffset int    `json:"gmtoffset"`
		} `json:"post"`
	} `json:"currentTradingPeriod"`
	DataGranularity string   `json:"dataGranularity"`
	ValidRanges     []string `json:"validRanges"`
}

ChartMeta is meta data associated with a chart response.

type Contract

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

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

type CryptoPair

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

CryptoPair represents a single crypto currency pair quote.

type ETF

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

ETF represents a single etf quote.

type Equity

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

Equity representa a single equity quote.

type ForexPair

type ForexPair struct {
	Quote
}

ForexPair represents a single forex currency pair quote.

type Future

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

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

type Index

type Index struct {
	Quote
}

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 {
	Quote
	// MutualFund/ETF-only fields.
	YTDReturn                    float64 `json:"ytdReturn"`
	TrailingThreeMonthReturns    float64 `json:"trailingThreeMonthReturns"`
	TrailingThreeMonthNavReturns float64 `json:"trailingThreeMonthNavReturns"`
}

MutualFund represents a single mutual fund share quote.

type Option

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

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

type OptionsMeta

type OptionsMeta struct {
	UnderlyingSymbol   string
	ExpirationDate     int
	AllExpirationDates []int
	Strikes            []float64
	HasMiniOptions     bool
	Quote              *Quote
}

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"`
	MarketState MarketState `json:"marketState"`
	QuoteType   QuoteType   `json:"quoteType"`
	ShortName   string      `json:"shortName"`

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

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

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

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

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

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

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

	// Quote meta-data.
	QuoteSource               string `json:"quoteSourceName"`
	CurrencyID                string `json:"currency"`
	IsTradeable               bool   `json:"tradeable"`
	QuoteDelay                int    `json:"exchangeDataDelayedBy"`
	FullExchangeName          string `json:"fullExchangeName"`
	SourceInterval            int    `json:"sourceInterval"`
	ExchangeTimezoneName      string `json:"exchangeTimezoneName"`
	ExchangeTimezoneShortName string `json:"exchangeTimezoneShortName"`
	GMTOffSetMilliseconds     int    `json:"gmtOffSetMilliseconds"`
	MarketID                  string `json:"market"`
	ExchangeID                string `json:"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"`
	Call   *Contract `json:"call,omitempty"`
	Put    *Contract `json:"put,omitempty"`
}

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.