-
Notifications
You must be signed in to change notification settings - Fork 14
/
money.go
865 lines (803 loc) · 22.7 KB
/
money.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
package money
/*
The package contains type Money...
type Money struct {
M int64
}
...which usese a fixed-length guard for precision arithmetic: the
int64 variable Guard (and its float64 and int-related variables Guardf
and Guardi.
ROunding is done on float64 to int64 by the Rnd() function truncating
at values less than (.5 + (1 / Guardf)) or greater than -(.5 + (1 / Guardf))
in the case of negative numbers. The Guard adds four decimal places
of protection to rounding.
DP is the decimal precision, which can be changed in the DecimalPrecision()
function. DP hold the places after the decimalplace in teh active money struct field M
The following functions are available
Abs Returns the absolute value of Money
(m *Money) Abs() *Money
Add Adds two Money types
(m *Money) Add(n *Money) *Money
Black-Scholes (European put and call options)
BS(s, k, t, r, v float64, putcall string) float64
CMP Compounded Interest Rate
CMP(fv, pv *Money, n float64) float64
CNI Continuous Interest
(pv *Money) CNI(r float64, n int) *Money
Cov Covariance
Cov(x, y []float64) float64
DecimalChange resets the package-wide decimal place (default is 2 decimal places)
DecimalChange(d int)
Div Divides one Money type from another
(m *Money) Div(n *Money) *Money
FVA Future Value of an Annuity
(m *Money) FVA(r float64, n int) *Money
Future Value of a growing Annuity
(pmt *Money) FVGA(r, g float64, n int) *Money
FV Future Value (compound interest)
(m *Money) FV(r float64, n int) *Money
FVi Future Value Simple Interest
(m *Money) FVi(r float64, n int) (m *Money)
Gett gets value of money truncating after DP (see Value() for no truncation)
(m *Money) Gett() int64
Get gets the float64 value of money (see Value() for int64)
(m *Money) Get() float64
GetQuote obtains a security quote
(q *Quote) GetQuote(t, e string) *Quote
Interest
(m *Money) Interest(r float64, n int) (m *Money)
I Interest (of 1 value returned) for n periods
I(r float64, n int) float64
Ifl Interest (float64 arguments)
Ifl(r, n float64) float64
Is Simple Interest (also see Compounded Interest Rate)
(m *Money) Is(pv *Money) *Money
Mean Average
Mean(a []float64) float64
MP Mortgage Payment
(m *Money) MP(r float64, n int) *Money
Mul Multiplies two Money types
(m *Money) Mul(n *Money) *Money
Mulf Multiplies a Money with a float to return a money-stored type
(m *Money) Mulf(f float64) *Money
Neg Returns the negative value of Money
(m *Money) Neg() *Money
Pow is the power of Money
(m *Money) Pow(r float64) *Money
Present Value of a Series of cash flows (using non integer time periods) general case
(m *Money) PV(fvs []Money, i []float64, ns []float64) *Money
PVA Present Value of an Annuity (ordinary)
(m *Money) PVA(r float64, n int) *Money
Present Value of an Annuity Due
(m *Money) PVAD(r float64, n int) *Money
PVf Present Value of a single future Value (using non integer period)
(m *Money) PVf(r, n float64) *Money
PVGA Present Value of a growing Annuity
(m *Money) PVGA(r, g float64, n int) *Money
PVGAD Present Value of a growing Annuity due (start of period)
(m *Money) PVGAD(r, g float64, n int) *Money
PVi Present Value of a single future Value (using integer period)
(m *Money) PVi(r float64, n int) *Money
PVP Present Value (of an integer period)
(m *Money) PVP(r float64, n, pd int) *Money
R Regression
R(x, y []float64) (a, b, r float64)
RND Rounds int64 remainder if greater than Round
Rnd(r int64, trunc float64) int64
SD Standard Deviation
SD(a []float64) float64
SDs Standard Deviation of a sample
SDs(a []float64) float64
Set sets the Money field M
(m *Money) Set(x int64) *Money
Setf sets a float 64 into a Money type for precision calculations
(m *Money) Setf(f float64) *Money
Sign returns the Sign of Money 1 if positive, -1 if negative
(m *Money) Sign() int
String for money type representation in basic monetary unit (DOLLARS CENTS)
(m *Money) String() string
Sub subtracts one Money type from another
(m *Money) Sub(n *Money) *Money
Value returns in int64 the value of Money (also see Gett, See Get() for float64)
(m *Money) Value() int64
*/
import (
"fmt"
"http"
"io/ioutil"
"math"
"strconv"
"time"
)
type Money struct {
M int64 // value of the integer64 Money
}
type Quote struct {
ID string
Ticker string
Exchange string
Price Money
PriceCur Money
S string
LTT time.Time // last trade
LT time.Time // last trade
Change Money
ChangePct float64
CCOL string
EL Money // after hours
ELCurrent Money // after hours price
ELT time.Time // after hours time
EC Money // after hours price change
ECP float64 // after hours percent change
ECCOL string // chb
Dividend Money
Yield float64
Other string // forecol
}
var qPos = map[string]int{"id": 0, // Quote position
"t": 1,
"e": 2,
"l": 3,
"l_cur": 4,
"s": 5,
"ltt": 6,
"lt": 7,
"c": 8,
"cp": 9,
"ccol": 10,
"el": 11,
"el_cur": 12,
"elt": 13,
"ec": 14,
"ecp": 15,
"eccol": 16,
"div": 17,
"yld": 18,
}
var (
Guardi int = 100
Guard int64 = int64(Guardi)
Guardf float64 = float64(Guardi)
DP int64 = 100 // for default of 2 decimal places => 10^2 (can be reset)
DPf float64 = float64(DP) // for default of 2 decimal places => 10^2 (can be reset)
Round = .5
// Round = .5 + (1 / Guardf)
Roundn = Round * -1
call string = "c"
put string = "p"
)
const (
DBZ = "Divide by zero"
DTL = "Decimal places too large"
DLZ = "Decimal places cannot be less than zero"
INF = "Calulcations results in infinity"
INFN = "Calulcations results in negative infinity"
NAN = "Not a Number"
NOOR = "Number out of range"
OVFL = "Overflow"
UND = "Undefined Number: non a number, or infinity"
STRCONE = "String Conversion error"
MAXDEC = 18
)
const ( // for GetQuote
DOUBLEQUOTE byte = 34
COLONBYTE byte = 58
COLON string = string(COLONBYTE)
QUOTEURL string = "http://finance.google.com/finance/info?client=ig&q="
QLTTTIME string = "3:04PM MST"
QLTTIME string = "Jan 02, 3:04PM MST"
UNABLE string = "Unable to convert "
BADQUOTE string = "Quote read is bad or invalid"
QUOTEFAIL string = "Bad read or quote not found for "
)
// Abs Returns the absolute value of Money
func (m *Money) Abs() *Money {
if m.M < 0 {
m.Neg()
}
return m
}
// Add Adds two Money types
func (m *Money) Add(n *Money) *Money {
r := m.M + n.M
if (r^m.M)&(r^n.M) < 0 {
panic(OVFL)
}
m.M = r
return m
}
// Black-Scholes (European put and call options)
// C Theoretical call premium (non-dividend paying stock)
// c = sn(d1) - ke^(-rt)N(d2)
// d1 = ln(s/k) + (r + s^2/2)t
// d2 = d1- st^1/2
// v = stock value
// k = Stock strike price
// s = Spot price
// t = time to expire in years
// r = risk free rate
// v = volitilaty (sigma)
// e math.E 2.7183
// putcall = "c" for a call or "p" for a put
func BS(s, k, t, r, v float64, putcall string) float64 {
d1 := (math.Log(s/k) + ((r + (math.Pow(v, 2) / 2)) * t)) / (v * math.Sqrt(t))
d2 := d1 - (v * math.Sqrt(t))
if putcall == call {
return math.Erf(d1)*s - (math.Erf(d2) * k * math.Pow(math.E, (-1*r*t)))
}
if putcall == put {
return k*math.Pow(math.E, (-1*r*t)) - s + ((math.Erf(-1*d2) * k * math.Pow(math.E, (-1*r*t))) - (math.Erf(-1*d1) * s))
}
panic(NOOR)
}
// CMP Compounded Interest Rate
// i = (fv / pv) ^ (1/n) - 1
// pv = present value
// fv = future value
// n - number of periods
// i = interest rate in percent per period
// returned as a decimal representation of the interest rate over the period
// can return NaN (Not a Number) on improbable input values (n = 0 pv = 0)
func CMP(fv, pv *Money, n float64) float64 {
return Ifl(float64(fv.Div(pv).Get()), 1/n) - 1
}
// CNI Continuous Interest
// fv = pv * e ^ (i * n)
// pv - principal or present value
// i - interest rate per period
// n - number of periods
// returned as a decimal representation of the interest rate over the period
func (pv *Money) CNI(r float64, n int) *Money {
return pv.Mulf(Ifl(math.E, (r * float64(n))))
}
// Cov Covariance
// Cov(x,y) = SIGMA(XY) - (SIGMA(X) * SIGMA(Y))
// SIGMA a total of all of the elements of a
// n is the number of x,y data points
func Cov(x, y []float64) float64 {
if len(x) == 0 {
panic(NOOR)
}
if len(x) != len(y) {
panic(NOOR)
}
xy := make([]float64, len(x))
for i, _ := range x {
xy[i] = x[i] * y[i]
}
xysl := xy[:]
return Mean(xysl) - (Mean(x) * Mean(y))
}
// DecimalChange resets the package-wide decimal place (default is 2 decimal places)
func DecimalChange(d int) {
if d < 0 {
panic(DLZ)
}
if d > MAXDEC {
panic(DTL)
}
var newDecimal int
if d > 0 {
newDecimal++
for i := 0; i < d; i++ {
newDecimal *= 10
}
}
DPf = float64(newDecimal)
DP = int64(newDecimal)
return
}
// Div Divides one Money type from another
func (m *Money) Div(n *Money) *Money {
f := Guardf * DPf * float64(m.M) / float64(n.M) / Guardf
i := int64(f)
return m.Set(Rnd(i, f-float64(i)))
}
// FVA Future Value of an Annuity
// fv = pmt * ( ( 1 + n )^n - 1 ) / r
// fv = future value
// pmt (m) = payment per period
// r = interest rate in percent per period
// n = number of periods
// can return NaN (Not a Number) on improbable input values
func (m *Money) FVA(r float64, n int) *Money {
return m.Mulf((I(r, n) - 1) / r)
}
// FVGA Future Value of a growing Annuity
// fv = pmt * ( (1+i)^n - (1+r)^n ) / (i - r)
// when i = r, fv = pmt * n * ((1+i)^(n-1))
// pmt (m) = amount of each payment
// fv = Future Value
// r = interest rate in decimal percent
// g rate of growth in decimal percent
// n = periods
func (m *Money) FVGA(r, g float64, n int) *Money {
if r == g {
return m.Mulf(float64(n) * I(r, n-1))
}
return m.Mulf(I(r, n) - I(g, n)/(r-g))
}
// FV Future Value (compound interest)
// fv (m) = pv * ( 1 + i )^n
// pv = present value
// fv = future value (the maturity value)
// i = interest rate in percent per period
// n = number of periods
func (m *Money) FV(r float64, n int) *Money {
return m.Mulf(I(r, n))
}
// FVi Future Value Simple Interest
// fv = pv * (1 + ( i * n ) )
// fv - future value (maturity value)
// pv (m) - principal or present value
// i - interest rate per period
// n - number of periods
func (m *Money) FVi(r float64, n int) *Money {
return m.Mulf(1 + r*float64(n))
}
// Gett gets value of money truncating after DP (see Value() for no truncation)
func (m *Money) Gett() int64 {
return m.M / DP
}
// Get gets the float64 value of money (see Value() for int64)
func (m *Money) Get() float64 {
return float64(m.M) / DPf
}
// GetQuote obtains a security quote of type Quote
// q = Quote
// t = the string ticker ex. "GOOG" "VTI"
// e = the string exchange ex. "NASDAQ" "NYSE"
func (q *Quote) GetQuote(t, e string) *Quote {
return q.parseQuote(getQuotePage(e, t))
}
// Interest
// I = pv * i * n
// pv (m) - principal or present value
// i - interest rate per period
// n - number of periods
// returned into a money type as an int64-decimal representation of the interest rate over the period
func (m *Money) Interest(r float64, n int) *Money {
return m.Mulf(I(r, n))
}
// I Interest (of 1 value returned) for n periods
// i - interest rate per period
// n - number of periods
// returned as a decimal representation of the interest rate over the period
func I(r float64, n int) float64 {
return math.Pow((1 + r), float64(n))
}
// Ifl Interest (float64 arguments)
// r PLUS - interest rate per period - use (1 + r), E for ln etc.
// n - number of periods
// returned as a decimal representation of the interest rate over the period
func Ifl(r, n float64) float64 {
return math.Pow(r, n)
}
// Is Simple Interest (also see Compounded Interest Rate)
// i = fv - pv
// pv = present value in Money
// m = future value (maturity value) in Money
// i = interest rate in percent per period returned as Money
// returned as a decimal representation of the interest rate over the period
func (m *Money) Is(pv *Money) *Money {
n := new(Money)
return m.Sub(pv).Div(n.Set(100))
}
// Mean Average
// mean = SIGMA a / len(a)
// SIGMA a total of all of the elements of a
// len(a) = the number of values
func Mean(a []float64) float64 {
lenA := float64(len(a))
if lenA == 0 {
panic(NOOR)
}
var sum float64
for _, v := range a {
sum += v
}
return sum / lenA
}
// MP Mortgage Payment
// pmt = loan * r * (1 + r)^n / ((1 + r)^n - 1)
// loan - loan amount
// i - note percent interest rate (not monthly rate)
// n - number of periods (ex 360 for a 30 year loan)
// returned as Money
func (m *Money) MP(r float64, n int) *Money {
return m.Setf(m.Get() * r * I(r/12, n) / (I(r/12, n) - 1))
}
// Mul Multiplies two Money types
func (m *Money) Mul(n *Money) *Money {
return m.Set(m.M * n.M / DP)
}
// Mulf Multiplies a Money with a float to return a money-stored type
func (m *Money) Mulf(f float64) *Money {
i := m.M * int64(f*Guardf*DPf)
r := i/Guard/DP
return m.Set(Rnd(r,float64(i) / Guardf / DPf - float64(r)))
}
// Neg Returns the negative value of Money
func (m *Money) Neg() *Money {
if m.M != 0 {
m.M *= -1
}
return m
}
// Pow is the power of Money
func (m *Money) Pow(r float64) *Money {
return m.Setf(math.Pow(m.Get(), r))
}
// Present Value of a Series of cash flows (using non integer time periods) general case
// pv = SIGMA (n, t=0) [fv-sub(t) / ((1 + i) ^ n-sub(t))]
// pv = present value of Money
// SIGMA (n, t=0) Sum of n's beginning at time t = 0
// fv = future value in the array slice element of fvs
// fv-sub(t) Future Value at time t (subscript t)
// n-sub(t) period at array slice position t
// i = interest rate in percent per period
// n = period in array slice ns
// fvs and ns must correspond, be the same len()
// does not work for for example fvs[j] < -100% and ns[j] = 0.5
func (m *Money) PV(fvs []Money, i []float64, ns []float64) *Money {
m.Set(0)
for j, _ := range fvs {
m.Add(fvs[j].PVf(i[j], ns[j]))
}
return m
}
// PVA Present Value of an Annuity (ordinary)
// pv = pmt * (1 - ( 1 / ((1+i)^n)) / i)
// m = amount of each payment and solution returned
// n = periods
// r = interest rate in decimal percent
func (m *Money) PVA(r float64, n int) *Money {
return m.Mulf((1 - (1 / I(r, n))) / r)
}
// Present Value of an Annuity Due
// pv = pmt * (1 - ( 1 / ((1+i)^n)) / i) * (i+1)
// pmt = amount of each payment
// n = periods
// r = interest rate in decimal percent
func (m *Money) PVAD(r float64, n int) *Money {
return m.Mulf(((1 - (1 / I(r, n))) / r) * (r + 1))
}
// PVf Present Value of a single future Value (using non integer period)
// pv = fv * ( 1 / ( 1 + r )^n)
// pv = present value
// fv = future value
// r = interest rate in percent for period
// n = period
// can panic on improbable input values if > -100% r or 1/2 period.
// called by finance.PV
func (m *Money) PVf(r, n float64) *Money {
return m.Mulf(1 / Ifl(1+r, n))
}
// PVGA Present Value of a growing Annuity
// pv = pmt * (1 - ( (1+g) / ((1+r)^n)) / (r-g))
// pv = present value (returned as m)
// m = payment per period
// r = interest rate in percent per period
// n = number of periods
// g = rate of growth
func (m *Money) PVGA(r, g float64, n int) *Money {
return m.Mulf(((1 - ((1 + g) / I(r, n))) / (r - g)))
}
// PVGAD Present Value of a growing Annuity due (start of period)
// pv = pmt * (1 - ( (1+g) / ((1+r)^n)) / (r-g)) * (1+r)
// pv = present value
// pmt = payment per period
// r = interest rate in percent per period
// n = number of periods
// g rate of growth
func (m *Money) PVGAD(r, g float64, n int) *Money {
return m.Mulf(((1 - ((1 + g) / I(r, n))) / (r - g)) * (1 + r))
}
// PVi Present Value of a single future Value (using integer period)
// pv = fv * ( 1 / ( 1 + r )^n)
// pv = present value
// fv = future value
// r = interest rate
// n = period
func (m *Money) PVi(r float64, n int) *Money {
return m.Mulf(1 / I(r, n))
}
// PVP Present Value (of an integer period)
// pv = fv * ( 1 / ( 1 + i )^n)
// pv = present value
// fv = future value
// r = interest rate in percent per period
// n = number of periods
func (m *Money) PVP(r float64, n, pd int) *Money {
return m.Mulf(1 / Ifl((1+(r/float64(pd))), float64(n*pd)))
}
// R Regression
// slope(b) = (n * SIGMAXY - (SIGMA X)(SIGMA Y))) / (n * SIGMAX^2) - (SIGMAX)^2)
// Intercept(a) = (SIGMA Y - b(SIGMA X)) / n
// r-squared = (Cov(x,y) / SD(x) * SD(y))^2
// r-squared = s1 / (p1' * q1')
// s1 = n('XY) - ('X)('Y)
// p1 = (n('X2) -- ('X)2)^1/2
// q1 = (n('X2) -- ('X)2)^1/2
func R(x, y []float64) (a, b, r float64) {
n := float64(len(x))
var (
sumX, sumY, sumXY, sumXsq, sumYsq float64
)
for _, v := range x {
sumX += v
}
for _, v := range y {
sumY += v
}
for i, v := range x {
sumXY += v * y[i]
}
for _, v := range x {
sumXsq += math.Pow(v, 2)
}
b = ((n * sumXY) - (sumX * sumY)) / ((n * sumXsq) - math.Pow(sumX, 2))
a = (sumY - (b * sumX)) / n
s1 := (n * sumXY) - (sumX * sumY)
p1 := n*sumXsq - math.Pow(sumX, 2)
p1sqrt := math.Sqrt(p1)
for _, v := range y {
sumYsq += math.Pow(v, 2)
}
q1 := n*sumYsq - math.Pow(sumY, 2)
q1sqrt := math.Sqrt(q1)
r = s1 / (p1sqrt * q1sqrt)
return a, b, r
}
// RND rounds int64 remainder rounded half towards plus infinity
// trunc = the remainder of the float64 calc
// r = the result of the int64 cal
func Rnd(r int64, trunc float64) int64 {
//fmt.Printf("RND 1 r = % v, trunc = %v Round = %v\n", r, trunc, Round)
if trunc > 0 {
if trunc >= Round {
r++
}
} else {
if trunc < Roundn {
r--
}
}
//fmt.Printf("RND 2 r = % v, trunc = %v Round = %v\n", r, trunc, Round)
return r
}
// SD Standard Deviation
// sd = sqrt(SIGMA ((a[i] - mean) ^ 2) / len(a))
// SIGMA a total of all of the elements of a
// a[i] is the ith elemant of a
// len(a) = the number of elements in the slice a
func SD(a []float64) float64 {
var sum float64
m := Mean(a)
for _, v := range a {
sum += math.Pow(v-m, 2)
}
return math.Sqrt(sum / float64(len(a)))
}
// SDs Standard Deviation of a sample
// sd = sqrt(SIGMA ((a[i] - mean) ^ 2) / (len(a)-1))
// SIGMA a total of all of the elements of a
// a[i] is the ith elemant of a
// len(a) = the number of elements in the slice a adjusted for sample
func SDs(a []float64) float64 {
var sum float64
m := Mean(a)
for _, v := range a {
sum += math.Pow(v-m, 2)
}
return math.Sqrt(sum / float64(len(a)-1))
}
// Set sets the Money field M
func (m *Money) Set(x int64) *Money {
m.M = x
return m
}
// Setf sets a float64 into a Money type for precision calculations
func (m *Money) Setf(f float64) *Money {
fDPf := f * DPf
r := int64(f*DPf)
return m.Set(Rnd(r, fDPf-float64(r)))
}
// Sign returns the Sign of Money 1 if positive, -1 if negative
func (m *Money) Sign() int {
if m.M < 0 {
return -1
}
return 1
}
// String for money type representation in basic monetary unit (DOLLARS CENTS)
func (m *Money) String() string {
return fmt.Sprintf("%d.%02d", m.Value()/DP, m.Abs().Value()%DP)
}
// Sub subtracts one Money type from another
func (m *Money) Sub(n *Money) *Money {
r := m.M - n.M
if (r^m.M)&^(r^n.M) < 0 {
panic(OVFL)
}
m.M = r
return m
}
// Value returns in int64 the value of Money (also see Gett(), See Get() for float64)
func (m *Money) Value() int64 {
return m.M
}
// worker funcs for GetQuote
func now() (t time.Time) {
lt := time.LocalTime()
t.Year = lt.Year
t.Month = lt.Month
t.Weekday = lt.Weekday
t.Day = lt.Day
return t
}
func (q *Quote) quoteFields(bKey, bVal []byte) *Quote {
if bVal == nil {
return q
}
bStr := string(bKey)
for fld, v := range qPos {
if bStr == fld {
switch v {
case 0:
q.ID = string(bVal)
case 1:
q.Ticker = string(bVal)
case 2:
q.Exchange = string(bVal)
case 3:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.Price.Setf(f)
case 4:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.PriceCur.Setf(f)
case 5:
q.S = string(bVal)
case 6:
t, err := time.Parse(QLTTTIME, string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.LTT = now()
q.LTT.Hour = t.Hour
q.LTT.Minute = t.Minute
q.LTT.Zone = t.Zone
case 7:
t, err := time.Parse(QLTTIME, string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.LT = now()
q.LT.Month = t.Month
q.LT.Day = t.Day
q.LT.Hour = t.Hour
q.LT.Minute = t.Minute
q.LT.Zone = t.Zone
case 8:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.Change.Setf(f)
case 9:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.ChangePct = f
case 10:
q.CCOL = string(bVal)
case 11:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.EL.Setf(f)
case 12:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.ELCurrent.Setf(f)
case 13:
t, err := time.Parse(QLTTIME, string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.ELT = now()
q.ELT.Month = t.Month
q.ELT.Day = t.Day
q.ELT.Hour = t.Hour
q.ELT.Minute = t.Minute
q.ELT.Zone = t.Zone
case 14:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.EC.Setf(f)
case 15:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + string(bVal))
}
q.ECP = f
case 16:
q.ECCOL = string(bVal)
case 17:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + err.String() + " " + string(bVal))
}
q.Dividend.Setf(f)
case 18:
f, err := strconv.Atof64(string(bVal))
if err != nil {
panic(UNABLE + fld + " " + err.String() + " " + string(bVal))
}
q.Yield = f
}
return q
}
}
panic("no valid symbol loaded list for " + bStr)
}
func (s *Quote) parseQuote(b []byte) *Quote {
var bKey, bVal []byte
var pos int
for pos < len(b) {
if b[pos] == DOUBLEQUOTE {
if bKey == nil {
pos++
if pos == len(b) {
panic(BADQUOTE)
}
for b[pos] != DOUBLEQUOTE {
bKey = append(bKey, b[pos])
pos++
if pos == len(b) {
panic(BADQUOTE)
}
}
} else if bVal == nil {
pos++
if pos == len(b) {
panic(BADQUOTE)
}
for b[pos] != DOUBLEQUOTE {
bVal = append(bVal, b[pos])
pos++
if pos == len(b) {
panic(BADQUOTE)
}
}
s.quoteFields(bKey, bVal)
bKey, bVal = nil, nil
}
}
pos++
}
return s
}
func getQuotePage(t, e string) []byte {
var b []byte
// r, _, err := http.Get(QUOTEURL + e + COLON + t) // http.Get with re-direct
r, err := http.Get(QUOTEURL + e + COLON + t)
if err != nil {
panic(QUOTEFAIL + e + " " + t)
}
defer r.Body.Close()
b, _ = ioutil.ReadAll(r.Body)
return b
}