-
Notifications
You must be signed in to change notification settings - Fork 1
/
bitPredict.py
1642 lines (1483 loc) · 56 KB
/
bitPredict.py
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import urllib
import contextlib # for urllib.urlopen
import copy
import os
import tkMessageBox
import tkSimpleDialog
from datetime import datetime
from datetime import date
from Tkinter import *
import time
import webbrowser
from eventBasedAnimationClass import EventBasedAnimationClass
class Matrix(object):
def __init__(self, rows, cols, A):
self.rows = rows
self.cols = cols
self.entries = [[0 for j in xrange(cols)] for i in xrange(rows)]
for i in xrange(rows):
for j in xrange(cols):
self.entries[i][j] = A[i][j]
self.D = None
self.T = None
def __mul__(self, other):
if type(other) == Matrix:
return self.matrixMatrixMultiplication(other)
elif type(other) == Vector:
return self.matrixVectorMultiplication(other)
elif type(other) == int or type(other) == float:
return self.matrixScalarMultiplication(other)
def matrixMatrixMultiplication(self, other):
if other.rows == self.cols:
multiplied = ([[0 for i in xrange(self.rows)]
for j in xrange(other.cols)])
for row in xrange(self.rows):
vec1 = Vector(self.cols, self.entries[row])
for col in xrange(other.cols):
vec2entries = ([other.entries[r][col]
for r in xrange(other.rows)])
vec2 = Vector(other.rows, vec2entries)
multiplied[row][col] = vec1 * vec2
return Matrix(self.rows, other.cols, multiplied)
else:
raise Exception("Cannot be multiplied")
def matrixVectorMultiplication(self, other):
if other.dimension == self.cols:
multiplied = [0 for i in xrange(self.rows)]
for row in xrange(self.rows):
vec1 = Vector(self.cols, self.entries[row])
vec2 = other
multiplied[row] = vec1 * vec2
return Vector(self.rows, multiplied)
else:
raise Exception("Cannot be multiplied")
def matrixScalarMultiplication(self, other):
multiplied = copy.deepcopy(self.entries)
for row in xrange(self.rows):
for col in xrange(self.cols):
multiplied[row][col] *= other
return Matrix(self.rows, self.cols, multiplied)
def __rmul__(self, other):
return self * other
def __div__(self, other):
newMatrix = Matrix(self.rows, self.cols, self.entries)
if isinstance(other, int) or isinstance(other, float):
for row in xrange(self.rows):
for col in xrange(self.cols):
newMatrix.entries[row][col] = (float(
newMatrix.entries[row][col])/other)
return newMatrix
def determinant(self):
if self.rows == self.cols:
n, self.D = self.rows, 0
if n == 1:
return self.entries[0][0]
else:
for i in xrange(self.cols):
self.D += (self.entries[0][i] * self.cofactor(0, i))
return self.D
def inverse(self):
if self.D == 0:
raise Exception("Inverse doesn't exist")
else:
return self.adjoint()/self.determinant()
def cofactor(self, a, b):
assert (self.rows == self.cols)
n = self.rows
residualMatrix = [[0 for j in xrange(n-1)] for i in xrange(n-1)]
crow = 0
for i in xrange(n):
if i != a:
ccol = 0
for j in xrange(n):
if j != b:
residualMatrix[crow][ccol] = self.entries[i][j]
ccol += 1
crow += 1
return ((-1)**(a+b)) * (Matrix(self.rows - 1, self.cols - 1,
residualMatrix)).determinant()
def cofactorMatrix(self):
assert self.rows == self.cols
n = self.rows
cofMatrix = [[0 for j in xrange(n)] for i in xrange(n)]
for i in xrange(n):
for j in xrange(n):
cofMatrix[i][j] = self.cofactor(i, j)
return Matrix(n, n, cofMatrix)
def adjoint(self):
assert self.rows == self.cols
n = self.rows
return self.cofactorMatrix().transpose()
def transpose(self):
B = [[0 for col in xrange(self.rows)] for row in xrange(self.cols)]
for row in xrange(self.rows):
for col in xrange(self.cols):
B[col][row] = self.entries[row][col]
self.T = Matrix(self.cols, self.rows, B)
return self.T
def append(self, n):
# appends a column of n's to the right of matrix
newMatrix = ([[0 for i in xrange(self.cols + 1)]
for j in xrange(self.rows)])
for row in xrange(self.rows):
for col in xrange(self.cols):
newMatrix[row][col] = self.entries[row][col]
newMatrix[row][self.cols] = n
return Matrix(self.rows, self.cols+1, newMatrix)
class Vector(Matrix):
def __init__(self, dimension, b):
self.dimension = dimension
self.entries = b
def __mul__(self, other):
if type(other) == Vector:
product = 0
assert self.dimension == other.dimension
for i in xrange(self.dimension):
product += self.entries[i] * other.entries[i]
return product
elif type(other) == Matrix:
return other * self
def leastSquares(A, b):
# matrix A, vector b. returns vector with slope and intercept
return (A.transpose() * A).inverse() * (A.transpose() * b)
# CITATION: function rgbString taken from Course notes
def rgbString(red, green, blue):
return "#%02x%02x%02x" % (red, green, blue)
# CITATION: function readWebPage taken from Course notes
def readWebPage(url):
# reads from url and returns it
assert(url.startswith("https://"))
with contextlib.closing(urllib.urlopen(url)) as fin:
return fin.read()
def writeFile(filename, contents, mode = "a"):
# writes contents to filename
fout = open(filename, mode)
if type(contents) == list:
for i in xrange(len(contents)):
fout.write(str(contents[i]))
else: fout.write(str(contents))
fout.close()
def makeFileIntoArray(filename):
with open(filename, "rt") as fin:
contents = fin.read()
contents = contents.split("\n")
return contents
def getSpotRate():
# returns the spot rate at that moment. returns a STRING
url = "https://api.coinbase.com/v1/prices/spot_rate"
priceAndCurrency = readWebPage(url)
priceAndCurrency = priceAndCurrency.split("\"")
priceIndex = 3
price = priceAndCurrency[priceIndex]
return price
class Application(EventBasedAnimationClass):
def __init__(self):
self.width, self.height = 1200, 600
self.spotRate, self.timerCount = 0, 0
self.lastEntry = 0.0
super(Application, self).__init__(self.width, self.height)
def change(self, activePage):
self.activePage = activePage(self.change)
def initAnimation(self):
self.timerDelay = 1000
self.activePage = HomePage(self.change)
self.root.bind("<Motion>", lambda event: self.onMouseMotion(event))
def onTimerFired(self):
self.timerCount += 1
self.spotRate = getSpotRate()
if self.activePage.data:
self.callCreateDataFile()
if self.activePage.chartIntermediate:
self.changeToChartPage()
if self.timerCount >= 120:
# two minutes up, look for new data
self.newEntry = self.activePage.getNewEntry()
if (self.activePage == PredictPage and self.activePage.frozen and
self.activePage.promptToBuy and self.newEntry > self.lastEntry):
self.displayDialog("BUY NOW!")
# was frozen and it's time to BUY NOW!
elif (self.activePage == PredictPage and self.activePage.frozen and
self.activePage.promptToSell and self.newEntry<self.lastEntry):
self.displayDialog("SELL NOW!")
# was frozen and it's time to SELL NOW!
self.lastEntry = self.newEntry
self.timerCount = 0
self.redrawAll()
def callCreateDataFile(self):
self.redrawAll()
self.activePage.data = False
self.activePage.createDataFile()
def changeToChartPage(self):
self.redrawAll()
self.activePage.change(ChartPage)
self.activePage.chartIntermediate = False
def displayDialog(self, msg):
message = msg
title = "Info box"
tkMessageBox.showinfo(title, message)
def onKeyPressed(self, event):
self.activePage.onKeyPressed(event)
self.redrawAll()
def onMousePressed(self, event):
self.activePage.onMousePressed(event)
self.redrawAll()
def onMouseMotion(self, event):
self.activePage.onMouseMotion(event)
self.redrawAll()
def redrawAll(self):
self.activePage.draw(self.canvas, self.spotRate)
class Page(object):
def __init__(self, change):
self.pageWidth, self.pageHeight = 1200, 600
self.appNameX, self.appNameY = self.pageWidth/4, self.pageHeight/8
wby2, h = 50, 40
self.initializeBooleanVariables()
self.change = change
self.initializeAllButtonVariables()
filename = "tempDir" + os.sep + "bitcoinHistory2.txt"
(self.days1Month, self.prices1Month) = self.getNMonthsData(filename,1)
self.initializeChartStuff()
self.want1Month = True
self.want6Months, self.want3Months, self.want1Year = False, False, False
self.justStarted = False
self.chartIntermediate = False
def initializeBooleanVariables(self):
self.predict = False
self.chart = False
self.data = False
def initializeAllButtonVariables(self):
wby2, h, mgn, space = 50, 40, 80, 120
self.predictX1 = self.pageWidth/2 - wby2 - mgn
self.predictY1 = self.pageHeight - h
self.predictX2 = self.pageWidth/2 + wby2 - mgn
self.predictY2 = self.pageHeight
self.chartX1, self.chartX2 = self.predictX1-space, self.predictX2-space
self.chartY1, self.chartY2 = self.predictY1, self.predictY2
self.dataX1, self.dataX2 = self.predictX1+space, self.predictX2 + space
self.dataY1, self.dataY2 = self.predictY1, self.predictY2
self.homeX1, self.homeX2 = self.predictX1-2*space,self.predictX2-2*space
self.homeY1, self.homeY2 = self.predictY1, self.predictY2
self.personalizedX1 = self.predictX1 + 2*space
self.personalizedX2 = self.predictX2 + 2*space
self.personalizedY1, self.personalizedY2 = self.predictY1,self.predictY2
self.helpX1 = self.predictX1 + 3*space
self.helpX2 = self.predictX2 + 3*space
self.helpY1, self.helpY2 = self.predictY1, self.predictY2
def initializeChartStuff(self):
self.lengthOfXAxisInPixels, self.lengthOfYAxisInPixels = 1000, 300
self.chartWidth = self.lengthOfXAxisInPixels
self.chartHeight = self.lengthOfYAxisInPixels
leftMargin, botMargin = 150, 100
self.originX = leftMargin
self.originY = self.pageHeight - botMargin
self.days, self.prices = self.days1Month, self.prices1Month
self.xmax, self.ymax = len(self.days), max(self.prices)
self.horizScalingFactor = float(self.lengthOfXAxisInPixels)/self.xmax
# pixel per day
self.vertScalingFactor = float(self.lengthOfYAxisInPixels)/self.ymax
# pixel per dollar
def createDataFile(self):
# creates a file containing data of approximately
# last one year
self.data = True
url = "https://api.coinbase.com/v1/prices/historical?page="
path = "tempDir" + os.sep + "bitcoinHistory2.txt"
if os.path.exists(path):
writeFile(path, "", "wt")
else:
os.makedirs("tempDir")
writeFile(path, "", "wt")
reachedLastYear = False
pageNo = 1
while not reachedLastYear:
urlWithPage = url + str(pageNo)
urlContents = readWebPage(urlWithPage)
dateLen = 10
reachedLastYear = self.checkLastYear(str(urlContents[0:dateLen]))
normalizedContents = self.normalize(urlContents)
writeFile(path, normalizedContents)
pageNo += 1
self.data = False
def getNewEntry(self):
# gets new entry if released by coinbase
url = "https://api.coinbase.com/v1/prices/historical?page=1"
path = "tempDir" + os.sep + "bitcoinHistory2.txt"
with open(path, "rt") as fin:
originalContents = fin.read()
contents = makeFileIntoArray(path)
urlContents = readWebPage(url)
urlContents = urlContents.split("\n")
urlContents = urlContents[0]
possibleNewEntry = self.normalize(urlContents)
if possibleNewEntry[0].split("\n")[0] != contents[0]:
newContents = (str(possibleNewEntry[0].split("\n")[0]) +
"\n" + str(originalContents))
writeFile(path, newContents, "wt")
def normalize(self, urlContents):
# normalizes all timestamps to CMU's timezone,
# i.e. UTC-5
# reason for having this fn: coinbase randomizes the timezone it
# displays its data in, every instant.
cmuTimezone = -5 # relative to UTC
newContents = "" # the contents as we want them
urlContents = urlContents.split("\n")
hIndex, hhmmLength, tzIndex, dateLen = 11, 5, 21, 10
for i in xrange(len(urlContents)):
timestamp = urlContents[i][hIndex : hIndex + hhmmLength]
# in hh:mm format
coinbaseTimezone = int(urlContents[i][tzIndex - 2 : tzIndex + 1])
mIdx, hrsInDay, priceIdx = 3, 24, 26
hour, minute = int(timestamp[0 : 2]), timestamp[mIdx : mIdx + 2]
normalizedHour = (str((hour + cmuTimezone - coinbaseTimezone)
% hrsInDay))
newDate = urlContents[i][0 : dateLen]
if len(normalizedHour) == 1: normalizedHour = "0" + normalizedHour
if int(normalizedHour) + coinbaseTimezone - cmuTimezone >= 24:
newDate = self.timezoneTooPositiveDecreaseDate(newDate)
# timezone was so positive that date changed
elif int(normalizedHour) + coinbaseTimezone - cmuTimezone < 0:
newDate = self.timezoneTooNegativeIncreaseDate(newDate)
# timezone was so negative that date changed
urlContents[i] = (newDate + normalizedHour
+ ":" + str(minute) + str(urlContents[i][priceIdx:]) + "\n")
return urlContents
def timezoneTooNegativeIncreaseDate(self, d):
# returns a string of the newDate
d = date(int(d[:4]), int(d[5:7]), int(d[8:]))
dayLengthList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
dayCopy = d.day + 1
if dayCopy > dayLengthList[d.month-1]:
newDay = 1
if d.month == 12:
newMonth = 1
newYear = d.year + 1
else:
newMonth = d.month + 1
newYear = d.year
else:
newDay = dayCopy
newMonth = d.month
newYear = d.year
newDate = date(newYear, newMonth, newDay)
dateString = str(newDate)
return dateString
def timezoneTooPositiveDecreaseDate(self, d):
# returns a string of the newDate
d = date(int(d[:4]), int(d[5:7]), int(d[8:]))
dayLengthList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
dayCopy = d.day - 1
if dayCopy == 0:
newDay = dayLengthList[(d.month - 1) - 1]
if d.month == 1:
newMonth = 12
newYear = d.year - 1
else:
newMonth = d.month - 1
newYear = d.year
else:
newDay = dayCopy
newMonth = d.month
newYear = d.year
newDate = date(newYear, newMonth, newDay)
dateString = str(newDate)
return dateString
def checkLastYear(self, dateOnPage):
# returns True if dateOnPage is older than one year before
# today's date
dateOnPage = dateOnPage.split("-")
today = str(date.today()).split("-")
if (int(dateOnPage[0]) == int(today[0]) - 1 and
((int(dateOnPage[1]) < int(today[1])) or
(int(dateOnPage[1]) == int(today[1]) and
int(dateOnPage[2]) < int(today[2])))):
return True
return False
def onMousePressed(self, event):
x, y = event.x, event.y
if (self.predictX1 < x < self.predictX2 and
self.predictY1 < y < self.predictY2):
self.predict, self.chart, self.data = True, False, False
self.change(PredictPage)
elif (self.chartX1 < x < self.chartX2 and self.chartY1<y<self.chartY2):
self.chart, self.chartIntermediate = True, True
self.predict, self.data = False, False
elif (self.dataX1 < x < self.dataX2 and self.dataY1 < y < self.dataY2):
self.data = True
elif (self.homeX1 < x < self.homeX2 and self.homeY1 < y < self.homeY2):
self.predict, self.data, self.chart = False, False, False
self.change(HomePage)
elif (self.personalizedX1 < x < self.personalizedX2 and
self.personalizedY1 < y < self.personalizedY2):
self.predict, self.data, self.chart = False, False, False
self.change(PersonalizedCharts)
elif (self.helpX1 < x < self.helpX2 and self.helpY1 < y < self.helpY2):
self.predict, self.data, self.chart = False, False, False
self.change(Help)
def draw(self, canvas, spotRate):
canvas.delete(ALL)
self.makePredictButton(canvas)
self.makeChartsButton(canvas)
self.makeLoadDataButton(canvas)
self.makeHomeButton(canvas)
self.makePersonalizedChartsButton(canvas)
self.makeAboutButton(canvas)
# rgbString(30, 104, 255) is the dodger blue color which is the main color
# I use in my app.
def makeChartsButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.chartX1, self.chartY1,
self.chartX2, self.chartY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.chartX1 + wby2, self.chartY1 + h/2,
text = "View Charts", fill = "snow")
def makePredictButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.predictX1, self.predictY1,
self.predictX2, self.predictY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.predictX1 + wby2, self.predictY1 + h/2,
text = "Predict!", fill = "snow")
def makeLoadDataButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.dataX1, self.dataY1,
self.dataX2, self.dataY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.dataX1 + wby2, self.dataY1 + h/2,
text = "Refresh Data", fill = "snow")
def makeHomeButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.homeX1, self.homeY1,
self.homeX2, self.homeY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.homeX1 + wby2, self.homeY1 + h/2,
text = "Home", fill = "snow")
def makePersonalizedChartsButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.personalizedX1, self.personalizedY1,
self.personalizedX2, self.personalizedY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.personalizedX1 + wby2,
self.personalizedY1 + h/2,
text = "Personalize", fill = "snow")
def makeAboutButton(self, canvas):
wby2, h = 50, 40
canvas.create_rectangle(self.helpX1, self.helpY1,
self.helpX2, self.helpY2,
fill = rgbString(30, 104, 255),
outline = rgbString(30, 104, 255))
canvas.create_text(self.helpX1 + wby2,
self.helpY1 + h/2,
text = "About", fill = "snow")
def drawLoadingScreen(self, canvas):
canvas.create_rectangle(0, 0, self.pageWidth, self.pageHeight,
fill = "black")
canvas.create_text(self.pageWidth/2, self.pageHeight/2,
text = "Loading... Please be patient..",
font = "Arial 40 bold", fill = "snow")
def drawBanner(self, canvas):
canvas.create_rectangle(0, 0, self.pageWidth, self.pageHeight/4,
fill = rgbString(30, 104, 255), outline = rgbString(30, 104, 255))
# dodger blue color
canvas.create_text(self.appNameX, self.appNameY,
text = "bitPredict", fill = "snow",
font = "Trebuchet 100 bold italic")
def getPriceArray(self, filename):
priceIdx = 15
with open(filename, "rt") as fin:
contents = fin.read()
contents = contents.split("\n")
for i in xrange(len(contents)):
contents[i] = contents[i][priceIdx:]
return contents
def getLastNMaximas(self, N):
filename = "tempDir" + os.sep + "bitcoinHistory2.txt"
self.priceArray = self.getPriceArray(filename)
self.maximas, noOfMax, i = [], 0, 1
while noOfMax < N:
if (float(self.priceArray[i]) >= float(self.priceArray[i - 1]) and
float(self.priceArray[i]) >= float(self.priceArray[i + 1])):
self.maximas += [float(self.priceArray[i])]
noOfMax += 1
i += 1
return self.maximas
def getLastNMinimas(self, N):
filename = "tempDir" + os.sep + "bitcoinHistory2.txt"
self.priceArray = self.getPriceArray(filename)
self.minimas, noOfMin, i = [], 0, 1
while noOfMin < N:
if (float(self.priceArray[i]) <= float(self.priceArray[i - 1]) and
float(self.priceArray[i]) <= float(self.priceArray[i + 1])):
self.minimas += [float(self.priceArray[i])]
noOfMin += 1
i += 1
return self.minimas
def getResistanceLine(self):
N, S, avg = 10, 0, 0
self.maximas = self.getLastNMaximas(N)
for i in xrange(len(self.maximas)):
S += self.maximas[i]
avg = float(S)/N
return avg
def getSupportLine(self):
N, S, avg = 10, 0, 0
self.minimas = self.getLastNMinimas(N)
for i in xrange(len(self.minimas)):
S += self.minimas[i]
avg = float(S)/N
return avg
def getNMonthsData(self, filename, N):
# sifts through the file and creates two arrays of time coordinate and
# varying bitcoin price.
days, prices = [date.today()], [float(getSpotRate())]
with open(filename, "rt") as fin:
contents = fin.read()
contents = contents.split("\n")
current = date.today()
yrIdx, mIdx, dIdx, hIdx, minIdx, priceIdx = 4, 5, 8, 10, 13, 15
i = 0
month = date.today().month
while (((date.today().month - month) % 12 < N) or
((date.today().month - month) % 12 == N and
day >= date.today().day)):
year = int(contents[i][0 : yrIdx])
month = int(contents[i][mIdx : mIdx + 2])
day = int(contents[i][dIdx : dIdx + 2])
if (date(year, month, day) != current):
days = [date(year, month, day)] + days
prices = [float(contents[i][priceIdx:])] + prices
current = date(year, month, day)
i += 1
return (days, prices)
def getOneYearData(self, filename):
# sifts through the file and creates two arrays of time coordinate and
# varying bitcoin price.
days, prices = [date.today()], [float(getSpotRate())]
with open(filename, "rt") as fin:
contents = fin.read()
contents = contents.split("\n")
current = date.today()
yrIdx, mIdx, dIdx, hIdx, minIdx, priceIdx = 4, 5, 8, 10, 13, 15
for i in xrange(len(contents)):
year = int(contents[i][0 : yrIdx])
month = int(contents[i][mIdx : mIdx + 2])
day = int(contents[i][dIdx : dIdx + 2])
if (current >= date(date.today().year - 1,
date.today().month, date.today().day)):
if (date(year, month, day) != current):
days = [date(year, month, day)] + days
prices = [float(contents[i][priceIdx:])] + prices
current = date(year, month, day)
else:
break
return (days, prices)
def drawScaledAxes(self, canvas):
# draws the Axes scaled according to parameters given as input.
canvas.create_line(self.originX, self.originY,
self.originX, self.originY - self.chartHeight)
# draws Y axis
canvas.create_line(self.originX, self.originY,
self.originX + self.chartWidth, self.originY)
# draws X axis
self.hashXAxis(canvas)
self.hashYAxis(canvas)
def hashXAxis(self, canvas):
spacing = 10
i = 0
if self.want1Year: step = 30
elif self.want6Months: step = 20
elif self.want3Months: step = 15
elif self.want1Month: step = 3
while (i <= len(self.days) - step):
canvas.create_text(self.originX + i * self.horizScalingFactor,
self.originY + spacing, text = self.display(self.days[i]))
i += step
canvas.create_text(self.originX + self.lengthOfXAxisInPixels,
self.originY + spacing, text = self.display(self.days[-1]))
# display today's date
def hashYAxis(self, canvas):
spacing = 30
canvas.create_text(self.originX - spacing,
self.originY - self.lengthOfYAxisInPixels,
text = "$ " + str(self.ymax))
i = 0
while i <= self.ymax:
canvas.create_text(self.originX - spacing,
self.originY - i * self.vertScalingFactor,
text = "$ " + str(i))
i += 200
def plotChart(self, canvas, noOfMonths):
filename = "tempDir" + os.sep + "bitcoinHistory2.txt"
if self.justStarted: self.justStarted = False
elif noOfMonths == 12:
self.days, self.prices = self.days1Year, self.prices1Year
elif noOfMonths == 6:
self.days, self.prices = self.days6Months, self.prices6Months
elif noOfMonths == 3:
self.days, self.prices = self.days3Months, self.prices3Months
elif noOfMonths == 1:
self.days, self.prices = self.days1Month, self.prices1Month
self.adjustScale()
self.drawScaledAxes(canvas)
oldScreenX = self.originX
oldScreenY = self.originY - self.vertScalingFactor * self.prices[0]
for i in xrange(len(self.days)):
screenX = (self.originX + i*self.horizScalingFactor)
screenY = self.originY - (self.prices[i]*self.vertScalingFactor)
canvas.create_line(screenX, screenY, oldScreenX, oldScreenY)
oldScreenX, oldScreenY = screenX, screenY
def adjustScale(self):
self.xmax, self.ymax = len(self.days), max(self.prices)
self.horizScalingFactor = float(self.lengthOfXAxisInPixels)/self.xmax
# pixel per day
self.vertScalingFactor = float(self.lengthOfYAxisInPixels)/self.ymax
# pixel per dollar
def display(self, date):
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"]
month = months[date.month - 1]
day = date.day
return str(month) + " " + str(day)
def displaySpotRateInCorner(self, canvas, spotRate):
lineSpace = 100
canvas.create_text(self.pageWidth, 0, anchor = NE,
text = "$ " + spotRate, font = "Helvetica 50 bold")
def inChart(self, x, y):
return ((self.originX < x < self.originX + self.chartWidth) and
(self.originY - self.chartHeight < y < self.originY))
def getDaysIndexFromChartX(self, x):
index = (x - self.originX)/self.horizScalingFactor
return index
def getChartYFromPricesIndex(self, index):
return (self.originY - self.prices[index] * self.vertScalingFactor)
class HomePage(Page):
def __init__(self, change):
super(HomePage, self).__init__(change)
self.spotRateX, self.spotRateY = self.pageWidth/2, self.pageHeight*5/8
self.lastRate = 0.0
def draw(self, canvas, spotRate):
if self.chartIntermediate:
self.drawLoadingScreen(canvas)
elif self.data:
self.drawLoadingScreen(canvas)
else:
super(HomePage, self).draw(canvas, spotRate)
canvas.create_rectangle(0, 0, self.pageWidth, self.pageHeight/4,
fill = rgbString(30, 104, 255), outline=rgbString(30, 104, 255))
canvas.create_text(self.appNameX, self.appNameY,
text = "bitPredict", fill = "snow",
font = "Trebuchet 100 bold italic")
if self.chart:
self.change(ChartPage)
else:
canvas.create_text(self.spotRateX, self.spotRateY,
text = "$ "+spotRate, fill = "black",
font = "Helvetica 200 bold")
self.lastRate = float(spotRate)
self.makeLogInButton(canvas)
def makeLogInButton(self, canvas):
lineSpace, vertR, horizR = 40, 20, 60
self.butX, self.butY = self.pageWidth*3/4, self.pageHeight/8
canvas.create_rectangle(self.butX - horizR, self.butY - vertR,
self.butX + horizR, self.butY + vertR, fill = rgbString(0, 0, 128))
canvas.create_text(self.butX, self.butY, text = "Log into Coinbase",
fill = "snow")
def onMousePressed(self, event):
x, y = event.x, event.y
inpFieldVertR, inpFieldHorizR, butVertR, butHorizR = 10, 100, 20, 60
if (self.butX - butHorizR < x < self.butX + butHorizR and
self.butY - butVertR < y < self.butY + butVertR):
browser = webbrowser.get()
browser.open_new_tab("https://www.coinbase.com")
else:
super(HomePage, self).onMousePressed(event)
def onMouseMotion(self, event):
pass
def onKeyPressed(self, event):
pass
class PredictPage(Page):
def __init__(self, change):
super(PredictPage, self).__init__(change)
self.predict = True
self.intention, self.intentionRecorded, self.trend = None, False, None
self.frozen = False
wby2, h, spacing = 50, 40, 100
self.originX = float(self.pageWidth)/4
self.originY = float(self.pageHeight)*3/4
self.horizPixelLimit = self.pageWidth/2
self.vertPixelLimit = self.pageHeight/2
path = "tempDir" + os.sep + "bitcoinHistory2.txt"
(self.xi, self.yi) = self.getPastOneDayData(path)
self.ymax, self.ymin = max(self.yi) + 5, min(self.yi) - 5 # in dollars
self.xmax = -1 * self.xi[-1] # in seconds
self.horizScalingFactor = float(self.horizPixelLimit)/self.xmax
self.vertScalingFactor = (float(self.vertPixelLimit)/(self.ymax -
self.ymin))
self.initializeFrozenAndPromptVariables()
def initializeFrozenAndPromptVariables(self):
wby2, h, spacing = 50, 40, 100
self.freezeX1 = self.pageWidth/2 - wby2
self.freezeX2 = self.pageWidth/2 + wby2
self.freezeY1 = self.pageHeight - spacing - h/2
self.freezeY2 = self.pageHeight - spacing + h/2
self.promptToBuy, self.promptToSell = False, False
def draw(self, canvas, spotRate):
if self.chartIntermediate:
self.drawLoadingScreen(canvas)
elif self.data:
self.drawLoadingScreen(canvas)
else:
super(PredictPage, self).draw(canvas, spotRate)
if not self.intentionRecorded:
self.drawBanner(canvas)
self.displaySpotRateInSnow(canvas, spotRate)
self.drawWhenIntentionNotRecorded(canvas)
else:
self.displaySpotRateInCorner(canvas, spotRate)
if self.wait:
self.drawWaitPrediction(canvas)
elif self.buy:
self.drawBuyPrediction(canvas)
elif self.sell:
self.drawSellPrediction(canvas)
self.plotLinRegChart(canvas)
self.showLegend(canvas)
def showLegend(self, canvas):
startX = self.originX + self.horizPixelLimit
canvas.create_text(startX, 200, anchor = W,
text = "Resistance Line: $ " + str(self.resistanceLine),
fill = rgbString(0, 100, 0))
canvas.create_text(startX, 300, anchor = W,
text = ("Linear regression curve: \ny = "+str(self.slope)+"x + " +
str(self.intercept)), fill = "blue")
canvas.create_text(startX, 400, anchor = W,
text = "Support Line: $ " + str(self.supportLine),
fill = "red")
#canvas.create_text()
def drawWaitPrediction(self, canvas):
self.trend = self.determineRecentTrend()
if ((self.intention == "b" or self.intention == "f") and
self.trend == "decreasing"):
message = self.getWaitMessageForSimilarTrendAndIntention()
elif ((self.intention == "b") and self.trend == "increasing"):
message = self.getWaitMessageForOppositeTrendAndIntention()
elif (self.intention == "s" and self.trend == "decreasing"):
message = self.getWaitMessageForOppositeTrendAndIntention()
elif ((self.intention == "s" or self.intention == "f") and
self.trend == "increasing"):
message = self.getWaitMessageForSimilarTrendAndIntention()
canvas.create_text(self.pageWidth/2, self.pageHeight/8, text = message,
font = "Helvetica 14 bold")
def getWaitMessageForSimilarTrendAndIntention(self):
# decreasing -> buy
# increasing -> sell
if self.trend == "decreasing":
limitLine = str(self.supportLine)
else:
limitLine = str(self.resistanceLine)
if self.intention == "b" or self.intention == "f":
activity = "buy"
else:
activity = "sell"
behavior = "drop" if self.trend == "decreasing" else "rise"
message = ("Please wait for a while, the price is in a %s\n" +
"trend. As the prices %s further upto $%s, \n" +
"you should %s.") %(self.trend, behavior, limitLine, activity)
return message
def getWaitMessageForOppositeTrendAndIntention(self):
# decreasing -> sell
# increasing -> buy
if self.intention == "f":
for intent in "bs":
message += self.setValuesAndGetMessage(intent)
return message
else:
message = self.setValuesAndGetMessage(self.intention)
return message
def setValuesAndGetMessage(self, intent):
activity = "buy" if intent == "b" else "sell"
behavior = "rise" if self.trend == "decreasing" else "drop"
hilo = "high" if self.trend == "decreasing" else "low"
if self.trend == "decreasing":
limitLine = str(self.resistanceLine)
else:
limitLine = str(self.supportLine)
message = ("At the moment, prices are %s. This is not a\n" +
" bad time to %s, but it may not be a very good time to %s \n" +
" as we anticipate the price to %s further than the current\n" +
" price eventually, i.e. at least as %s as $%s \n") %(self.trend,
activity, activity, behavior, hilo, limitLine)
return message
def drawBuyPrediction(self, canvas):
self.trend = self.determineRecentTrend()
if ((self.intention == "b" or self.intention == "f")
and self.trend == "decreasing"):
message = self.getBuyPredictionWithFreezeForDecreasingTrend(canvas)
elif ((self.intention == "b" or self.intention == "f")
and self.trend == "increasing"):
message = ("Current price is low, but it's rising. BUY NOW!")
elif (self.intention == "s" and self.trend == "decreasing"):
message = self.getBuyPredictionForSellIntentionAndDecreasingTrend()
elif (self.intention == "s" and self.trend == "increasing"):
message = ("Prices are lower than usual right now, and increasing."
+ "\n This is the time to wait to sell. Although you want to" +
" sell," + "\nthis is a great time to buy.")
canvas.create_text(self.pageWidth/2, self.pageHeight/8, text = message,
font = "Helvetica 14 bold")
def getBuyPredictionWithFreezeForDecreasingTrend(self, canvas):
message = ("This is a good time to buy. But the trend is\n" +
" decreasing, so prices will fall further. Click FREEZE if\n" +
" you want to be prompted when to buy." )
wby2, h = 50, 40
canvas.create_rectangle(self.freezeX1, self.freezeY1,
self.freezeX2, self.freezeY2, fill = rgbString(30, 104, 255))
canvas.create_text(self.freezeX1 + wby2, self.freezeY1 + h/2,
text = "FREEZE!", fill = "snow")
self.promptToBuy = True
return message
def getBuyPredictionForSellIntentionAndDecreasingTrend(self):
message = ("This is not a bad time to sell because prices are\n" +
" decreasing, but we anticipate" + " the price to rise as\n" +
" high as " + str(self.resistanceLine) + " eventually.\n" +
" Although you want to sell, this might be a good\n" +
" time to buy or wait for the prices to fall further.")
return message
def drawSellPrediction(self, canvas):
self.trend = self.determineRecentTrend()
wby2, h = 50, 40
if ((self.intention == "s" or self.intention == "f") and
self.trend == "decreasing"):
message = ("Current price is high, but it's dropping. SELL NOW!")
elif ((self.intention == "s" or self.intention == "f") and
self.trend == "increasing"):
message = self.getSellPredictionWithFreezeForIncreasingTrend(canvas)
elif self.intention == "b" and self.trend == "decreasing":
message = ("Prices are higher than usual right now, and decreasing."
+ " \nThis is the time to wait to buy. Although you want to" +
" buy, \nthis is a great time to sell.")
elif self.intention == "b" and self.trend == "increasing":
message = self.getSellPredictionForBuyIntentionAndIncreasingTrend()
canvas.create_text(self.pageWidth/2, self.pageHeight/8, text = message,
font = "Helvetica 14 bold")
def getSellPredictionWithFreezeForIncreasingTrend(self, canvas):
message = ("This is a good time to sell. But the price is \n" +
"increasing, so prices will rise further. Click FREEZE if\n" +
" you want to be prompted when to sell.")
canvas.create_rectangle(self.freezeX1, self.freezeY1,
self.freezeX2, self.freezeY2, fill = rgbString(30, 104, 255))
canvas.create_text(self.freezeX1 + wby2, self.freezeY1 + h/2,
text = "FREEZE!", fill = "snow")
self.promptToSell = True
return message
def getSellPredictionForBuyIntentionAndIncreasingTrend(self):
message = ("This is not a bad time to buy because prices are\n" +
" increasing, but we anticipate" + " the price to fall as\n" +
" low as " + str(self.supportLine) + " eventually.\n" +
" Although you want to buy, this might be a good\n" +
" time to sell or wait for the prices to rise further.")
return message
def drawWhenIntentionNotRecorded(self, canvas):
intentMessage = ("What do you intend to do?\n" +
"Press B if you intend to buy\n"+"Press S if you intend to sell\n"+
"Press F if you're flexible.")
canvas.create_text(self.pageWidth/2, self.pageHeight/2,
text = intentMessage, font = "Georgia 20 bold")
def onKeyPressed(self, event):
if not self.intentionRecorded:
if event.char == "b" or event.char == "s" or event.char == "f":
self.intention = event.char
self.intentionRecorded = True
self.prediction()
def onMousePressed(self, event):
x, y = event.x, event.y
if (self.intentionRecorded and
(self.freezeX1 < x < self.freezeX2) and
(self.freezeY1 < y < self.freezeY2)):
self.frozen = True
else:
super(PredictPage, self).onMousePressed(event)
def prediction(self):
self.resistanceLine = self.getResistanceLine()