repl.it
@andrewkdinh/

fund-indicators

Python

Determine indicators of overperforming mutual funds

fork
loading
Files
  • main.py
  • modules
  • cache.sqlite
  • Functions.py
  • README.md
  • stocks.txt
  • Packager files
  • poetry.lock
  • pyproject.toml
  • requirements.txt
main.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
'''
  __                 _            _           _ _           _
 / _|               | |          (_)         | (_)         | |
| |_ _   _ _ __   __| |  ______   _ _ __   __| |_  ___ __ _| |_ ___  _ __ ___
|  _| | | | '_ \ / _` | |______| | | '_ \ / _` | |/ __/ _` | __/ _ \| '__/ __|
| | | |_| | | | | (_| |          | | | | | (_| | | (_| (_| | || (_) | |  \__ \
|_|  \__,_|_| |_|\__,_|          |_|_| |_|\__,_|_|\___\__,_|\__\___/|_|  |___/

Project homepage: https://github.com/andrewkdinh/fund-indicators
Author: Andrew Dinh <[email protected]>

Copyright (C) 2019 Andrew Dinh

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
'''

# PYTHON FILES
import Functions
from yahoofinancials import YahooFinancials
from termcolor import cprint

# REQUIRED
import requests_cache
import os.path
import re
import datetime
import json
import requests
from bs4 import BeautifulSoup
import numpy as np

# OPTIONAL
try:
    import matplotlib.pyplot as plt
except:
    pass
from halo import Halo

# FOR ASYNC
from concurrent.futures import ThreadPoolExecutor as PoolExecutor
import time
import random

import sys
sys.path.insert(0, './modules')

requests_cache.install_cache(
    'cache', backend='sqlite', expire_after=43200)  # 12 hours

# API Keys
apiAV = 'O42ICUV58EIZZQMU'
# apiBarchart = 'a17fab99a1c21cd6f847e2f82b592838'
apiBarchart = 'f40b136c6dc4451f9136bb53b9e70ffa'
apiTiingo = '2e72b53f2ab4f5f4724c5c1e4d5d4ac0af3f7ca8'
apiTradier = 'n26IFFpkOFRVsB5SNTVNXicE5MPD'
apiQuandl = 'KUh3U3hxke9tCimjhWEF'
# apiIntrinio = 'OmNmN2E5YWI1YzYxN2Q4NzEzZDhhOTgwN2E2NWRhOWNl'
# If you're going to take these API keys and abuse it, you should really
# reconsider your life priorities

'''
API Keys:
    Alpha Vantage API Key: O42ICUV58EIZZQMU
    Barchart API Key: a17fab99a1c21cd6f847e2f82b592838
        Possible other one? f40b136c6dc4451f9136bb53b9e70ffa
        150 getHistory queries per day
    Tiingo API Key: 2e72b53f2ab4f5f4724c5c1e4d5d4ac0af3f7ca8
    Tradier API Key: n26IFFpkOFRVsB5SNTVNXicE5MPD
        Monthly Bandwidth = 5 GB
        Hourly Requests = 500
        Daily Requests = 20,000
        Symbol Requests  = 500
    Quandl API Key: KUh3U3hxke9tCimjhWEF
    Intrinio API Key: OmNmN2E5YWI1YzYxN2Q4NzEzZDhhOTgwN2E2NWRhOWNl

    Mutual funds?
    Yes: Alpha Vantage, Tiingo
    No: IEX, Barchart

    Adjusted?
    Yes: Alpha Vantage, IEX
    No: Tiingo
'''


