Merge pull request #64 from adelina-t/add_premarket

Add pre and post market change percentage.
master
Brandon Lee Camilleri 5 years ago committed by GitHub
commit d1305eb791
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 40
      layout.go
  2. 64
      yahoo_quotes.go

@ -5,22 +5,22 @@
package mop package mop
import ( import (
`bytes` "bytes"
`fmt` "fmt"
`reflect` "reflect"
`regexp` "regexp"
`strings` "strings"
`text/template` "text/template"
`time` "time"
) )
// Column describes formatting rules for individual column within the list // Column describes formatting rules for individual column within the list
// of stock quotes. // of stock quotes.
type Column struct { type Column struct {
width int // Column width. width int // Column width.
name string // The name of the field in the Stock struct. name string // The name of the field in the Stock struct.
title string // Column title to display in the header. title string // Column title to display in the header.
formatter func(... string) string // Optional function to format the contents of the column. formatter func(...string) string // Optional function to format the contents of the column.
} }
// Layout is used to format and display all the collected data, i.e. market // Layout is used to format and display all the collected data, i.e. market
@ -53,6 +53,8 @@ func NewLayout() *Layout {
{9, `Dividend`, `Dividend`, zero}, {9, `Dividend`, `Dividend`, zero},
{9, `Yield`, `Yield`, percent}, {9, `Yield`, `Yield`, percent},
{11, `MarketCap`, `MktCap`, currency}, {11, `MarketCap`, `MktCap`, currency},
{13, `PreOpen`, `PreMktChg%`, last},
{13, `AfterHours`, `AfterMktChg%`, last},
} }
layout.regex = regexp.MustCompile(`(\.\d+)[BMK]?$`) layout.regex = regexp.MustCompile(`(\.\d+)[BMK]?$`)
layout.marketTemplate = buildMarketTemplate() layout.marketTemplate = buildMarketTemplate()
@ -208,7 +210,7 @@ func buildQuotesTemplate() *template.Template {
{{.Header}} {{.Header}}
{{range.Stocks}}{{if .Advancing}}<green>{{end}}{{.Ticker}}{{.LastTrade}}{{.Change}}{{.ChangePct}}{{.Open}}{{.Low}}{{.High}}{{.Low52}}{{.High52}}{{.Volume}}{{.AvgVolume}}{{.PeRatio}}{{.Dividend}}{{.Yield}}{{.MarketCap}}</> {{range.Stocks}}{{if .Advancing}}<green>{{end}}{{.Ticker}}{{.LastTrade}}{{.Change}}{{.ChangePct}}{{.Open}}{{.Low}}{{.High}}{{.Low52}}{{.High52}}{{.Volume}}{{.AvgVolume}}{{.PeRatio}}{{.Dividend}}{{.Yield}}{{.MarketCap}}{{.PreOpen}}{{.AfterHours}}</>
{{end}}` {{end}}`
return template.Must(template.New(`quotes`).Parse(markup)) return template.Must(template.New(`quotes`).Parse(markup))
@ -256,7 +258,7 @@ func arrowFor(column int, profile *Profile) string {
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
func blank(str... string) string { func blank(str ...string) string {
if len(str) < 1 { if len(str) < 1 {
return "ERR" return "ERR"
} }
@ -268,8 +270,8 @@ func blank(str... string) string {
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
func zero(str... string) string { func zero(str ...string) string {
if len(str) < 2{ if len(str) < 2 {
return "ERR" return "ERR"
} }
if str[0] == `0.00` { if str[0] == `0.00` {
@ -280,7 +282,7 @@ func zero(str... string) string {
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
func last(str... string) string { func last(str ...string) string {
if len(str) < 1 { if len(str) < 1 {
return "ERR" return "ERR"
} }
@ -292,13 +294,13 @@ func last(str... string) string {
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
func currency(str... string) string { func currency(str ...string) string {
if len(str) < 2 { if len(str) < 2 {
return "ERR" return "ERR"
} }
//default to $ //default to $
symbol := "$" symbol := "$"
switch (str[1]){ switch str[1] {
case "JPY": case "JPY":
symbol = "¥" symbol = "¥"
break break
@ -321,7 +323,7 @@ func currency(str... string) string {
// Returns percent value truncated at 2 decimal points. // Returns percent value truncated at 2 decimal points.
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
func percent(str... string) string { func percent(str ...string) string {
if len(str) < 1 { if len(str) < 1 {
return "ERR" return "ERR"
} }

@ -5,14 +5,14 @@
package mop package mop
import ( import (
`bytes` "bytes"
`encoding/json` "encoding/json"
`fmt` "fmt"
`io/ioutil` "io/ioutil"
`net/http` "net/http"
`reflect` "reflect"
`strconv` "strconv"
`strings` "strings"
) )
// const quotesURL = `http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2oghjkva2r2rdyj3j1` // const quotesURL = `http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1c1p2oghjkva2r2rdyj3j1`
@ -24,25 +24,27 @@ const noDataIndicator = `N/A`
// Stock stores quote information for the particular stock ticker. The data // Stock stores quote information for the particular stock ticker. The data
// for all the fields except 'Advancing' is fetched using Yahoo market API. // for all the fields except 'Advancing' is fetched using Yahoo market API.
type Stock struct { type Stock struct {
Ticker string `json:"symbol"` // Stock ticker. Ticker string `json:"symbol"` // Stock ticker.
LastTrade string `json:"regularMarketPrice"` // l1: last trade. LastTrade string `json:"regularMarketPrice"` // l1: last trade.
Change string `json:"regularMarketChange"` // c6: change real time. Change string `json:"regularMarketChange"` // c6: change real time.
ChangePct string `json:"regularMarketChangePercent"` // k2: percent change real time. ChangePct string `json:"regularMarketChangePercent"` // k2: percent change real time.
Open string `json:"regularMarketOpen"` // o: market open price. Open string `json:"regularMarketOpen"` // o: market open price.
Low string `json:"regularMarketDayLow"` // g: day's low. Low string `json:"regularMarketDayLow"` // g: day's low.
High string `json:"regularMarketDayHigh"` // h: day's high. High string `json:"regularMarketDayHigh"` // h: day's high.
Low52 string `json:"fiftyTwoWeekLow"` // j: 52-weeks low. Low52 string `json:"fiftyTwoWeekLow"` // j: 52-weeks low.
High52 string `json:"fiftyTwoWeekHigh"` // k: 52-weeks high. High52 string `json:"fiftyTwoWeekHigh"` // k: 52-weeks high.
Volume string `json:"regularMarketVolume"` // v: volume. Volume string `json:"regularMarketVolume"` // v: volume.
AvgVolume string `json:"averageDailyVolume10Day"` // a2: average volume. AvgVolume string `json:"averageDailyVolume10Day"` // a2: average volume.
PeRatio string `json:"trailingPE"` // r2: P/E ration real time. PeRatio string `json:"trailingPE"` // r2: P/E ration real time.
PeRatioX string `json:"trailingPE"` // r: P/E ration (fallback when real time is N/A). PeRatioX string `json:"trailingPE"` // r: P/E ration (fallback when real time is N/A).
Dividend string `json:"trailingAnnualDividendRate"` // d: dividend. Dividend string `json:"trailingAnnualDividendRate"` // d: dividend.
Yield string `json:"trailingAnnualDividendYield"` // y: dividend yield. Yield string `json:"trailingAnnualDividendYield"` // y: dividend yield.
MarketCap string `json:"marketCap"` // j3: market cap real time. MarketCap string `json:"marketCap"` // j3: market cap real time.
MarketCapX string `json:"marketCap"` // j1: market cap (fallback when real time is N/A). MarketCapX string `json:"marketCap"` // j1: market cap (fallback when real time is N/A).
Currency string `json:"currency"` // String code for currency of stock. Currency string `json:"currency"` // String code for currency of stock.
Advancing bool // True when change is >= $0. Advancing bool // True when change is >= $0.
PreOpen string `json:"preMarketChangePercent,omitempty"`
AfterHours string `json:"postMarketChangePercent,omitempty"`
} }
// Quotes stores relevant pointers as well as the array of stock quotes for // Quotes stores relevant pointers as well as the array of stock quotes for
@ -139,7 +141,7 @@ func (quotes *Quotes) parse2(body []byte) (*Quotes, error) {
} }
results := d["quoteResponse"]["result"] results := d["quoteResponse"]["result"]
quotes.stocks = make([]Stock, len(results)) quotes.stocks = make([]Stock, len(results))
for i, raw := range results { for i, raw := range results {
result := map[string]string{} result := map[string]string{}
for k, v := range raw { for k, v := range raw {
@ -152,7 +154,7 @@ func (quotes *Quotes) parse2(body []byte) (*Quotes, error) {
result[k] = fmt.Sprintf("%v", v) result[k] = fmt.Sprintf("%v", v)
} }
} }
quotes.stocks[i].Ticker = result["symbol"] quotes.stocks[i].Ticker = result["symbol"]
quotes.stocks[i].LastTrade = result["regularMarketPrice"] quotes.stocks[i].LastTrade = result["regularMarketPrice"]
quotes.stocks[i].Change = result["regularMarketChange"] quotes.stocks[i].Change = result["regularMarketChange"]
@ -173,8 +175,9 @@ func (quotes *Quotes) parse2(body []byte) (*Quotes, error) {
// TODO calculate rt? // TODO calculate rt?
quotes.stocks[i].MarketCapX = result["marketCap"] quotes.stocks[i].MarketCapX = result["marketCap"]
quotes.stocks[i].Currency = result["currency"] quotes.stocks[i].Currency = result["currency"]
quotes.stocks[i].PreOpen = result["preMarketChangePercent"]
/* quotes.stocks[i].AfterHours = result["postMarketChangePercent"]
/*
fmt.Println(i) fmt.Println(i)
fmt.Println("-------------------") fmt.Println("-------------------")
for k, v := range result { for k, v := range result {
@ -235,7 +238,7 @@ func sanitize(body []byte) []byte {
return bytes.Replace(bytes.TrimSpace(body), []byte{'"'}, []byte{}, -1) return bytes.Replace(bytes.TrimSpace(body), []byte{'"'}, []byte{}, -1)
} }
func float2Str(v float64) string { func float2Str(v float64) string {
unit := "" unit := ""
switch { switch {
case v > 1.0e12: case v > 1.0e12:
@ -256,4 +259,3 @@ func sanitize(body []byte) []byte {
// parse // parse
return fmt.Sprintf("%0.3f%s", v, unit) return fmt.Sprintf("%0.3f%s", v, unit)
} }

Loading…
Cancel
Save