forked from mop-tracker/mop
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathlayout.go
368 lines (334 loc) · 12 KB
/
layout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright (c) 2013-2021 by Michael Dvorkin, Brandon Lee Camilleri and contributors. All Rights Reserved. Use of this source code is governed by a MIT-style license that can be found in README.md.
package TerminalStocks
import (
"bytes"
"fmt"
"reflect"
"regexp"
"strings"
"text/template"
"unicode"
)
var currencies = map[string]string{
// https://www.xe.com/symbols.php
// https://github.com/mop-tracker/mop/commit/fa17d92b454981aca8e1dcf1aa1b748798070eff
"AFN": "؋", // Afghanistan Afghani
"ALL": "Lek", // Albania Lek
"ANG": "ƒ", // Netherlands Antilles Guilder
"ARS": "$", // Argentina Peso
"AUD": "$", // Australia Dollar
"AWG": "ƒ", // Aruba Guilder
"AZN": "₼", // Azerbaijan Manat
"BAM": "KM", // Bosnia and Herzegovina Convertible Mark
"BBD": "$", // Barbados Dollar
"BGN": "лв", // Bulgaria Lev
"BMD": "$", // Bermuda Dollar
"BND": "$", // Brunei Darussalam Dollar
"BOB": "$b", // Bolivia Bolíviano
"BRL": "R$", // Brazil Real
"BSD": "$", // Bahamas Dollar
"BWP": "P", // Botswana Pula
"BYN": "Br", // Belarus Ruble
"BZD": "BZ$", // Belize Dollar
"CAD": "$", // Canada Dollar
"CHF": "CHF", // Switzerland Franc
"CLP": "$", // Chile Peso
"CNY": "¥", // China Yuan Renminbi
"COP": "$", // Colombia Peso
"CRC": "₡", // Costa Rica Colon
"CUP": "₱", // Cuba Peso
"CZK": "Kč", // Czech Republic Koruna
"DKK": "kr", // Denmark Krone
"DOP": "RD$", // Dominican Republic Peso
"EGP": "£", // Egypt Pound
"EUR": "€", // Euro Member Countries
"FKP": "£", // Falkland Islands (Malvinas) Pound
"FJD": "$", // Fiji Dollar
"GBP": "£", // United Kingdom Pound aka Great Britain Pound
"GBp": "p", // United Kingdom Pound aka Great Britain pence
"GHS": "¢", // Ghana Cedi
"GIP": "£", // Gibraltar Pound
"GTQ": "Q", // Guatemala Quetzal
"GGP": "£", // Guernsey Pound
"GYD": "$", // Guyana Dollar
"HKD": "HK$", // Hong Kong Dollar
"HNL": "L", // Honduras Lempira
"HRK": "kn", // Croatia Kuna
"HUF": "Ft", // Hungary Forint
"IDR": "Rp", // Indonesia Rupiah
"ILS": "₪", // Israel Shekel
"IMP": "£", // Isle of Man Pound
"IRR": "﷼", // Iran Rial
"ISK": "kr", // Iceland Krona
"JEP": "£", // Jersey Pound
"JMD": "J$", // Jamaica Dollar
"JPY": "¥", // Japan Yen
"KGS": "лв", // Kyrgyzstan Som
"KHR": "៛", // Cambodia Riel
"KPW": "₩", // Korea (North) Won
"KRW": "₩", // Korea (South) Won
"KYD": "$", // Cayman Islands Dollar
"KZT": "лв", // Kazakhstan Tenge
"LAK": "₭", // Laos Kip
"LBP": "£", // Lebanon Pound
"LKR": "₨", // Sri Lanka Rupee
"LRD": "$", // Liberia Dollar
"MKD": "ден", // Macedonia Denar
"MNT": "₮", // Mongolia Tughrik
"MUR": "₨", // Mauritius Rupee
"MXN": "$", // Mexico Peso
"MYR": "RM", // Malaysia Ringgit
"MZN": "MT", // Mozambique Metical
"NAD": "$", // Namibia Dollar
"NPR": "₨", // Nepal Rupee
"NGN": "₦", // Nigeria Naira
"NIO": "C$", // Nicaragua Cordoba
"NOK": "kr", // Norway Krone
"NZD": "$", // New Zealand Dollar
"OMR": "﷼", // Oman Rial
"PKR": "₨", // Pakistan Rupee
"PAB": "B/.", // Panama Balboa
"PYG": "Gs", // Paraguay Guarani
"PEN": "S/.", // Peru Sol
"PHP": "₱", // Philippines Peso
"PLN": "zł", // Poland Zloty
"QAR": "﷼", // Qatar Riyal
"RSD": "Дин.", // Serbia Dinar
"RON": "lei", // Romania Leu
"RUB": "₽", // Russia Ruble
"SAR": "﷼", // Saudi Arabia Riyal
"SBD": "$", // Solomon Islands Dollar
"SCR": "₨", // Seychelles Rupee
"SEK": "kr", // Sweden Krona
"SGD": "$", // Singapore Dollar
"SHP": "£", // Saint Helena Pound
"SOS": "S", // Somalia Shilling
"SRD": "$", // Suriname Dollar
"SVC": "$", // El Salvador Colon
"SYP": "£", // Syria Pound
"THB": "฿", // Thailand Baht
"TTD": "TT$", // Trinidad and Tobago Dollar
"TVD": "$", // Tuvalu Dollar
"TWD": "NT$", // Taiwan New Dollar
"UAH": "₴", // Ukraine Hryvnia
"USD": "$", // United States Dollar
"UYU": "$U", // Uruguay Peso
"UZS": "лв", // Uzbekistan Som
"VEF": "Bs", // Venezuela Bolívar
"VND": "₫", // Viet Nam Dong
"XCD": "$", // East Caribbean Dollar
"YER": "﷼", // Yemen Rial
"ZAR": "R", // South Africa Rand
"ZWD": "Z$", // Zimbabwe Dollar
}
// Column describes formatting rules for individual column within the list of stock quotes.
type Column struct {
width int // Column width.
name string // The name of the field in the Stock struct.
title string // Column title to display in the header.
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 updates and the list of stock quotes.
type Layout struct {
columns []Column // List of stock quotes columns.
regex *regexp.Regexp // Pointer to regular expression to align decimal points.
quotesTemplate *template.Template // Pointer to template to format the list of stock quotes.
}
// Creates the layout and assigns the default values that stay unchanged.
func NewLayout() *Layout {
layout := &Layout{}
layout.columns = []Column{
{-8, `Ticker`, `Ticker`, nil}, // Default -19 for longest tickers
{10, `LastTrade`, `Last`, currency},
{10, `Change`, `Chnge`, currency}, // Change
{8, `ChangePct`, `Chnge%`, last}, // Percantage Change
{10, `Open`, `Open`, currency},
{10, `Low`, `Low`, currency},
{10, `High`, `High`, currency},
{10, `Low52`, `52wLow`, currency}, // 52-week low
{10, `High52`, `52wHigh`, currency}, // 52-week high
{8, `Volume`, `Vol`, integer}, // Volume
{8, `AvgVolume`, `AvgVol`, integer}, // Average Volume
{7, `PeRatio`, `P/E`, blank},
{9, `Dividend`, `Dvdnd`, zero}, // Dividend
{7, `Yield`, `Yld`, percent}, // Yield
{10, `MarketCap`, `MktCap`, currency},
{10, `PreOpen`, `PreMkt`, currency}, // Pre Market price
{11, `PreOpenPct`, `PreMktChg%`, percent}, // Pre Market percentage change
{10, `AfterHours`, `AftrMkt`, currency}, // After Market price
{12, `AfterHoursPct`, `AftrMktChg%`, percent}, // After Market percentage change
}
layout.regex = regexp.MustCompile(`(\.\d+)[TBMK]?$`)
layout.quotesTemplate = buildQuotesTemplate()
return layout
}
// Quotes uses quotes template to format stock quotes header, and the list of given stock quotes.
// It returns formatted string with all the necessary markup.
func (layout *Layout) Quotes(quotes *Quotes) string {
vars := struct {
Header string // Formatted header line.
Stocks []Stock // List of formatted stock quotes.
}{
layout.Header(quotes.profile),
layout.prettify(quotes),
}
buffer := new(bytes.Buffer)
layout.quotesTemplate.Execute(buffer, vars)
return buffer.String()
}
// Header iterates over column titles and formats the header line.
// When the column editor is active it knows how to highlight currently selected column title.
func (layout *Layout) Header(profile *Profile) string {
str, selectedColumn := ``, profile.selectedColumn
for i, col := range layout.columns {
if i != selectedColumn {
str += fmt.Sprintf(`%*s`, col.width, col.title)
} else {
str += fmt.Sprintf(`<r>%*s</r>`, col.width, col.title)
}
}
return `<u>` + str + `</u>`
}
// TotalColumns is the utility method for the column editor that returns total number of columns.
func (layout *Layout) TotalColumns() int {
return len(layout.columns)
}
//-----------------------------------------------------------------------------
func (layout *Layout) prettify(quotes *Quotes) []Stock {
pretty := make([]Stock, len(quotes.stocks))
//
// Iterate over the list of stocks and properly format all its columns.
//
for i, stock := range quotes.stocks {
pretty[i].Advancing = stock.Advancing
//
// Iterate over the list of stock columns. For each column name:
// - Get current column value.
// - If the column has the formatter method then call it.
// - Set the column value padding it to the given width.
//
for _, column := range layout.columns {
// ex. value = stock.Change
value := reflect.ValueOf(&stock).Elem().FieldByName(column.name).String()
if column.formatter != nil {
// ex. value = currency(value)
value = column.formatter(value, stock.Currency)
}
// ex. pretty[i].Change = layout.pad(value, 10)
reflect.ValueOf(&pretty[i]).Elem().FieldByName(column.name).SetString(layout.pad(value, column.width))
}
}
return pretty
}
//-----------------------------------------------------------------------------
func (layout *Layout) pad(str string, width int) string {
match := layout.regex.FindStringSubmatch(str)
if len(match) > 0 {
switch len(match[1]) {
case 2:
str = strings.Replace(str, match[1], match[1]+`0`, 1)
case 4, 5:
str = strings.Replace(str, match[1], match[1][0:3], 1)
}
}
return fmt.Sprintf(`%*s`, width, str)
}
//-----------------------------------------------------------------------------
func buildQuotesTemplate() *template.Template {
markup := `{{.Header}}
{{range.Stocks}}{{if .Advancing}}<green>{{end}}{{.Ticker}}{{.LastTrade}}{{.Change}}{{.ChangePct}}{{.Open}}{{.Low}}{{.High}}{{.Low52}}{{.High52}}{{.Volume}}{{.AvgVolume}}{{.PeRatio}}{{.Dividend}}{{.Yield}}{{.MarketCap}}{{.PreOpen}}{{.PreOpenPct}}{{.AfterHours}}{{.AfterHoursPct}}</>
{{end}}`
return template.Must(template.New(`quotes`).Parse(markup))
}
// Negative coloured red:
// {{range.Stocks}}{{if .Advancing}}<green>{{else}}<red>{{end}}{{.Ticker}}{{.LastTrade}}{{.Change}}{{.ChangePct}}{{.Open}}{{.Low}}{{.High}}{{.Low52}}{{.High52}}{{.Volume}}{{.AvgVolume}}{{.PeRatio}}{{.Dividend}}{{.Yield}}{{.MarketCap}}{{.PreOpen}}{{.PreOpenPct}}{{.AfterHours}}{{.AfterHoursPct}}</>
//-----------------------------------------------------------------------------
func blank(str ...string) string {
if len(str) < 1 {
return "ERR"
}
if (len(str[0]) == 3 && str[0][0:3] == `N/A`) || len(str[0]) == 0 { // https://github.com/robertalv/mop/commit/2d5ef2317b004d86074fca0d898489cb35265e35
return `-`
}
return str[0]
}
//-----------------------------------------------------------------------------
func zero(str ...string) string {
if len(str) < 2 {
return "ERR"
}
if str[0] == `0.00` {
return `-`
}
return currency(str[0], str[1])
}
//-----------------------------------------------------------------------------
func last(str ...string) string {
if len(str) < 1 {
return "ERR"
}
if len(str[0]) >= 6 && str[0][0:6] == `N/A - ` {
return str[0][6:]
}
return percent(str[0])
}
//-----------------------------------------------------------------------------
func currency(str ...string) string {
if len(str) < 2 {
return "ERR"
}
//defaults to $
symbol := "$"
c, ok := currencies[str[1]]
if ok {
symbol = c
}
if str[0] == `N/A` || len(str[0]) == 0 {
return `-`
}
if sign := str[0][0:1]; sign == `+` || sign == `-` {
return sign + symbol + str[0][1:]
}
return symbol + str[0]
}
//-----------------------------------------------------------------------------
// Returns percent value truncated at 2 decimal points.
func percent(str ...string) string {
if len(str) < 1 {
return "ERR"
}
if str[0] == `N/A` || len(str[0]) == 0 {
return `-`
}
split := strings.Split(str[0], ".")
if len(split) == 2 {
digits := len(split[1])
if digits > 2 {
digits = 2
}
str[0] = split[0] + "." + split[1][0:digits]
}
if str[0][len(str)-1] != '%' {
str[0] += `%`
}
return str[0]
}
//-----------------------------------------------------------------------------
// Returns value as integer (no trailing digits after a '.').
// Added from here: https://github.com/robertalv/mop/commit/2d5ef2317b004d86074fca0d898489cb35265e35
func integer(str ...string) string {
if len(str) < 1 {
return "ERR"
}
if str[0] == `N/A` || len(str[0]) == 0 {
return `-`
}
// Don't strip after the '.' if we have a value such as 123.45M
if unicode.IsDigit(rune(str[0][len(str[0])-1])) {
split := strings.Split(str[0], ".")
if len(split) == 2 {
return split[0]
}
}
return str[0]
}