class Stock:

    # GLOBAL VARIABLES
    timeFrame = 0  # Months
    riskFreeRate = 0
    indicator = ''

    # CONFIG
    removeOutliers = True
    sourceList = ['Yahoo', 'Alpha Vantage', 'IEX', 'Tiingo']
    plotIndicatorRegression = False
    timePlotIndicatorRegression = 5  # seconds
    config = 'N/A'

    # BENCHMARK VALUES
    benchmarkDates = []
    benchmarkCloseValues = []
    benchmarkAverageMonthlyReturn = 0
    benchmarkStandardDeviation = 0

    # INDICATOR VALUES
    indicatorCorrelation = []
    indicatorRegression = []
    persTimeFrame = 0

    def __init__(self):
        # BASIC DATA
        self.name = ''  # Ticker symbol
        self.allDates = []
        self.allCloseValues = []
        self.dates = []
        self.closeValues = []
        self.datesMatchBenchmark = []
        self.closeValuesMatchBenchmark = []

        # CALCULATED RETURN
        self.averageMonthlyReturn = 0
        self.monthlyReturn = []
        self.sharpe = 0
        self.sortino = 0
        self.treynor = 0
        self.alpha = 0
        self.beta = 0
        self.standardDeviation = 0
        self.downsideDeviation = 0
        self.kurtosis = 0
        self.skewness = 0  # Not sure if I need this
        self.correlation = 0
        self.linearRegression = []  # for y=mx+b, this list has [m,b]

        self.indicatorValue = ''

    def setName(self, newName):
        self.name = newName

    def getName(self):
        return self.name

    def getAllDates(self):
        return self.allDates

    def getAllCloseValues(self):
        return self.allCloseValues

    def IEX(self):
        url = ''.join(
            ('https://api.iextrading.com/1.0/stock/', self.name, '/chart/5y'))
        # link = "https://api.iextrading.com/1.0/stock/spy/chart/5y"
        cprint("GET:" + url, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            f = requests.get(url)
        Functions.fromCache(f)
        json_data = f.text
        if json_data == 'Unknown symbol' or f.status_code != 200:
            print("IEX not available")
            return 'N/A'
        loaded_json = json.loads(json_data)
        listIEX = []

        print("\nFinding all dates given")
        allDates = []
        for i in range(0, len(loaded_json), 1):  # For oldest first
            # for i in range(len(loaded_json)-1, -1, -1):
            line = loaded_json[i]
            date = line['date']
            allDates.append(date)
        listIEX.append(allDates)
        print(len(listIEX[0]), "dates")

        # print("\nFinding close values for each date")
        values = []
        for i in range(0, len(loaded_json), 1):  # For oldest first
            # for i in range(len(loaded_json)-1, -1, -1):
            line = loaded_json[i]
            value = line['close']
            values.append(value)
        listIEX.append(values)

        # print(len(listIEX[0]), 'dates and', len(listIEX[1]), "close values")
        return listIEX

    def AV(self):
        listAV = []
        url = ''.join(('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=',
                       self.name, '&outputsize=full&apikey=', apiAV))
        # https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&outputsize=full&apikey=demo

        cprint("GET:" + url, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            f = requests.get(url)
        Functions.fromCache(f)
        json_data = f.text
        loaded_json = json.loads(json_data)

        if len(loaded_json) == 1 or f.status_code != 200 or len(loaded_json) == 0:
            print("Alpha Vantage not available")
            return 'N/A'

        dailyTimeSeries = loaded_json['Time Series (Daily)']
        listOfDates = list(dailyTimeSeries)
        # listAV.append(listOfDates)
        listAV.append(list(reversed(listOfDates)))

        # print("\nFinding close values for each date")
        values = []
        for i in range(0, len(listOfDates), 1):
            temp = listOfDates[i]
            loaded_json2 = dailyTimeSeries[temp]
            # value = loaded_json2['4. close']
            value = loaded_json2['5. adjusted close']
            values.append(float(value))
        # listAV.append(values)
        listAV.append(list(reversed(values)))
        # print(len(listAV[0]), 'dates and', len(listAV[1]), "close values")

        return listAV

    def Tiingo(self):
        token = ''.join(('Token ', apiTiingo))
        headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
        url = ''.join(('https://api.tiingo.com/tiingo/daily/', self.name))
        cprint("GET:" + url, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            f = requests.get(url, headers=headers)
        Functions.fromCache(f)
        loaded_json = f.json()
        if len(loaded_json) == 1 or f.status_code != 200 or loaded_json['startDate'] is None:
            print("Tiingo not available")
            return 'N/A'

        listTiingo = []

        print("\nFinding first and last date")
        firstDate = loaded_json['startDate']
        lastDate = loaded_json['endDate']
        print(firstDate, '...', lastDate)

        print("\nFinding all dates given", end='')
        dates = []
        values = []
        url2 = ''.join((url, '/prices?startDate=',
                        firstDate, '&endDate=', lastDate))
        # https://api.tiingo.com/tiingo/daily/<ticker>/prices?startDate=2012-1-1&endDate=2016-1-1
        cprint("\nGET:" + url2 + '\n', 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            requestResponse2 = requests.get(url2, headers=headers)
        Functions.fromCache(requestResponse2)
        loaded_json2 = requestResponse2.json()
        for i in range(0, len(loaded_json2)-1, 1):
            line = loaded_json2[i]
            dateWithTime = line['date']
            temp = dateWithTime.split('T00:00:00.000Z')
            date = temp[0]
            dates.append(date)

            value = line['close']
            values.append(value)
        listTiingo.append(dates)
        print(len(listTiingo[0]), "dates")

        # print("Finding close values for each date")
        # Used loop from finding dates
        listTiingo.append(values)

        # print(len(listTiingo[0]), 'dates and', len(listTiingo[1]), "close values")
        return listTiingo

    def Yahoo(self):
        url = ''.join(('https://finance.yahoo.com/quote/',
                       self.name, '?p=', self.name))
        cprint('GET:' + url, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            t = requests.get(url)
        Functions.fromCache(t)
        if t.history:
            print('Yahoo Finance does not have data for', self.name)
            print('Yahoo not available')
            return 'N/A'
        else:
            print('Yahoo Finance has data for', self.name)

        ticker = self.name
        firstDate = datetime.datetime.now().date(
        ) - datetime.timedelta(days=self.timeFrame*31)  # 31 days as a buffer just in case
        with Halo(spinner='dots'):
            yahoo_financials = YahooFinancials(ticker)
            r = yahoo_financials.get_historical_price_data(
                str(firstDate), str(datetime.date.today()), 'daily')

        s = r[self.name]['prices']
        listOfDates = []
        listOfCloseValues = []
        for i in range(0, len(s), 1):
            listOfDates.append(s[i]['formatted_date'])
            listOfCloseValues.append(s[i]['close'])
        listYahoo = [listOfDates, listOfCloseValues]

        # Sometimes close value is a None value
        i = 0
        while i < len(listYahoo[1]):
            if Functions.listIndexExists(listYahoo[1][i]):
                if listYahoo[1][i] is None:
                    del listYahoo[1][i]
                    del listYahoo[0][i]
                    i = i - 1
                i = i + 1
            else:
                break

        # print(len(listYahoo[0]), 'dates and', len(listYahoo[1]), "close values")
        return listYahoo

    def datesAndClose(self):
        cprint('\n' + str(self.name), 'cyan')

        sourceList = Stock.sourceList
        # Use each source until you get a value
        for j in range(0, len(sourceList), 1):
            source = sourceList[j]
            print('Source being used:', source)

            if source == 'Alpha Vantage':
                datesAndCloseList = Stock.AV(self)
            elif source == 'Yahoo':
                datesAndCloseList = Stock.Yahoo(self)
            elif source == 'IEX':
                datesAndCloseList = Stock.IEX(self)
            elif source == 'Tiingo':
                datesAndCloseList = Stock.Tiingo(self)

            if datesAndCloseList != 'N/A':
                break
            else:
                if j == len(sourceList)-1:
                    print('\nNo sources have data for', self.name)
                    cprint('Removing ' + self.name +
                           ' because no data was found', 'yellow')
                    return 'N/A'
                print('')

        # Convert dates to datetime
        allDates = datesAndCloseList[0]
        for j in range(0, len(allDates), 1):
            allDates[j] = Functions.stringToDate(allDates[j])
        datesAndCloseList[0] = allDates

        # Determine if close value list has value of zero
        # AKA https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=RGN&outputsize=full&apikey=O42ICUV58EIZZQMU
        for i in datesAndCloseList[1]:
            if i == 0:
                print('Found close value of 0. This is likely something like ticker RGN (Daily Time Series with Splits and Dividend Events)')
                cprint('Removing ' + self.name +
                       'from list of stocks to ensure compability later', 'yellow')
                return 'N/A'

        return datesAndCloseList

    def datesAndCloseFitTimeFrame(self):
        # print('\nShortening list to fit time frame')
        # Have to do this because if I just make dates = self.allDates & closeValues = self.allCloseValues, then deleting from dates & closeValues also deletes it from self.allDates & self.allCloseValues (I'm not sure why)
        dates = list(self.allDates)
        closeValues = list(self.allCloseValues)

        firstDate = datetime.datetime.now().date() - datetime.timedelta(
            days=self.timeFrame*30)
        # print(self.timeFrame, ' months ago: ', firstDate, sep='')
        closestDate = Functions.getNearest(dates, firstDate)
        if closestDate != firstDate:
            # print('Closest date available to ' + str(self.timeFrame) + ' months ago: ' + str(closestDate))
            firstDate = closestDate
        else:
            print(self.name, 'has a close value for', firstDate)

        # Remove dates in list up to firstDate
        while dates[0] != firstDate:
            dates.remove(dates[0])

        # Remove close values until list is same length as dates
        while len(closeValues) != len(dates):
            closeValues.remove(closeValues[0])

        datesAndCloseList2 = []
        datesAndCloseList2.append(dates)
        datesAndCloseList2.append(closeValues)

        print(len(dates), 'dates and', len(closeValues), 'close values')
        return datesAndCloseList2

    def calcAverageMonthlyReturn(self):
        # averageMonthlyReturn = (float(self.closeValues[len(self.closeValues)-1]/self.closeValues[0])**(1/(self.timeFrame)))-1
        # averageMonthlyReturn = averageMonthlyReturn * 100
        averageMonthlyReturn = sum(self.monthlyReturn)/self.timeFrame
        print('Average monthly return:', averageMonthlyReturn)
        return averageMonthlyReturn

    def calcMonthlyReturn(self):
        monthlyReturn = []

        # Calculate monthly return in order from oldest to newest
        monthlyReturn = []
        for i in range(0, self.timeFrame, 1):
            firstDate = datetime.datetime.now().date() - datetime.timedelta(
                days=(self.timeFrame-i)*30)
            secondDate = datetime.datetime.now().date() - datetime.timedelta(
                days=(self.timeFrame-i-1)*30)

            # Find closest dates to firstDate and lastDate
            firstDate = Functions.getNearest(self.dates, firstDate)
            secondDate = Functions.getNearest(self.dates, secondDate)

            if firstDate == secondDate:
                print('Closest date is ' + str(firstDate) +
                      ', which is after the given time frame')
                return 'N/A'

            # Get corresponding close values and calculate monthly return
            for i in range(0, len(self.dates), 1):
                if self.dates[i] == firstDate:
                    firstClose = self.closeValues[i]
                elif self.dates[i] == secondDate:
                    secondClose = self.closeValues[i]
                    break

            monthlyReturnTemp = (secondClose/firstClose)-1
            monthlyReturnTemp = monthlyReturnTemp * 100
            monthlyReturn.append(monthlyReturnTemp)

        # print('Monthly return over the past', self.timeFrame, 'months:', monthlyReturn)
        return monthlyReturn

    def calcCorrelation(self, closeList):
        correlation = np.corrcoef(
            self.closeValuesMatchBenchmark, closeList)[0, 1]
        print('Correlation with benchmark:', correlation)
        return correlation

    def calcStandardDeviation(self):
        numberOfValues = self.timeFrame
        mean = self.averageMonthlyReturn
        standardDeviation = (
            (sum((self.monthlyReturn[x]-mean)**2 for x in range(0, numberOfValues, 1)))/(numberOfValues-1))**(1/2)
        print('Standard Deviation:', standardDeviation)
        return standardDeviation

    def calcDownsideDeviation(self):
        numberOfValues = self.timeFrame
        targetReturn = self.averageMonthlyReturn
        downsideDeviation = (
            (sum(min(0, (self.monthlyReturn[x]-targetReturn))**2 for x in range(0, numberOfValues, 1)))/(numberOfValues-1))**(1/2)
        print('Downside Deviation:', downsideDeviation)
        return downsideDeviation

    def calcKurtosis(self):
        numberOfValues = self.timeFrame
        mean = self.averageMonthlyReturn
        kurtosis = (sum((self.monthlyReturn[x]-mean)**4 for x in range(
            0, numberOfValues, 1)))/((numberOfValues-1)*(self.standardDeviation ** 4))
        print('Kurtosis:', kurtosis)
        return kurtosis

    def calcSkewness(self):
        numberOfValues = self.timeFrame
        mean = self.averageMonthlyReturn
        skewness = (sum((self.monthlyReturn[x]-mean)**3 for x in range(
            0, numberOfValues, 1)))/((numberOfValues-1)*(self.standardDeviation ** 3))
        print('Skewness:', skewness)
        return skewness

    def calcBeta(self):
        beta = self.correlation * \
            (self.standardDeviation/Stock.benchmarkStandardDeviation)
        print('Beta:', beta)
        return beta

    def calcAlpha(self):
        alpha = self.averageMonthlyReturn - \
            (Stock.riskFreeRate+((Stock.benchmarkAverageMonthlyReturn -
                                  Stock.riskFreeRate) * self.beta))
        print('Alpha:', alpha)
        return alpha

    def calcSharpe(self):
        sharpe = (self.averageMonthlyReturn - Stock.riskFreeRate) / \
            self.standardDeviation
        print('Sharpe Ratio:', sharpe)
        return sharpe

    def calcSortino(self):
        sortino = (self.averageMonthlyReturn - self.riskFreeRate) / \
            self.downsideDeviation
        print('Sortino Ratio:', sortino)
        return sortino

    def calcTreynor(self):
        treynor = (self.averageMonthlyReturn - Stock.riskFreeRate)/self.beta
        print('Treynor Ratio:', treynor)
        return treynor

    def calcLinearRegression(self):
        dates = self.dates
        y = self.closeValues

        # First change dates to integers (days from first date)
        x = datesToDays(dates)

        x = np.array(x)
        y = np.array(y)

        # Estimate coefficients
        # number of observations/points
        n = np.size(x)

        # mean of x and y vector
        m_x, m_y = np.mean(x), np.mean(y)

        # calculating cross-deviation and deviation about x
        SS_xy = np.sum(y*x) - n*m_y*m_x
        SS_xx = np.sum(x*x) - n*m_x*m_x

        # calculating regression coefficients
        b_1 = SS_xy / SS_xx
        b_0 = m_y - b_1*m_x

        b = [b_0, b_1]

        formula = ''.join(
            ('y = ', str(round(float(b[0]), 2)), 'x + ', str(round(float(b[1]), 2))))
        print('Linear regression formula:', formula)

        # Stock.plot_regression_line(self, x, y, b)

        regression = []
        regression.append(b[0])
        regression.append(b[1])
        return regression

    def plot_regression_line(self, x, y, b):
        # plotting the actual points as scatter plot
        plt.scatter(self.dates, y, color="m",
                    marker="o", s=30)

        # predicted response vector
        y_pred = b[0] + b[1]*x

        # plotting the regression line
        plt.plot(self.dates, y_pred, color="g")

        # putting labels
        plt.title(self.name)
        plt.xlabel('Dates')
        plt.ylabel('Close Values')

        # function to show plot
        try:
            t = Stock.timePlotIndicatorRegression
            plt.show(block=False)
            for i in range(t, 0, -1):
                if i == 1:
                    sys.stdout.write('Keeping plot open for ' +
                                     str(i) + ' second \r')
                else:
                    sys.stdout.write('Keeping plot open for ' +
                                     str(i) + ' seconds \r')
                plt.pause(1)
                sys.stdout.flush()
            sys.stdout.write(
                '                                                 \r')
            sys.stdout.flush()
            plt.close()
        except:
            sys.stdout.write(
                '                                                 \r')
            sys.stdout.flush()

    def scrapeYahooFinance(self):
        # Determine if ETF, Mutual fund, or stock
        url = ''.join(('https://finance.yahoo.com/quote/',
                       self.name, '?p=', self.name))
        cprint('GET:' + url, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            t = requests.get(url)
        Functions.fromCache(t)
        if t.history:
            print('Yahoo Finance does not have data for', self.name)
            return 'N/A'
        else:
            print('Yahoo Finance has data for', self.name)

        stockType = ''
        url2 = ''.join(('https://finance.yahoo.com/lookup?s=', self.name))
        cprint('GET:' + url2, 'white', attrs=['dark'])
        with Halo(spinner='dots'):
            x = requests.get(url2)
            raw_html = x.text
        Functions.fromCache(x)

        soup2 = BeautifulSoup(raw_html, 'html.parser')
        # Type (Stock, ETF, Mutual Fund)
        r = soup2.find_all(
            'td', attrs={'class': 'data-col4 Ta(start) Pstart(20px) Miw(30px)'})
        u = soup2.find_all('a', attrs={'class': 'Fw(b)'})  # Name and class
        z = soup2.find_all('td', attrs={
                           'class': 'data-col1 Ta(start) Pstart(10px) Miw(80px)'})  # Name of stock
        listNames = []
        for i in u:
            if i.text.strip() == i.text.strip().upper():
                listNames.append(i.text.strip())
            '''
            if len(i.text.strip()) < 6:
                listNames.append(i.text.strip())
            elif '.' in i.text.strip():
                listNames.append(i.text.strip())  # Example: TSNAX (TSN.AX)
            #! If having problems later, separate them by Industries (Mutual funds and ETF's are always N/A)
            '''

        for i in range(0, len(listNames), 1):
            if listNames[i] == self.name:
                break

        r = r[i].text.strip()
        z = z[i].text.strip()
        print('Name:', z)

        if r == 'ETF':
            stockType = 'ETF'
        elif r == 'Stocks':
            stockType = 'Stock'
        elif r == 'Mutual Fund':
            stockType = 'Mutual Fund'
        else:
            print('Could not determine fund type')
            return 'N/A'
        print('Type:', stockType)

        if Stock.indicator == 'Expense Ratio':
            if stockType == 'Stock':
                print(
                    self.name, 'is a stock, and therefore does not have an expense ratio')
                return 'Stock'

            raw_html = t.text
            soup = BeautifulSoup(raw_html, 'html.parser')

            r = soup.find_all('span', attrs={'class': 'Trsdu(0.3s)'})
            if r == []:
                print('Something went wrong with scraping expense ratio')
                return('N/A')

            if stockType == 'ETF':
                for i in range(len(r)-1, 0, -1):
                    s = r[i].text.strip()
                    if s[-1] == '%':
                        break
            elif stockType == 'Mutual Fund':
                count = 0  # Second in set
                for i in range(0, len(r)-1, 1):
                    s = r[i].text.strip()
                    if s[-1] == '%' and count == 0:
                        count += 1
                    elif s[-1] == '%' and count == 1:
                        break

            if s[-1] == '%':
                expenseRatio = float(s.replace('%', ''))
            else:
                print('Something went wrong with scraping expense ratio')
                return 'N/A'
            print(Stock.indicator + ': ', end='')
            print(str(expenseRatio) + '%')
            return expenseRatio

        elif Stock.indicator == 'Market Capitalization':
            somethingWrong = False
            raw_html = t.text
            soup = BeautifulSoup(raw_html, 'html.parser')
            r = soup.find_all(
                'span', attrs={'class': 'Trsdu(0.3s)'})
            if r == []:
                somethingWrong = True
            else:
                marketCap = 0
                for t in r:
                    s = t.text.strip()
                    if s[-1] == 'B':
                        print(Stock.indicator + ': ', end='')
                        print(s, end='')
                        s = s.replace('B', '')
                        marketCap = float(s) * 1000000000  # 1 billion
                        break
                    elif s[-1] == 'M':
                        print(Stock.indicator + ': ', end='')
                        print(s, end='')
                        s = s.replace('M', '')
                        marketCap = float(s) * 1000000  # 1 million
                        break
                    elif s[-1] == 'K':
                        print(Stock.indicator + ': ', end='')
                        print(s, end='')
                        s = s.replace('K', '')
                        marketCap = float(s) * 1000  # 1 thousand
                        break
                if marketCap == 0:
                    somethingWrong = True
            if somethingWrong:
                ticker = self.name
                yahoo_financials = YahooFinancials(ticker)
                marketCap = yahoo_financials.get_market_cap()
                if marketCap is not None:
                    print('(Taken from yahoofinancials)')
                    print(marketCap)
                    return int(marketCap)
                else:
                    print(
                        'Was not able to scrape or get market capitalization from yahoo finance')
                    return 'N/A'
                marketCap = int(marketCap)
                return marketCap

            print(' =', marketCap)
            marketCap = marketCap / 1000000
            print(
                'Dividing marketCap by 1 million:', marketCap)
            return marketCap

        elif Stock.indicator == 'Turnover':
            if stockType == 'Stock':
                print(self.name, 'is a stock, and therefore does not have turnover')
                return 'Stock'

            if stockType == 'Mutual Fund':
                raw_html = t.text
                soup = BeautifulSoup(raw_html, 'html.parser')

                r = soup.find_all(
                    'span', attrs={'class': 'Trsdu(0.3s)'})
                if r == []:
                    print('Something went wrong without scraping turnover')
                    return 'N/A'
                turnover = 0
                for i in range(len(r)-1, 0, -1):
                    s = r[i].text.strip()
                    if s[-1] == '%':
                        turnover = float(s.replace('%', ''))
                        break
            if stockType == 'ETF':
                url = ''.join(('https://finance.yahoo.com/quote/',
                               self.name, '/profile?p=', self.name))
                # https://finance.yahoo.com/quote/SPY/profile?p=SPY
                cprint('GET:' + url, 'white', attrs=['dark'])
                with Halo(spinner='dots'):
                    t = requests.get(url)
                Functions.fromCache(t)
                raw_html = t.text
                soup = BeautifulSoup(raw_html, 'html.parser')

                r = soup.find_all(
                    'span', attrs={'class': 'W(20%) D(b) Fl(start) Ta(e)'})
                if r == []:
                    print('Something went wrong without scraping turnover')
                    return 'N/A'
                turnover = 0
                for i in range(len(r)-1, 0, -1):
                    s = r[i].text.strip()
                    if s[-1] == '%':
                        turnover = float(s.replace('%', ''))
                        break

            if turnover == 0:
                print('Something went wrong with scraping turnover')
                return 'N/A'
            print(Stock.indicator + ': ', end='')
            print(str(turnover) + '%')
            return turnover

    def indicatorManual(self):
        indicatorValueFound = False
        while indicatorValueFound is False:
            if Stock.indicator == 'Expense Ratio':
                indicatorValue = str(
                    input(Stock.indicator + ' for ' + self.name + ' (%): '))
            elif Stock.indicator == 'Persistence':
                indicatorValue = str(
                    input(Stock.indicator + ' for ' + self.name + ' (years): '))
            elif Stock.indicator == 'Turnover':
                indicatorValue = str(input(
                    Stock.indicator + ' for ' + self.name + ' in the last ' + str(Stock.timeFrame) + ' years: '))
            elif Stock.indicator == 'Market Capitalization':
                indicatorValue = str(
                    input(Stock.indicator + ' of ' + self.name + ': '))

            if Functions.strintIsFloat(indicatorValue):
                indicatorValueFound = True
                return float(indicatorValue)
            else:
                print('Please enter a number')

    def calcPersistence(self):
        persistenceFirst = (sum(self.monthlyReturn[i] for i in range(
            0, Stock.persTimeFrame, 1))) / Stock.persTimeFrame
        persistenceSecond = self.averageMonthlyReturn
        persistence = persistenceSecond-persistenceFirst
        print('Change (difference) in average monthly return:', persistence)
        return persistence


def datesToDays(dates):
    days = []
    firstDate = dates[0]
    days.append(0)
    for i in range(1, len(dates), 1):
        # Calculate days from first date to current date
        daysDiff = (dates[i]-firstDate).days
        days.append(daysDiff)
    return days


def benchmarkInit():
    # Treat benchmark like stock
    benchmarkTicker = ''
    benchmarks = ['S&P500', 'DJIA', 'Russell 3000', 'MSCI EAFE']
    benchmarksTicker = ['SPY', 'DJIA', 'VTHR', 'EFT']
    print('\nList of benchmarks:')
    for i in range(0, len(benchmarks), 1):
        print('[' + str(i+1) + '] ' +
              benchmarks[i] + ' (' + benchmarksTicker[i] + ')')
    while benchmarkTicker == '':

        benchmark = str(input('Please choose a benchmark from the list: '))
        # benchmark = 'SPY' # TESTING

        if Functions.stringIsInt(benchmark):
            if int(benchmark) <= len(benchmarks) and int(benchmark) > 0:
                benchmarkInt = int(benchmark)
                benchmark = benchmarks[benchmarkInt-1]
                benchmarkTicker = benchmarksTicker[benchmarkInt-1]
        else:
            for i in range(0, len(benchmarks), 1):
                if benchmark == benchmarks[i]:
                    benchmarkTicker = benchmarksTicker[i]
                    break
                if benchmark == benchmarksTicker[i] or benchmark == benchmarksTicker[i].lower():
                    benchmark = benchmarks[i]
                    benchmarkTicker = benchmarksTicker[i]
                    break

        if benchmarkTicker == '':
            print('Benchmark not found')

    print(benchmark, ' (', benchmarkTicker, ')', sep='')

    benchmark = Stock()
    benchmark.setName(benchmarkTicker)

    return benchmark


def stocksInit():
    listOfStocks = []

    print('\nThis program can analyze stocks (GOOGL), mutual funds (VFINX), and ETFs (SPY)')
    print('For simplicity, all of them will be referred to as "stock"')

    found = False
    while found is False:
        print('\nMethods:')
        method = 0
        methods = ['Read from a file', 'Enter manually',
                   'Kiplinger top-performing funds (50)',
                   'TheStreet top-rated mutual funds (20)',
                   'Money best mutual funds (50)',
                   'Investors Business Daily best mutual funds (~45)']

        for i in range(0, len(methods), 1):
            print('[' + str(i+1) + '] ' + methods[i])
        while method == 0 or method > len(methods):
            method = str(input('Which method? '))
            if Functions.stringIsInt(method):
                method = int(method)
                if method == 0 or method > len(methods):
                    print('Please choose a number from 1 to', len(methods))
            else:
                method = 0
                print('Please choose a number')

        print('')
        if method == 1:
            defaultFiles = ['.gitignore', 'LICENSE', 'main.py', 'Functions.py',
                            'README.md', 'requirements.txt', 'cache.sqlite',
                            'config.json', 'CONTRIBUTING.md',
                            'config.example.json', 'CODE-OF-CONDUCT.md', 
                            '_test_runner.py', 'poetry.lock', 'pyproject.toml']
            # Added by repl.it for whatever reason
            stocksFound = False
            print('Files in current directory (without default files): ')
            listOfFilesTemp = [f for f in os.listdir() if os.path.isfile(f)]
            listOfFiles = []
            for files in listOfFilesTemp:
                if files[0] != '.' and any(x in files for x in defaultFiles) is not True:
                    listOfFiles.append(files)
            for i in range(0, len(listOfFiles), 1):
                if listOfFiles[i][0] != '.':
                    print('[' + str(i+1) + '] ' + listOfFiles[i])
            while stocksFound is False:
                fileName = str(input('What is the file number/name? '))
                if Functions.stringIsInt(fileName):
                    if int(fileName) < len(listOfFiles)+1 and int(fileName) > 0:
                        fileName = listOfFiles[int(fileName)-1]
                        print(fileName)
                if Functions.fileExists(fileName):
                    listOfStocks = []
                    file = open(fileName, 'r')
                    n = file.read()
                    file.close()
                    s = re.findall(r'[^,;\s]+', n)
                    for i in s:
                        if str(i) != '' and Functions.hasNumbers(str(i)) is False:
                            listOfStocks.append(str(i).upper())
                    stocksFound = True
                else:
                    print('File not found')
            for i in range(0, len(listOfStocks), 1):
                stockName = listOfStocks[i].upper()
                listOfStocks[i] = Stock()
                listOfStocks[i].setName(stockName)

            for k in listOfStocks:
                print(k.name, end=' ')
            print('\n' + str(len(listOfStocks)) + ' stocks total')

        elif method == 2:
            isInteger = False
            while isInteger is False:
                temp = input('Number of stocks to analyze (2 minimum): ')
                isInteger = Functions.stringIsInt(temp)
                if isInteger:
                    if int(temp) >= 2:
                        numberOfStocks = int(temp)
                    else:
                        print('Please type a number greater than or equal to 2')
                        isInteger = False
                else:
                    print('Please type an integer')

            i = 0
            while i < numberOfStocks:
                print('Stock', i + 1, end=' ')
                stockName = str(input('ticker: '))

                if stockName != '' and Functions.hasNumbers(stockName) is False:
                    stockName = stockName.upper()
                    listOfStocks.append(stockName)
                    listOfStocks[i] = Stock()
                    listOfStocks[i].setName(stockName)
                    i += 1
                else:
                    print('Invalid ticker')

        elif method == 3:
            listOfStocks = []
            url = 'https://www.kiplinger.com/tool/investing/T041-S001-top-performing-mutual-funds/index.php'
            headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'}
            cprint('GET:' + url, 'white', attrs=['dark'])
            with Halo(spinner='dots'):
                f = requests.get(url, headers=headers)
            Functions.fromCache(f)
            raw_html = f.text
            soup = BeautifulSoup(raw_html, 'html.parser')

            file = open('kiplinger-stocks.txt', 'w')
            r = soup.find_all('a', attrs={'style': 'font-weight:700;'})
            for k in r:
                print(k.text.strip(), end=' ')
                listOfStocks.append(k.text.strip())
                file.write(str(k.text.strip()) + '\n')
            file.close()

            for i in range(0, len(listOfStocks), 1):
                stockName = listOfStocks[i].upper()
                listOfStocks[i] = Stock()
                listOfStocks[i].setName(stockName)

            print('\n' + str(len(listOfStocks)) + ' mutual funds total')

        elif method == 4:
            listOfStocks = []
            url = 'https://www.thestreet.com/topic/21421/top-rated-mutual-funds.html'
            headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'}
            cprint('GET:' + url, 'white', attrs=['dark'])
            with Halo(spinner='dots'):
                f = requests.get(url, headers=headers)
            Functions.fromCache(f)
            raw_html = f.text
            soup = BeautifulSoup(raw_html, 'html.parser')

            file = open('thestreet-stocks.txt', 'w')
            r = soup.find_all('a')
            for k in r:
                if len(k.text.strip()) == 5:
                    n = re.findall(r'^/quote/.*\.html', k['href'])
                    if len(n) != 0:
                        print(k.text.strip(), end=' ')
                        listOfStocks.append(k.text.strip())
                        file.write(str(k.text.strip()) + '\n')
            file.close()

            for i in range(0, len(listOfStocks), 1):
                stockName = listOfStocks[i].upper()
                listOfStocks[i] = Stock()
                listOfStocks[i].setName(stockName)

            print('\n' + str(len(listOfStocks)) + ' mutual funds total')

        elif method == 5:
            listOfStocks = []
            url = 'http://money.com/money/4616747/best-mutual-funds-etfs-money-50/'
            headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'}
            cprint('GET:' + url, 'white', attrs=['dark'])
            with Halo(spinner='dots'):
                f = requests.get(url, headers=headers)
            Functions.fromCache(f)
            raw_html = f.text
            soup = BeautifulSoup(raw_html, 'html.parser')

            file = open('money.com-stocks.txt', 'w')
            r = soup.find_all('td')

            for k in r:
                t = k.text.strip()
                if '(' in t and ')' in t:
                    t = t.split('(')[1]
                    t = t.split(')')[0]
                    print(t, end=' ')
                    listOfStocks.append(t)
                    file.write(str(t + '\n'))
            file.close()

            for i in range(0, len(listOfStocks), 1):
                stockName = listOfStocks[i].upper()
                listOfStocks[i] = Stock()
                listOfStocks[i].setName(stockName)

            print('\n' + str(len(listOfStocks)) + ' mutual funds total')

        elif method == 6:
            listOfStocks = []
            listOfStocksOriginal = []
            url = 'https://www.investors.com/etfs-and-funds/mutual-funds/best-mutual-funds-beating-sp-500-over-last-1-3-5-10-years/'
            headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'}
            cprint('GET:' + url, 'white', attrs=['dark'])
            with Halo(spinner='dots'):
                f = requests.get(url, headers=headers)
            Functions.fromCache(f)
            raw_html = f.text
            soup = BeautifulSoup(raw_html, 'html.parser')

            file = open('investors-stocks.txt', 'w')
            r = soup.find_all('td')

            for k in r:
                t = k.text.strip()
                if len(t) == 5 and Functions.strintIsFloat(t) is False:
                    if t not in listOfStocksOriginal or listOfStocksOriginal == []:
                        if t[-1] != '%':
                            listOfStocksOriginal.append(t)
                            print(t, end=' ')
                            listOfStocks.append(k.text.strip())
                            file.write(str(k.text.strip()) + '\n')
            file.close()

            for i in range(0, len(listOfStocks), 1):
                stockName = listOfStocks[i].upper()
                listOfStocks[i] = Stock()
                listOfStocks[i].setName(stockName)

            print('\n' + str(len(listOfStocks)) + ' mutual funds total')

        if len(listOfStocks) < 2:
            print('Please choose another method')
        else:
            found = True

    return listOfStocks


def asyncData(benchmark, listOfStocks):
    # Make list of urls to send requests to
    urlList = []
    # Benchmark
    url = ''.join(('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=',
                   benchmark.name, '&outputsize=full&apikey=', apiAV))
    urlList.append(url)

    # Stocks
    for i in range(0, len(listOfStocks), 1):
        # Alpha Vantage
        url = ''.join(('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=',
                       listOfStocks[i].name, '&outputsize=full&apikey=', apiAV))
        urlList.append(url)

    # Risk-free rate
    url = ''.join(
        ('https://www.quandl.com/api/v3/datasets/USTREASURY/LONGTERMRATES.json?api_key=', apiQuandl))
    urlList.append(url)

    # Yahoo Finance
    for i in range(0, len(listOfStocks), 1):
        url = ''.join(('https://finance.yahoo.com/quote/',
                       listOfStocks[i].name, '?p=', listOfStocks[i].name))
        urlList.append(url)
    for i in range(0, len(listOfStocks), 1):
        url = ''.join(
            ('https://finance.yahoo.com/lookup?s=', listOfStocks[i].name))
        urlList.append(url)

    # Send async requests
    print('\nSending async requests (Assuming Alpha Vantage is first choice)')
    with PoolExecutor(max_workers=3) as executor:
        for _ in executor.map(sendAsync, urlList):
            pass

    return


def sendAsync(url):
    time.sleep(random.randrange(0, 2))
    cprint('GET:' + url, 'white', attrs=['dark'])
    requests.get(url)
    return


def timeFrameInit():
    isInteger = False
    print('')
    while isInteger is False:
        print(
            'Please enter the time frame in months (<60 recommended):', end='')
        temp = input(' ')
        isInteger = Functions.stringIsInt(temp)
        if isInteger:
            if int(temp) > 1 and int(temp) < 1000:
                months = int(temp)
            elif int(temp) >= 1000:
                print('Please enter a number less than 1000')
                isInteger = False
            else:
                print('Please enter a number greater than 1')
                isInteger = False
        else:
            print('Please type an integer')

    timeFrame = months
    return timeFrame


def dataMain(listOfStocks):
    i = 0
    while i < len(listOfStocks):

        try:
            datesAndCloseList = Stock.datesAndClose(listOfStocks[i])
        except:
            print('Error retrieving data')
            datesAndCloseList = 'N/A'
        if datesAndCloseList == 'N/A':
            del listOfStocks[i]
            if len(listOfStocks) == 0:
                # print('No stocks to analyze. Ending program')
                cprint('No stocks to analyze. Ending program', 'white', 'on_red')
                exit()
        else:
            listOfStocks[i].allDates = datesAndCloseList[0]
            listOfStocks[i].allCloseValues = datesAndCloseList[1]

            # Clip list to fit time frame
            datesAndCloseList2 = Stock.datesAndCloseFitTimeFrame(
                listOfStocks[i])
            listOfStocks[i].dates = datesAndCloseList2[0]
            listOfStocks[i].closeValues = datesAndCloseList2[1]

            i += 1


def riskFreeRate():
    print('Quandl')
    url = ''.join(
        ('https://www.quandl.com/api/v3/datasets/USTREASURY/LONGTERMRATES.json?api_key=', apiQuandl))
    # https://www.quandl.com/api/v3/datasets/USTREASURY/LONGTERMRATES.json?api_key=KUh3U3hxke9tCimjhWEF

    cprint('\nGET:' + url, 'white', attrs=['dark'])
    with Halo(spinner='dots'):
        f = requests.get(url)
    Functions.fromCache(f)
    json_data = f.text
    loaded_json = json.loads(json_data)
    riskFreeRate = round(float(loaded_json['dataset']['data'][0][1]),2)
    print('Risk-free rate:', riskFreeRate, end='\n\n')

    if f.status_code != 200:
        print('Quandl not available')
        print('Returning 2.50 as risk-free rate', end='\n\n')
        # return 0.0250
        return 2.50

    return riskFreeRate


def returnMain(benchmark, listOfStocks):
    cprint('\nCalculating return statistics\n', 'white', attrs=['underline'])
    print('Getting risk-free rate from current 10-year treasury bill rates', end='\n\n')
    Stock.riskFreeRate = riskFreeRate()
    cprint(benchmark.name, 'cyan')
    benchmark.monthlyReturn = Stock.calcMonthlyReturn(benchmark)
    if benchmark.monthlyReturn == 'N/A':
        # print('Please use a lower time frame\nEnding program')
        cprint('Please use a lower time frame. Ending program', 'white', 'on_red')
        exit()
    benchmark.averageMonthlyReturn = Stock.calcAverageMonthlyReturn(benchmark)
    benchmark.standardDeviation = Stock.calcStandardDeviation(benchmark)

    # Make benchmark data global
    Stock.benchmarkDates = benchmark.dates
    Stock.benchmarkCloseValues = benchmark.closeValues
    Stock.benchmarkAverageMonthlyReturn = benchmark.averageMonthlyReturn
    Stock.benchmarkStandardDeviation = benchmark.standardDeviation

    i = 0
    while i < len(listOfStocks):
        cprint('\n' + listOfStocks[i].name, 'cyan')

        # Make sure each date has a value for both the benchmark and the stock
        list1 = []
        list2 = []
        list1.append(listOfStocks[i].dates)
        list1.append(listOfStocks[i].closeValues)
        list2.append(Stock.benchmarkDates)
        list2.append(Stock.benchmarkCloseValues)
        temp = Functions.removeExtraDatesAndCloseValues(list1, list2)
        listOfStocks[i].datesMatchBenchmark = temp[0][0]
        listOfStocks[i].closeValuesMatchBenchmark = temp[0][1]
        benchmarkMatchDatesAndCloseValues = temp[1]

        # Calculate everything for each stock
        listOfStocks[i].monthlyReturn = Stock.calcMonthlyReturn(
            listOfStocks[i])
        if listOfStocks[i].monthlyReturn == 'N/A':
            cprint('Removing ' +
                   listOfStocks[i].name + ' from list of stocks', 'yellow')
            del listOfStocks[i]
            if len(listOfStocks) == 0:
                # print('No stocks fit time frame. Ending program')
                cprint('No stocks fit time frame. Ending program',
                       'white', 'on_red')
                exit()
        else:
            listOfStocks[i].averageMonthlyReturn = Stock.calcAverageMonthlyReturn(
                listOfStocks[i])
            listOfStocks[i].correlation = Stock.calcCorrelation(
                listOfStocks[i], benchmarkMatchDatesAndCloseValues[1])
            listOfStocks[i].standardDeviation = Stock.calcStandardDeviation(
                listOfStocks[i])
            listOfStocks[i].downsideDeviation = Stock.calcDownsideDeviation(
                listOfStocks[i])
            listOfStocks[i].kurtosis = Stock.calcKurtosis(
                listOfStocks[i])
            listOfStocks[i].skewness = Stock.calcSkewness(
                listOfStocks[i])
            listOfStocks[i].beta = Stock.calcBeta(listOfStocks[i])
            listOfStocks[i].alpha = Stock.calcAlpha(listOfStocks[i])
            listOfStocks[i].sharpe = Stock.calcSharpe(listOfStocks[i])
            listOfStocks[i].sortino = Stock.calcSortino(listOfStocks[i])
            listOfStocks[i].treynor = Stock.calcTreynor(listOfStocks[i])
            # listOfStocks[i].linearRegression = Stock.calcLinearRegression(
            #     listOfStocks[i])

            i += 1

    cprint('\nNumber of stocks that fit time frame: ' +
           str(len(listOfStocks)), 'green')
    if len(listOfStocks) < 2:
        # print('Cannot proceed to the next step. Exiting program')
        cprint('Unable to proceed. Exiting program',
               'white', 'on_red')
        exit()


def outlierChoice():
    print('\nWould you like to remove indicator outliers?')
    return Functions.trueOrFalse()


def indicatorInit():
    # Runs correlation or regression study
    indicatorFound = False
    listOfIndicators = ['Expense Ratio',
                        'Market Capitalization', 'Turnover', 'Persistence']
    print('\n', end='')
    print('List of indicators:')
    for i in range(0, len(listOfIndicators), 1):
        print('[' + str(i + 1) + '] ' + listOfIndicators[i])
    while indicatorFound is False:
        indicator = str(input('Choose an indicator from the list: '))

        # indicator = 'expense ratio' # TESTING

        if Functions.stringIsInt(indicator):
            if int(indicator) <= 4 and int(indicator) > 0:
                indicator = listOfIndicators[int(indicator)-1]
                indicatorFound = True
        else:
            indicatorFormats = [
                indicator.upper(), indicator.lower(), indicator.title()]
            for i in range(0, len(indicatorFormats), 1):
                for j in range(0, len(listOfIndicators), 1):
                    if listOfIndicators[j] == indicatorFormats[i]:
                        indicator = listOfIndicators[j]
                        indicatorFound = True
                        break

        if indicatorFound is False:
            print('Please choose a number from 1 to', len(
                listOfIndicators), 'or type an answer')

    return indicator


def calcIndicatorCorrelation(listOfIndicatorValues, listOfReturns):
    correlationList = []
    for i in range(0, len(listOfReturns), 1):
        correlation = np.corrcoef(
            listOfIndicatorValues, listOfReturns[i])[0, 1]
        correlationList.append(correlation)
    return correlationList


def calcIndicatorRegression(listOfIndicatorValues, listOfReturns):
    regressionList = []
    x = np.array(listOfIndicatorValues)
    for i in range(0, len(listOfReturns), 1):
        y = np.array(listOfReturns[i])

        # Estimate coefficients
        # number of observations/points
        n = np.size(x)

        # mean of x and y vector
        m_x, m_y = np.mean(x), np.mean(y)

        # calculating cross-deviation and deviation about x
        SS_xy = np.sum(y*x) - n*m_y*m_x
        SS_xx = np.sum(x*x) - n*m_x*m_x

        # calculating regression coefficients
        b_1 = SS_xy / SS_xx
        b_0 = m_y - b_1*m_x

        b = [b_0, b_1]

        regression = []
        regression.append(b[0])
        regression.append(b[1])
        regressionList.append(regression)

        if Stock.plotIndicatorRegression:
            plot_regression_line(x, y, b, i)

    return regressionList


def plot_regression_line(x, y, b, i):
    # plotting the actual points as scatter plot
    plt.scatter(x, y, color="m",
                marker="o", s=30)

    # predicted response vector
    y_pred = b[0] + b[1]*x

    # plotting the regression line
    plt.plot(x, y_pred, color="g")

    # putting labels
    listOfReturnStrings = ['Average Monthly Return',
                           'Sharpe Ratio', 'Sortino Ratio', 'Treynor Ratio', 'Alpha']

    plt.title(Stock.indicator + ' and ' + listOfReturnStrings[i])
    if Stock.indicator == 'Expense Ratio' or Stock.indicator == 'Turnover':
        plt.xlabel(Stock.indicator + ' (%)')
    elif Stock.indicator == 'Persistence':
        plt.xlabel(Stock.indicator + ' (Difference in average monthly return)')
    elif Stock.indicator == 'Market Capitalization':
        plt.xlabel(Stock.indicator + ' (millions)')
    else:
        plt.xlabel(Stock.indicator)

    if i == 0:
        plt.ylabel(listOfReturnStrings[i] + ' (%)')
    else:
        plt.ylabel(listOfReturnStrings[i])

    # function to show plot
    try:
        t = Stock.timePlotIndicatorRegression
        plt.show(block=False)
        for i in range(t, 0, -1):
            if i == 1:
                sys.stdout.write('Keeping plot open for ' +
                                 str(i) + ' second \r')
            else:
                sys.stdout.write('Keeping plot open for ' +
                                 str(i) + ' seconds \r')
            plt.pause(1)
            sys.stdout.flush()
        sys.stdout.write('                                                 \r')
        sys.stdout.flush()
        plt.close()
    except:
        sys.stdout.write('                                                 \r')
        sys.stdout.flush()


def persistenceTimeFrame():
    print('\nTime frame you chose was', Stock.timeFrame, 'months')
    persTimeFrameFound = False
    while persTimeFrameFound is False:
        persistenceTimeFrame = str(
            input('Please choose how many months to measure persistence: '))
        if Functions.stringIsInt(persistenceTimeFrame):
            if int(persistenceTimeFrame) > 0 and int(persistenceTimeFrame) < Stock.timeFrame - 1:
                persistenceTimeFrame = int(persistenceTimeFrame)
                persTimeFrameFound = True
            else:
                print('Please choose a number between 0 and',
                      Stock.timeFrame, end='\n')
        else:
            print('Please choose an integer between 0 and',
                  Stock.timeFrame, end='\n')

    return persistenceTimeFrame


def indicatorMain(listOfStocks):
    cprint('\n' + str(Stock.indicator) + '\n', 'white', attrs=['underline'])

    listOfStocksIndicatorValues = []

    i = 0
    while i < len(listOfStocks):
        cprint(listOfStocks[i].name, 'cyan')
        if Stock.indicator == 'Persistence':
            listOfStocks[i].indicatorValue = Stock.calcPersistence(
                listOfStocks[i])
        else:
            try:
                listOfStocks[i].indicatorValue = Stock.scrapeYahooFinance(
                    listOfStocks[i])
            except:
                print('Error retrieving indicator data')
                print('\nWould you like to enter a ' + str(Stock.indicator.lower()
                                                           ) + ' value for ' + str(listOfStocks[i].name) + '?')
                r = Functions.trueOrFalse()
                if r is False:
                    listOfStocks[i].indicatorValue = 'Remove'
                else:
                    listOfStocks[i].indicatorValue = 'N/A'

        if listOfStocks[i].indicatorValue == 'N/A':
            listOfStocks[i].indicatorValue = Stock.indicatorManual(
                listOfStocks[i])
        elif listOfStocks[i].indicatorValue == 'Stock' or listOfStocks[i].indicatorValue == 'Remove':
            cprint('Removing ' +
                   listOfStocks[i].name + ' from list of stocks', 'yellow')
            del listOfStocks[i]
            if len(listOfStocks) < 2:
                # print('Not able to go to the next step. Ending program')
                cprint('Unable to proceed. Ending program',
                       'white', 'on_red')
                exit()
        else:
            listOfStocks[i].indicatorValue = float(
                listOfStocks[i].indicatorValue)
            listOfStocksIndicatorValues.append(listOfStocks[i].indicatorValue)
            i = i + 1
        print('')

    # Remove outliers
    if Stock.removeOutliers:
        cprint('\nRemoving outliers\n', 'white', attrs=['underline'])
        temp = Functions.removeOutliers(listOfStocksIndicatorValues)
        if temp[0] == listOfStocksIndicatorValues:
            print('No indicator outliers\n')
        else:
            print('First quartile:', temp[2], ', Median:', temp[3],
                  ', Third quartile:', temp[4], 'Interquartile range:', temp[5])
            # print('Original list:', listOfStocksIndicatorValues)
            listOfStocksIndicatorValues = temp[0]
            i = 0
            while i < len(listOfStocks):
                for j in temp[1]:
                    if listOfStocks[i].indicatorValue == j:
                        cprint('Removing ' + listOfStocks[i].name + ' because it has a ' + str(
                            Stock.indicator.lower()) + ' value of ' + str(listOfStocks[i].indicatorValue), 'yellow')
                        del listOfStocks[i]
                        i = i - 1
                        break
                i += 1
            # print('New list:', listOfStocksIndicatorValues, '\n')
            print('')

    # Calculate data
    cprint('Calculating correlation and linear regression\n',
           'white', attrs=['underline'])

    listOfReturns = []  # A list that matches the above list with return values [[averageMonthlyReturn1, aMR2, aMR3], [sharpe1, sharpe2, sharpe3], etc.]
    tempListOfReturns = []
    for i in range(0, len(listOfStocks), 1):
        tempListOfReturns.append(listOfStocks[i].averageMonthlyReturn)
    listOfReturns.append(tempListOfReturns)
    tempListOfReturns = []
    for i in range(0, len(listOfStocks), 1):
        tempListOfReturns.append(listOfStocks[i].sharpe)
    listOfReturns.append(tempListOfReturns)
    tempListOfReturns = []
    for i in range(0, len(listOfStocks), 1):
        tempListOfReturns.append(listOfStocks[i].sortino)
    listOfReturns.append(tempListOfReturns)
    tempListOfReturns = []
    for i in range(0, len(listOfStocks), 1):
        tempListOfReturns.append(listOfStocks[i].treynor)
    listOfReturns.append(tempListOfReturns)
    tempListOfReturns = []
    for i in range(0, len(listOfStocks), 1):
        tempListOfReturns.append(listOfStocks[i].alpha)
    listOfReturns.append(tempListOfReturns)

    # Create list of each indicator (e.g. expense ratio)
    listOfIndicatorValues = []
    for i in range(0, len(listOfStocks), 1):
        listOfIndicatorValues.append(listOfStocks[i].indicatorValue)

    Stock.indicatorCorrelation = calcIndicatorCorrelation(
        listOfIndicatorValues, listOfReturns)

    listOfReturnStrings = ['Average Monthly Return',
                           'Sharpe Ratio', 'Sortino Ratio', 'Treynor Ratio', 'Alpha']
    for i in range(0, len(Stock.indicatorCorrelation), 1):
        print('Correlation for ' + Stock.indicator.lower() + ' and ' +
              listOfReturnStrings[i].lower() + ': ' + str(Stock.indicatorCorrelation[i]))

    Stock.indicatorRegression = calcIndicatorRegression(
        listOfIndicatorValues, listOfReturns)
    print('\n', end='')
    for i in range(0, len(Stock.indicatorCorrelation), 1):
        formula = ''.join(
            ('f(x) = ', str(round(float(Stock.indicatorRegression[i][0]), 2)), 'x + ', str(round(float(Stock.indicatorRegression[i][1]), 2))))
        print('Linear regression equation for ' + Stock.indicator.lower() + ' and ' +
              listOfReturnStrings[i].lower() + ': ' + formula)


def checkConfig(fileName):
    if Functions.fileExists(fileName) is False:
        return 'N/A'
    file = open(fileName, 'r')
    n = file.read()
    file.close()
    if Functions.validateJson(n) is False:
        print('Config file is not valid')
        return 'N/A'
    t = json.loads(n)
    r = t['Config']
    return r


def continueProgram():
    found = False
    print('Would you like to rerun the program?')
    return Functions.trueOrFalse()


def plotIndicatorRegression():
    if Functions.detectDisplay():
        if Functions.checkPackage('matplotlib') is False:
            print(
                'matplotlib is not installed. \nIf you would like to install' +
                ' it (and have a display), run `pip install matplotlib`')
            Stock.plotIndicatorRegression = False
        else:
            print('\nWould you like to plot indicator linear regression '
                  'results?')
            plotLinear = Functions.trueOrFalse()
            if plotLinear:
                Stock.plotIndicatorRegression = True
            else:
                Stock.plotIndicatorRegression = False
    else:
        Stock.plotIndicatorRegression = False

    # Ask for how long
    Stock.timePlotIndicatorRegression = 60
    '''
    if Stock.plotIndicatorRegression:
        timeFound = False
        print('')
        while timeFound is False:
            x = str(input('How long would you like to keep the graph up (seconds)? '))
            if Functions.stringIsInt(x):
                if int(x) > 0:
                    Stock.timePlotIndicatorRegression = int(x)
                    timeFound = True
                else:
                    print('Please choose a number greater than zero')
            else:
                print('Please choose an integer')
    '''


def main():
    '''
    Check config file for errors and if not, then use values
    #! Only use this if you know it is exactly correct. I haven't spent much
    #! time debugging this
    '''
    Stock.config = checkConfig('config.json')

    runningProgram = True
    while runningProgram:
        if Stock.config == 'N/A':
            # Check that all required packages are installed
            packagesInstalled = Functions.checkPackages(
                ['numpy', 'requests', 'bs4', 'requests_cache', 'halo'])
            if not packagesInstalled:
                exit()
            else:
                print('All required packages are installed')

            # Check python version is above 3.3
            pythonVersionGood = Functions.checkPythonVersion()
            if not pythonVersionGood:
                exit()

            # Test internet connection
            internetConnection = Functions.isConnected()
            if not internetConnection:
                exit()
            else:
                Functions.getJoke()
                # Functions.getWeather()

            # Choose benchmark and makes it class Stock
            benchmark = benchmarkInit()
            # Add it to a list to work with other functions
            benchmarkAsList = [benchmark]

            # Asks for stock(s) ticker and makes them class Stock
            listOfStocks = stocksInit()

            # Determine time frame (Years)
            timeFrame = timeFrameInit()
            Stock.timeFrame = timeFrame

            # Choose indicator
            Stock.indicator = indicatorInit()
            # Choose time frame for initial persistence
            if Stock.indicator == 'Persistence':
                Stock.persTimeFrame = persistenceTimeFrame()

            # Choose whether to remove outliers or not
            Stock.removeOutliers = outlierChoice()

            # Check if matplotlib is installed and if so, ask user if
            # they want to plot and for how long
            plotIndicatorRegression()

        else:
            if Stock.config['Check Packages'] is not False:
                packagesInstalled = Functions.checkPackages(
                    ['numpy', 'requests', 'bs4', 'requests_cache', 'halo'])
                if not packagesInstalled:
                    exit()
                else:
                    print('All required packages are installed')

            if Stock.config['Check Python Version'] is not False:
                pythonVersionGood = Functions.checkPythonVersion()
                if not pythonVersionGood:
                    exit()

            if Stock.config['Check Internet Connection'] is not False:
                internetConnection = Functions.isConnected()
                if not internetConnection:
                    exit()
            if Stock.config['Get Joke'] is not False:
                Functions.getJoke()

            benchmarksTicker = ['SPY', 'DJIA', 'VTHR', 'EFT']
            if Stock.config['Benchmark'] in benchmarksTicker:
                benchmark = Stock()
                benchmark.setName(str(Stock.config['Benchmark']))
                benchmarkAsList = [benchmark]
            else:
                benchmark = benchmarkInit()
                benchmarkAsList = [benchmark]

            listOfStocks = stocksInit()

            if int(Stock.config['Time Frame']) >= 2:
                timeFrame = int(Stock.config['Time Frame'])
            else:
                timeFrame = timeFrameInit()
            Stock.timeFrame = timeFrame  # Needs to be a global variable for all stocks

            indicators = ['Expense Ratio',
                          'Market Capitalization', 'Turnover', 'Persistence']
            if Stock.config['Indicator'] in indicators:
                Stock.indicator = Stock.config['Indicator']
            else:
                Stock.indicator = indicatorInit()

            if Stock.indicator == 'Persistence':
                Stock.persTimeFrame = persistenceTimeFrame()

            # Choose whether to remove outliers or not
            if Stock.config['Remove Outliers'] is not False:
                Stock.removeOutliers = True
            else:
                Stock.removeOutliers = outlierChoice()

        # Send async request to AV for listOfStocks and benchmark
        # asyncData(benchmark, listOfStocks)

        # Gather data for benchmark and stock(s)
        cprint('\nGathering data', 'white', attrs=['underline'])
        dataMain(benchmarkAsList)
        dataMain(listOfStocks)

        # Calculate return for benchmark and stock(s)
        returnMain(benchmark, listOfStocks)

        # Choose indicator and calculate correlation with indicator
        indicatorMain(listOfStocks)

        # Decide if running program again
        print('')
        runningProgram = continueProgram()
        print('')

    print('Goodbye!\n')
    exit()


if __name__ == "__main__":
    main()
Fetching token
?