-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinternet.py
More file actions
3913 lines (3454 loc) · 169 KB
/
Copy pathinternet.py
File metadata and controls
3913 lines (3454 loc) · 169 KB
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 sys
import os
import time
#Web Driver
import selenium
from selenium import webdriver
from seleniumwire import webdriver as wire_webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.select import Select
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains as ac
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import multiprocessing
import threading
import urllib3
import OpenSSL
from io import StringIO
import gc
import pymysql
# Parsing HTML
import requests
import copy
from math import isnan, nan
#Yahoo Financials
from yahoofinancials import YahooFinancials as yf
import yfinance
import pandas_datareader as pdr
import pandas_datareader.data as data
import pandas as pd
from sqlalchemy import create_engine, text
import timestring
# Excel operations
#import csv
import xlrd
import xlwt
# Date
import datetime
from datetime import datetime as dt, timedelta
from dateutil.relativedelta import relativedelta
from datetime import date
#List Files
from fractions import Fraction
import smtplib
import re
from bs4 import BeautifulSoup
import pprint
import excel
import conf
from datastructures import *
import parse_html
import DB
from common import *
import hdf5
stop_thread=False
br=None
def get_ticker(symbol):
return yfinance.Ticker(symbol)
def get_stock_price_data(country, tick, symbol, symbols, stk, db, sql_engine, proxy=False, vpn_event=None, write_to_db=True):
ret = False
df = pd.DataFrame()
collection = DB.get_collection(country, db)
try:
today=dt.now()
end=dt.now().date()# - timedelta(7)
#Updating the price and volume for the first time
if stk['bscs']['symbol'] in US_indices.keys():
index = True
symbol = US_indices[stk['bscs']['symbol']]
else:
index = False
symbol = stk['bscs']['symbol']
#symbol = '/' + stk['bscs']['symbol']
table = DB.get_symbol_table_name(symbol)
if len(symbols) == 0 or symbol.replace('-','.').replace('_','.') not in symbols:
# Check if symbol is ending with +, =, -
# Delete those junk symbols from mongodb
if re.match(r'.*[\+|\=|\-]$', symbol):
print("Deleting Junk Symbol: %r" %(symbol))
if write_to_db:
db.US_Stocks.remove({"bscs.symbol" : symbol})
db.US_Stocks_List.remove({"symbol" : symbol})
else:
start = dt.strptime("1970-01-01", "%Y-%m-%d").date()
print("New symbol: getting data for %r from yahoo" %(stk['bscs']['symbol']))
df = hdf5.get_stock_data(country, stk, start, end, vpn_event, tick=tick, proxy=proxy)
#df = remove_df_duplicates(df)
if not df.empty:
df['Date'] = df.index.strftime("%Y-%m-%d")
df.index = df['Date'] #Is it required?
print("mysql: %s: %s"%(symbol,stk['bscs']['name']))
if write_to_db:
DB.check_n_write_to_sql(sql_engine, DB.get_symbol_table_name(symbol), copy.deepcopy(df), list(df.columns))
# Reset mysql_price_failcount
DB.update_field(collection, symbol, "failcount.mysql_price_failcount", 0)
else:
if write_to_db:
DB.update_field(collection, symbol, "ignore", "YES")
DB.update_price_failcount(stk, country, df=True)
#Updating today's price and volume
else:
#if index:
if True:
# Yahoo Finance sometimes returns wrong volume data for the latest date.
# Check and delete record.
# Will be populated again the below code.
# Happens only when small set of data is requested.
DB.check_volume_of_last_record(sql_engine, DB.get_symbol_table_name(stk['bscs']['symbol']))
else:
pass
query='select Date from ' + table + ' order by Date DESC limit 1'
rdf = DB.read_from_sql(query, sql_engine)
# Read the existing data of the symbol
if rdf.empty:
PRINT_ERR("update_dataframe_price_volume: %s: No data. Read from the start" %(stk['bscs']['symbol']))
start = dt.strptime("1970-01-01", "%Y-%m-%d").date()
else:
#get timestamp of the last entry
start = dt.strptime(rdf['Date'][0], "%Y-%m-%d").date()
if start < end:
#if True:
# If date difference is less than a week, get atleast
# a week of prices. yahoofinance sometimes misbehaves
# in case of a shorter timespan and returns inconsistent data.
# Min of week is a safer timespan.
# Though you get a week data, insert only the entries that are missing.
# Taken care below.
if end-start < timedelta(10):
start = end - timedelta(10)
df = hdf5.get_stock_data(country, stk, start, end, vpn_event, tick=tick, proxy=proxy)
# Sometimes yahoo gives wrong data. Wrong data will have volume as 0. Discard those rows
#df.drop(df[df['Volume']==0].index, inplace=True)
#e=time.time()
#print("got data for %r from yahoo, elapsed time: %r sec" %(stk['bscs']['symbol'], (e-s)))
#print("two: sym: %r, start: %r, end: %r" %(stk['bscs']['symbol'], str(start), str(end)))
if not df.empty:
ret=True
xdf=copy.deepcopy(df)
#rdf = rdf.append(df)
#rdf = remove_df_duplicates(rdf)
#df['Symbol'] = symbol
df['Date'] = df.index.strftime("%Y-%m-%d")
df.index = df['Date'] #Is it required?
#df = df[~df.Date.isin(rdf.Date)]
# Get the data starting from the next day of the last entry in MySQL database
#df=df.loc[rdf['Date'][0]:].drop(rdf['Date'][0])
if not df.empty:
try:
if not rdf.empty and rdf['Date'][0] in list(df.index):
index = df.index.get_loc(rdf['Date'][0])
df = df[index+1:]
except Exception as E:
print("internet.py: %r: update_dataframe_price_volume exception: %r"%(symbol, str(E)))
print("internet.py: %r: update_dataframe_price_volume exception, df: %r"%(symbol, df))
print("internet.py: %r: update_dataframe_price_volume exception, xdf: %r"%(symbol, xdf))
print("internet.py: %r: update_dataframe_price_volume exception, rdf: %r"%(symbol, rdf))
if not df.empty and write_to_db:
#print("Writing to sql prices for %r" %(symbol))
#print("writing data for %r to mysql" %(stk['bscs']['symbol']))
#s=time.time()
print("mysql get_stock_data(): %s: %s"%(symbol,stk['bscs']['name']))
#DB.write_to_sql(sql_engine, table, df)
DB.mysql_update_table(sql_engine, table, df, insert=True)
#DB.update_field(collection, symbol, "dates.mysql_price_date", dt.combine(dt.now(), dt.min.time()))
# Reset mysql_price_failcount
DB.update_field(collection, symbol, "failcount.mysql_price_failcount", 0)
#threading.Thread(target=internet.update_price_change, args=(country, collection, stk['bscs']['symbol'], None, sql_engine,)).start()
#e=time.time()
#print("done data for %r to mysql, elapsed time: %r sec" %(stk['bscs']['symbol'], (e-s)))
#print("Wrote to sql prices for %r" %(symbol))
##if index:
## rdf = update_percent_change(rdf)
##Update Betas
##if stk['bscs']['symbol'] not in India_indices.keys() and stk['bscs']['symbol'] not in US_indices.keys():
## rdf = hdf_get_beta(country, symbol, rdf)
## #DB.update_stock_betas2(country, stk, df=rdf)
#write_to_hdf(country, rdf, symbol)
#write_to_hdf_store(country, rdf, stk['bscs']['symbol'])
# Update the date on which the price is updated
#DB.update_field(collection, symbol, "ignore", "NO")
else:
PRINT_ERR("df empty for %r" %(symbol))
DB.update_field(collection, symbol, "ignore", "YES")
#DB.update_field(collection, symbol, "dates.mysql_price_date", dt.combine(dt.now(), dt.min.time()))
DB.update_price_failcount(stk, country, df=True)
else:
ret = True
if write_to_db:
DB.update_field(collection, symbol, "dates.mysql_price_date", dt.combine(dt.now(), dt.min.time()))
finally:
return ret, df
def open_browser(head=None, wiredriver=False):
profile = webdriver.FirefoxProfile()
capabilities = DesiredCapabilities.FIREFOX
options = Options()
if head == 'headless':
options.add_argument('--headless')
profile.set_preference("browser.cache.disk.enable", False)
profile.set_preference("browser.cache.memory.enable", False)
profile.set_preference("browser.cache.offline.enable", False)
profile.set_preference("network.http.use-cache", False)
profile.set_preference("browser.privatebrowsing.autostart", True)
profile.set_preference("dom.webnotifications.enabled", False)
#profile.set_preference('browser.download.folderList', 2) # custom location
#profile.set_preference('browser.download.manager.showWhenStarting', False)
#profile.set_preference('browser.download.manager.focusWhenStarting', False)
#profile.set_preference('browser.download.manager.closeWhenDone', True)
#profile.set_preference('browser.download.manager.showAlertComplete', False)
#profile.set_preference('browser.download.manager.useWindow', False)
#profile.set_preference('services.sync.prefs.sync.browser.download.manager.showWhenStarting', False)
#profile.set_preference('browser.download.useDownloadDir', True)
#profile.set_preference('browser.download.dir', '/tmp')
#profile.set_preference("browser.helperApps.alwaysAsk.force", False);
#profile.set_preference("browser.helperApps.neverAsk.openFile", "text/plain, application/octet-stream, application/binary, text/csv, application/csv, application/excel, text/comma-separated-values, text/xml, application/xml");
#profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "text/plain, application/octet-stream, application/binary, text/csv, application/csv, application/excel, text/comma-separated-values, text/xml, application/xml")
#profile.set_preference('csvjs.disabled', True)
#profile.set_preference('pdfjs.disabled', True)
#profile.add_extension(extension='/home/vpetla/.mozilla/firefox/ekwma54v.default-release/extensions/jid1-P34HaABBBpOerQ@jetpack.xpi')
#profile.add_extension(extension='/home/vpetla/.mozilla/firefox/ekwma54v.default-release/extensions/{246C9D65-51E6-4B0C-9CCF-B081B7BF9242}.xpi')
if wiredriver:
browser = wire_webdriver.Firefox(firefox_profile=profile, options=options, capabilities=capabilities)
else:
browser = webdriver.Firefox(firefox_profile=profile, options=options, capabilities=capabilities)
#browser.set_page_load_timeout(30)
#browser.maximize_window()
return browser
def close_browser(br):
#br.close()
br.delete_all_cookies()
br.quit()
def send_email(message):
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.ehlo()
s.starttls()
# Authentication
s.login("askpvenkatesh@gmail.com", "tasche#gm")
# message to be sent
message = "Hello World."
# sending the mail
s.sendmail("askpvenkatesh@gmail.com", "askpvenkatesh@gmail.com", message)
# terminating the session
s.quit()
def send_email2(user, recipient, subject, body):
try:
FROM = user
TO = recipient if isinstance(recipient, list) else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
#message = """From: %s\nTo: %s\nSubject: %s\n\n%s
#""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
message = MIMEMultipart('alternative')
message['Subject'] = subject
message['From'] = user
message['To'] = recipient
message.attach(MIMEText(body, 'html'))
#server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server = smtplib.SMTP("smtp.gmail.com", 587)
#server.set_debuglevel(1)
server.ehlo()
server.starttls()
pwd="poggfuvtowfdtsyp"
server.login(user, pwd)
server.sendmail(FROM, TO, message.as_string())
#server.sendmail(FROM, TO, message)
server.close()
print('successfully sent the mail')
except Exception as E:
print("Failed to send email, err: %s", str(E))
pass
def index_change(country, sym, name, num_days, data_type):
change = 0
symbol = sym.replace('.', '-')
if data_type == 'HOT':
end = dt.now()
diff = end.weekday() - 4
#If weekend
if diff > 0:
end = end - timedelta(days=diff+1)
start = end - timedelta(days=num_days)
diff = start.weekday() - 4
if diff > 0:
start = start - timedelta(days=diff+1)
try:
#print("Symbol: %s, Name: %s" %(sym, name))
#read = pdr.DataReader(symbol, 'morningstar', start, end)
read = pdr.DataReader(symbol, 'yahoo', start, end)
except pdr._utils.RemoteDataError:
PRINT_ERR("Unable to get data for %s"%(sym))
return None
except KeyError:
PRINT_ERR("Unable to get data for %s"%(sym))
return None
en_price = read.iat[-1, read.columns.get_loc('Adj Close')]
st_price = read.iat[0, read.columns.get_loc('Adj Close')]
change = en_price/st_price - 1
return change, round((en_price-st_price), 2)
# Deprecated. Use hdf_price_change().
def price_change(country, sym, name, num_days, data_type):
change,diff=index_change(country,sym,name,num_days,data_type)
return change
def check_price_change(country, sym, stock, name, change, req_change, count, sheet, sheet_type, excel_type):
if change >= req_change:
#print("sym: %s, name: %s, change: %d percent" %(sym, name, change*100))
count += 1
if excel_type == 'EXCEL':
excel.write_to_price_change_excel(count, sheet, stock, sheet_type)
elif change < -(req_change):
#print("sym: %s, name: %s, change: -%d percent" %(sym, name, change*100))
count += 1
if excel_type == 'EXCEL':
excel.write_to_price_change_excel(count, sheet, stock, sheet_type)
return count
def price_suprise(country, collection, stock, sym, name, change_percent, xl, criteria, db_type, excel_type):
#st_price = read.iat[0, read.columns.get_loc('Close')]
#en_price = read.iat[-1, read.columns.get_loc('Close')]
if criteria == ALL or criteria & YEAR:
change = hdf5.hdf_price_change(country, sym, 365)
if change:
if db_type == 'SYNC_DB':
DB.update_field(collection, sym, "price_change.year", change)
if excel_type == 'EXCEL':
sheet = xl.get_sheet(0)
else:
sheet = None
conf.PR_YR_COUNT = check_price_change(country, sym, stock, name, change, 0.40, conf.PR_YR_COUNT, sheet, 'YEAR', excel_type)
if criteria == ALL or criteria & QUARTER:
change = hdf5.hdf_price_change(country, sym, 90)
if change:
if db_type == 'SYNC_DB':
DB.update_field(collection, sym, "price_change.quarter", change)
if excel_type == 'EXCEL':
sheet = xl.get_sheet(1)
else:
sheet = None
conf.PR_QR_COUNT = check_price_change(country, sym, stock, name, change, 0.30, conf.PR_QR_COUNT, sheet, 'QUARTER', excel_type)
if criteria == ALL or criteria & MONTH:
change = hdf5.hdf_price_change(country, sym, 30)
if change:
if db_type == 'SYNC_DB':
DB.update_field(collection, sym, "price_change.month", change)
if excel_type == 'EXCEL':
sheet = xl.get_sheet(2)
else:
sheet = None
conf.PR_MON_COUNT = check_price_change(country, sym, stock, name, change, 0.20, conf.PR_MON_COUNT, sheet, 'MONTH', excel_type)
if criteria == ALL or criteria & WEEK:
change = hdf5.hdf_price_change(country, sym, 7)
if change:
if db_type == 'SYNC_DB':
DB.update_field(collection, sym, "price_change.week", change)
if excel_type == 'EXCEL':
sheet = xl.get_sheet(3)
else:
sheet = None
conf.PR_WEEK_COUNT = check_price_change(country, sym, stock, name, change, 0.10, conf.PR_WEEK_COUNT, sheet, 'WEEK', excel_type)
if criteria == ALL or criteria & DAY:
change = hdf5.hdf_price_change(country, sym, 1)
if change:
if db_type == 'SYNC_DB':
DB.update_field(collection, sym, "price_change.day", change)
if excel_type == 'EXCEL':
sheet = xl.get_sheet(4)
else:
sheet = None
conf.PR_DAY_COUNT = check_price_change(country, sym, stock, name, change, 0.10, conf.PR_DAY_COUNT, sheet, 'DAY', excel_type)
DB.update_field(collection, sym, "price_change.date", str(dt.now()))
def get_change(df, field):
if df.iloc[0][field] and not isnan(df.iloc[0][field]):
return df.iloc[0][field]
else:
return df.iloc[1][field]
# Fix mess caused by update_price_change() caused by the query
# query = 'select `Date`, `Adj Close` from %s where `Day Change` is NULL order by Date'
def nullify_price_change_error_stk(country, collection, sym, sql_engine):
table_name = DB.get_symbol_table_name(sym)
if DB.mysql_exists_table(sql_engine, table_name):
query = 'select `Date`, `Adj Close` from %s where `Day Change` = `Whole Change`' %(table_name)
df = DB.read_from_sql(query, sql_engine)
if not df.empty:
for index, d in df.iterrows():
end_date = str(pd.to_datetime(index).date())
query = 'select Date, `Adj Close`, `Day Change` from {} where Date = \'{}\''.format(table_name, end_date)
cur_df = DB.read_from_sql(query, sql_engine)
query = 'select Date, `Adj Close` from {} where `Date` < \'{}\' order by Date desc limit 1'.format(table_name, end_date)
prev_df = DB.read_from_sql(query, sql_engine)
price_change = round(cur_df['Adj Close'][-1]/prev_df['Adj Close'][-1] - 1, len(str(cur_df['Day Change'][-1]).split('.')[1]))
if abs(abs(price_change) - abs(cur_df['Day Change'][-1])) > 0.05: # Atleast 5% difference
# Nullify from here to end of the table
#query = 'select * from {} where `Date` BETWEEN \'{}\' and NOW()'.format(table_name, end_date)
query = 'select `Date`, {} from {} where `Date` BETWEEN \'{}\' and NOW()'.format(', '.join(['`{}`'.format(c) for c in [*price_change_fields]]), table_name, end_date)
df2 = DB.read_from_sql(query, sql_engine)
for field in [*price_change_fields]:
df2[field] = None
print("Updating change: %r" %(cur_df))
DB.mysql_update_table(sql_engine, table_name, df2, check=True)
break
def nullify_price_change_errors():
country = 'US'
c = DB.open_db_client()
db = c['Stocks']
collection = DB.get_collection(country, db)
sql_engine = DB.open_sql_connection('localhost', 'root', 'petla123', db='US_Stocks')
#stocks = collection.find({},no_cursor_timeout=True).batch_size(10).sort([["sno",1]])
symbols = DB.get_symbols_from_sql(country, sql_engine)
try:
for i, symbol in enumerate(symbols):
print("%d: %r" %(i, symbol))
nullify_price_change_error_stk(country, collection, symbol, sql_engine)
finally:
DB.close_sql_connection(sql_engine)
DB.close_db_client(c)
def identify_change_indices(params_engine, table_name, stock_dates, field):
with params_engine.connect() as conn:
result = conn.execute(text(
f"SELECT `Date` FROM {table_name} WHERE `{field}` IS NOT NULL"
))
param_valid_dates = set(row[0] for row in result)
indices = stock_dates - param_valid_dates
indices = sorted(indices)
return indices
def get_rows_from_indices(sql_engine, table_name, indices):
df = pd.DataFrame()
if indices:
CHUNK_SIZE = 1000
with sql_engine.connect() as conn:
for i in range(0, len(indices), CHUNK_SIZE):
chunk = list(indices)[i:i + CHUNK_SIZE]
placeholders = ','.join([':val' + str(j) for j in range(len(chunk))])
bind_params = {f'val{j}': chunk[j] for j in range(len(chunk))}
query = text(f"SELECT * FROM {table_name} WHERE `Date` IN ({placeholders})")
chunk_df = pd.read_sql_query(query, conn, params=bind_params)
df = pd.concat([df, chunk_df], ignore_index=True)
df.index = df.Date
return df
def calculate_percent_change(sql_engine, table_name, df, field, start_price=None):
wdf = pd.DataFrame(index=df.index[1:], columns=[field])
for index, d in df.iloc[1:].iterrows():
cur_price = d['Adj Close']
cur_date = pd.to_datetime(index).date()
cur_date_str = str(cur_date)
#wdf.loc[cur_date_str]=nan
#wdf.loc[cur_date_str]['Date'] = cur_date_str
wdf.loc[cur_date_str, 'Date'] = cur_date_str
if not start_price:
start_price = DB.mysql_get_price(sql_engine, table_name, str(cur_date - price_change_durations[field]), str(cur_date))
change = round(percent_change(start_price, cur_price),7)
wdf.loc[cur_date_str, field] = change
#wdf.loc[cur_date_str][[*price_change_fields][field_pos]] = change
wdf = wdf.dropna(axis=0)
return wdf
def insert_or_update(wdf, params_engine, table_name, field):
# Write to the database
if not wdf.empty:
#DB.mysql_update_table(params_engine, table_name, wdf)
sql = text(f"""
INSERT INTO `{table_name}` (`Date`, `{field}`)
VALUES (:date, :value)
ON DUPLICATE KEY UPDATE `{field}` = :value
""")
with params_engine.begin() as conn:
for _, row in wdf.iterrows():
result = conn.execute(sql, {
"value": float(row[field]) if pd.notnull(row[field]) else None,
"date": row['Date']
})
return
def update_price_change_field(params_engine, sql_engine, table_name, stock_dates, field, price_change_last_only, start_price=None):
indices = identify_change_indices(params_engine, table_name, stock_dates, field)
if len(indices) <= 1:
return
df = get_rows_from_indices(sql_engine, table_name, indices)
if price_change_last_only:
if not df.empty:
df = df.iloc[-1]
if df.empty:
return
wdf = calculate_percent_change(sql_engine, table_name, df, field, start_price=start_price)
insert_or_update(wdf, params_engine, table_name, field)
def update_price_change(country, stk, core, sem=None, index=False, type='Stocks', price_change_last_only=False):
#st_price = read.iat[0, read.columns.get_loc('Close')]
#en_price = read.iat[-1, read.columns.get_loc('Close')]
c = DB.open_db_client()
if type == 'Stocks':
db = c['Stocks']
collection=db.US_Stocks
sql_engine = DB.open_sql_connection('localhost', 'root', 'petla123', db='US_Stocks')
fin_engine = DB.open_sql_connection('localhost', 'vpetla', 'petla123', db='US_Stocks_Fin')
params_engine = DB.open_sql_connection('localhost', 'vpetla', 'petla123', db='US_Tech_Params')
else:
db = c['Cryptos']
collection=db.Cryptos
sql_engine = DB.open_sql_connection('localhost', 'root', 'petla123', db='Cryptos')
fin_engine = None
params_engine = None
#print("%s: Core: %r" %(sym, core))
aff = 0 | 1 << core
#print("Setting %d's affinity to core: %d" %(os.getpid(), core))
os.system("taskset -p %r %d >/dev/null 2>&1" %(str(hex(aff)), os.getpid()))
sym = ""
update = False
try:
sym = stk['bscs']['symbol']
except Exception as E:
print("update_price_change: error: %s, stk : %s" %(str(E), stk))
if isinstance(stk, dict):
if 'General' in stk.keys() and \
isinstance(stk['General'], dict) and \
'Exchange' in stk['General'].keys() and \
stk['General']['Exchange'] not in major_exchanges:
price_change_last_only=True
else:
print("internet.py:521, stk: %s" %(stk))
try:
sym = stk['bscs']['symbol']
table_name = DB.get_symbol_table_name(sym)
change = 0
if not DB.mysql_exists_table(params_engine, table_name):
DB.mysql_check_n_create_table(params_engine, table_name, primary_key=True)
if True:
print("mysql: percent_change: %s"%(sym))
table_cols = DB.mysql_get_columns_from_engine(params_engine, table_name)
missing_cols = list_difference([*price_change_fields], table_cols)
# Some price change fields are not present in the database.
# The datatype of the fields is taken from the price fields
# mentioned in the datastructures.py
if len(missing_cols) > 0:
print("%s: Adding missing columns: %r"%(table_name, missing_cols))
miss = DB.mysql_add_columns(params_engine, table_name, missing_cols, remove_spaces=False)
if miss > 0:
PRINT_ERR("Failed to add %r columns to table %r" %(miss, table_name))
PRINT_ERR("Columns: ",missing_cols)
sys.exit(1)
# Step 1: Fetch all Dates from US_Stocks
with sql_engine.connect() as conn:
result = conn.execute(text(f"SELECT `Date` FROM {table_name}"))
stock_dates = set(row[0] for row in result)
for field_pos, field in enumerate([*price_change_fields][:-2]):
update_price_change_field(params_engine, sql_engine, table_name, stock_dates, field, price_change_last_only)
if 'General' in stk.keys() and \
'IPODate' in stk['General'].keys() and \
is_val(stk['General']['IPODate']):
start_date = stk['General']['IPODate']
query = 'select `Date`, `Adj Close` from {} where Date=\'{}\' '.format(table_name, start_date)
df = DB.read_from_sql(query, sql_engine)
if df.empty:
query = 'select `Date`, `Adj Close` from {} order by Date limit 1'.format(table_name)
df = DB.read_from_sql(query, sql_engine)
else:
query = 'select `Date`, `Adj Close` from {} order by Date limit 1'.format(table_name)
df = DB.read_from_sql(query, sql_engine)
start_date = df.index[0].strftime("%Y-%m-%d")
#print(query)
query = 'select `Date`, `Adj Close` from {} order by Date limit 1'.format(table_name)
df = DB.read_from_sql(query, sql_engine)
start_price = df['Adj Close'][0]
# Whole Change
field = [*price_change_fields][-2]
update_price_change_field(params_engine, sql_engine, table_name, stock_dates, field, price_change_last_only, start_price=start_price)
# YTD Change
field = [*price_change_fields][-1]
indices = identify_change_indices(params_engine, table_name, stock_dates, field)
if len(indices) >= 1:
df = get_rows_from_indices(sql_engine, table_name, indices)
if price_change_last_only:
if not df.empty:
df = df.iloc[-1]
if not df.empty:
wdf = pd.DataFrame(index=df.index[1:], columns=[field])
for index, d in df.iloc[1:].iterrows():
cur_price = d['Adj Close']
cur_date = pd.to_datetime(index).date()
start_year = cur_date.year
cur_date_str = str(cur_date)
query = 'select Date, `Adj Close` from {} where Date = (select min(Date) from {} where Year(Date)={})'.format(table_name, table_name, start_year)
start_df = DB.read_from_sql(query, sql_engine)
if not start_df.empty:
start_price = start_df['Adj Close'][0]
wdf.loc[cur_date_str, 'Date'] = cur_date_str
change = percent_change(start_price, cur_price)
wdf.loc[cur_date_str, [*price_change_fields][-1]] = change
else:
change = nan
wdf = wdf.dropna(axis=0)
insert_or_update(wdf, params_engine, table_name, field)
query = 'select `Date`, {} from {} order by Date desc limit 2'.format(', '.join(['`{}`'.format(c) for c in [*price_change_fields]]), table_name)
df = DB.read_from_sql(query, params_engine)
change = get_change(df, 'Day Change')
DB.update_field(collection, sym, "price_change.day", change)
change = get_change(df, 'Week Change')
DB.update_field(collection, sym, "price_change.week", change)
change = get_change(df, 'Two Week Change')
DB.update_field(collection, sym, "price_change.two_week", change)
change = get_change(df, 'Month Change')
DB.update_field(collection, sym, "price_change.month", change)
change = get_change(df, 'Quarter Change')
DB.update_field(collection, sym, "price_change.quarter", change)
change = get_change(df, 'Half Year Change')
DB.update_field(collection, sym, "price_change.half_year", change)
change = get_change(df, 'Year Change')
DB.update_field(collection, sym, "price_change.year", change)
change = get_change(df, 'Five Year Change')
DB.update_field(collection, sym, "price_change.five_year", change)
change = get_change(df, 'Ten Year Change')
DB.update_field(collection, sym, "price_change.ten_year", change)
change = get_change(df, 'Whole Change')
DB.update_field(collection, sym, "price_change.whole", change)
change = get_change(df, 'YTD Change')
DB.update_field(collection, sym, "price_change.ytd", change)
end_date = str(dt.now().date())
#get 52 week high
#select max(`Adj Close`) from STKSP500 where Date between date_sub('2020-03-20', INTERVAL 1 YEAR) and '2020-03-20';
query ='select max(`Adj Close`) from {} where Date between date_sub(\'{}\', INTERVAL 1 YEAR) and \'{}\''.format(table_name, end_date, end_date)
result=sql_engine.execute(query)
high_price = result.first()[0]
#high_price = hdf5.hdf_get_high_n_days(df, 365)
DB.update_field(collection, sym, "bscs.fiftytwoweek_high", high_price)
#get 52 week low
query ='select min(`Adj Close`) from {} where Date between date_sub(\'{}\', INTERVAL 1 YEAR) and \'{}\''.format(table_name, end_date, end_date)
#query ='select min(`Adj Close`) from ' + table_name + ' where Date between Date between date_sub(%s, INTERVAL 1 YEAR);'%(end_date, end_date)
result=sql_engine.execute(query)
low_price = result.first()[0]
#low_price = hdf5.hdf_get_low_n_days(df, 365)
DB.update_field(collection, sym, "bscs.fiftytwoweek_low", low_price)
# Number of weeks
# query='select count(distinct concat(YEAR(Date), '-', WEEK(Date))) AS total_weeks from STKVFS where Date >= CURDATE() - INTERVAL 5 YEAR;'
# Number of weeks where the price is down atleast 20 percent
# query='select YEAR(Date) AS year, WEEK(Date) as week from STKHPE WHERE `Week Change` <= -0.20 AND Date >= CURDATE() - INTERVAL 5 YEAR GROUP BY YEAR(Date), WEEK(Date) HAVING COUNT(*) > 0 UNION ALL SELECT NULL AS year, COUNT(DISTINCT CONCAT(YEAR(Date), '-', WEEK(Date))) AS week FROM STKHPE WHERE `Week Change` <= -0.20 GROUP BY NULL;'
#query ='select count(Date) from {} where Date between date_sub(\'{}\', INTERVAL 3 YEAR) and \'{}\''.format(table_name, end_date, end_date)
query='select count(distinct concat(YEAR(Date), \'-\', WEEK(Date))) AS total_weeks from {} where Date >= CURDATE() - INTERVAL 5 YEAR;'.format(table_name)
rdf=pd.read_sql_query(query, params_engine)
total_weeks = rdf.iloc[0]['total_weeks']
# This also works
#result=sql_engine.execute(query)
#total_weeks = result.first()[0]
#query ='select count(Date) from {} where Date between date_sub(\'{}\', INTERVAL 3 YEAR) and \'{}\' and `Week Change` < -0.10'.format(table_name, end_date, end_date)
query='select YEAR(Date) AS year, WEEK(Date) as week from {} WHERE `Week Change` <= -0.10 AND Date >= CURDATE() - INTERVAL 5 YEAR GROUP BY YEAR(Date), WEEK(Date) HAVING COUNT(*) > 0 UNION ALL SELECT NULL AS year, COUNT(DISTINCT CONCAT(YEAR(Date), \'-\', WEEK(Date))) AS week FROM {} WHERE `Week Change` <= -0.10 GROUP BY NULL;'.format(table_name, table_name)
rdf=pd.read_sql_query(query, params_engine)
ten_percent_down_times = len(rdf.dropna())
#result=sql_engine.execute(query)
#ten_percent_down_times = result.first()[0]
#query ='select count(Date) from {} where Date between date_sub(\'{}\', INTERVAL 3 YEAR) and \'{}\' and `Week Change` < -0.20'.format(table_name, end_date, end_date)
query='select YEAR(Date) AS year, WEEK(Date) as week from {} WHERE `Week Change` <= -0.20 AND Date >= CURDATE() - INTERVAL 5 YEAR GROUP BY YEAR(Date), WEEK(Date) HAVING COUNT(*) > 0 UNION ALL SELECT NULL AS year, COUNT(DISTINCT CONCAT(YEAR(Date), \'-\', WEEK(Date))) AS week FROM {} WHERE `Week Change` <= -0.20 GROUP BY NULL;'.format(table_name, table_name)
rdf=pd.read_sql_query(query, params_engine)
twenty_percent_down_times = len(rdf.dropna())
#result=sql_engine.execute(query)
#twenty_percent_down_times = result.first()[0]
DB.update_field(collection, sym, "price_change.total_weeks", int(total_weeks))
DB.update_field(collection, sym, "price_change.ten_percent_down_times", ten_percent_down_times)
DB.update_field(collection, sym, "price_change.twenty_percent_down_times", twenty_percent_down_times)
# Get today's price
query = 'select `Adj Close` from {} order by Date desc limit 1'.format(table_name)
result=sql_engine.execute(query)
price = result.first()[0]
#price = hdf5.hdf_get_price(sym, df, dt.now().date())
if not high_price or high_price == 0:
change = 0
else:
change = (price/high_price) - 1
DB.update_field(collection, sym, "price_change.with_52week_high", change)
if not low_price or low_price == 0:
change = 0
else:
change = (price/low_price) - 1
DB.update_field(collection, sym, "price_change.with_52week_low", change)
#query = 'select max(`Adj Close`) from {}'.format(table_name)
query = 'select Date, `Adj Close` from {} where `Adj Close` = (SELECT MAX(`Adj Close`) FROM {})'.format(table_name, table_name)
#adf = DB.read_from_sql(query, sql_engine)
result = sql_engine.execute(query)
ret = result.first()
all_time_high_date = dt.strptime(ret[0], "%Y-%m-%d")
all_time_high_price = ret[1]
if not all_time_high_price or all_time_high_price == 0:
change = 0
else:
change = percent_change(all_time_high_price, price)
DB.update_field(collection, sym, "price_change.with_all_time_high", change)
DB.update_field(collection, sym, "price_change.all_time_high_price", all_time_high_price)
DB.update_field(collection, sym, "price_change.all_time_high_date", all_time_high_date)
query = 'select Date, `Adj Close` from {} where `Adj Close` = (SELECT MIN(`Adj Close`) FROM {})'.format(table_name, table_name)
#adf = DB.read_from_sql(query, sql_engine)
result = sql_engine.execute(query)
ret = result.first()
all_time_low_date = dt.strptime(ret[0], "%Y-%m-%d")
all_time_low_price = ret[1]
if not all_time_low_price or all_time_low_price == 0:
change = 0
else:
change = percent_change(all_time_low_price, price)
DB.update_field(collection, sym, "price_change.with_all_time_low", change)
DB.update_field(collection, sym, "price_change.all_time_low_price", all_time_low_price)
DB.update_field(collection, sym, "price_change.all_time_low_date", all_time_low_date)
if all_time_high_date < all_time_low_date:
change = percent_change(all_time_high_price, all_time_low_price)
else:
change = percent_change(all_time_low_price, all_time_high_price)
DB.update_field(collection, sym, "price_change.with_all_time_low_high_change", change)
if 'Highlights' in stk.keys() and 'MarketCapitalization' in stk['Highlights'].keys() and stk['Highlights']['MarketCapitalization'] != None:
if price > 0:
num_shares = stk['Highlights']['MarketCapitalization']/price
else:
num_shares = 0
all_time_high_mcap = num_shares * all_time_high_price
DB.update_field(collection, sym, "price_change.all_time_high_mcap", all_time_high_mcap)
else:
DB.update_field(collection, sym, "price_change.all_time_high_mcap", nan)
query = 'SELECT Date, Volume FROM (SELECT * FROM {} ORDER BY Date DESC LIMIT 60) AS sub ORDER BY Date ASC'.format(table_name)
df = DB.read_from_sql(query, sql_engine)
if not df.empty:
vol_mean = df['Volume'].mean()
DB.update_field(collection, sym, "price_change.avg_volume", vol_mean)
price_times_avg_vol_in_mn = round((price*vol_mean)/1000000,2)
DB.update_field(collection, sym, "price_change.price_times_avg_vol_in_mn", price_times_avg_vol_in_mn)
if 'Highlights' in stk.keys() and 'MarketCapitalizationMln' in stk['Highlights'].keys() and stk['Highlights']['MarketCapitalizationMln'] != None:
avg_vol_pcent_in_mcap_mn = round(((price*vol_mean)/(stk['Highlights']['MarketCapitalizationMln'] * 1000000))*100, 2)
DB.update_field(collection, sym, "price_change.avg_vol_pcent_in_mcap_mn",avg_vol_pcent_in_mcap_mn)
else:
DB.update_field(collection, sym, "price_change.avg_vol_in_mcap_mn", None)
else:
DB.update_field(collection, sym, "price_change.avg_volume", None)
DB.update_field(collection, sym, "price_change.price_times_avg_vol_in_mn", None)
DB.update_field(collection, sym, "price_change.avg_vol_pcent_in_mcap_mn", None)
# Update price change since last earnings date
if type == 'Stocks' and sym not in US_indices.keys():
query = 'select Symbol, Date, reportDate, marketCap, name from Nasdaq_Earnings_History where Symbol=\'{}\' order by date desc limit 2'.format(sym)
rdf = DB.read_from_sql(query, fin_engine)
if rdf.empty:
DB.update_field(collection, sym, "price_change.since_ndaq_last_earnings", None)
else:
report_date=dt.strptime(rdf.iloc[0]['reportDate'], "%Y-%m-%d")
# Future date is already updated in the database. So consider previous date
if report_date > dt.now():
report_date=dt.strptime(rdf.iloc[-1]['reportDate'], "%Y-%m-%d")
DB.update_field(collection, sym, "dates.ndaq_previous_earnings_date", report_date)
query = 'select * from {} where Date >=\'{}\' order by Date'.format(table_name, str(report_date.date()))
df = DB.read_from_sql(query, sql_engine)
change = percent_change(df.iloc[0]['Adj Close'], df.iloc[-1]['Adj Close'])
DB.update_field(collection, sym, "price_change.since_ndaq_last_earnings", change)
else:
change=None
DB.update_field(collection, sym, "price_change.day", change)
DB.update_field(collection, sym, "price_change.week", change)
DB.update_field(collection, sym, "price_change.month", change)
DB.update_field(collection, sym, "price_change.quarter", change)
DB.update_field(collection, sym, "price_change.half_year", change)
DB.update_field(collection, sym, "price_change.year", change)
DB.update_field(collection, sym, "price_change.whole", change)
DB.update_field(collection, sym, "bscs.fiftytwoweek_high", change)
DB.update_field(collection, sym, "bscs.fiftytwoweek_low", change)
DB.update_field(collection, sym, "price_change.with_52week_high", change)
DB.update_field(collection, sym, "price_change.with_52week_low", change)
DB.update_field(collection, sym, "price_change.since_last_earnings", change)
DB.update_field(collection, sym, "price_change.since_ndaq_last_earnings", None)
update = True
except Exception as E:
print("Error: price_change: %s, %s" %(stk['bscs'], str(E)))
finally:
if update:
print("price_change: sym: %s" %(sym))
DB.update_field(collection, sym, "price_change.date", dt.combine(dt.now(), dt.min.time()))
DB.close_sql_connection(sql_engine)
if fin_engine:
DB.close_sql_connection(fin_engine)
if params_engine:
DB.close_sql_connection(params_engine)
DB.close_db_client(c)
if sem:
sem.release()
def update_all_crypto_price_change():
c = DB.open_db_client()
db = c['Cryptos']
cryptos = db.Cryptos.find({"$or" : [ \
{"price_change.date": {"$exists": False }},\
{"price_change.date": {"$lt": dt.combine(dt.now().date(), dt.min.time())}},\
]\
}\
)
cryptos = db.Cryptos.find({})
try:
for i, crypto in enumerate(cryptos):
print("%d: %r" %(i, crypto['bscs']['symbol']))
update_price_change('US', crypto, 1, None, index=True,type='Crypto')
finally:
DB.close_db_client(c)
def fork_hdf5_process(country):
## Randomly get all records whose price is not updated till today
##pipeline = [{'$sample': {'size':num_docs}},
## {'$match' : {"price_change.date": {'$ne':today}}},
## #{"$group": {"_id": _id, "count": {"$sum":1}}},
## #{"$group": {"_id": None, "total": {"$sum": 1}, "details":{"$push":{"groupby": "$_id", "count": "$count"}}}}
## ]
##stocks = db.US_Stocks.aggregate(pipeline, allowDiskUse=True).batch_size(10)
c = DB.open_db_client()
db = c['Stocks']
collection = DB.get_collection(country, db)
sql_engine = DB.open_sql_connection('localhost', 'root', 'petla123', db='US_Stocks')
sort = [1, -1][dt.now().day % 2 == 0]
today=str(dt.now().date())
num_docs = collection.find({}).count()
#num_docs = collection.find({"dates.price_date": {'$ne':today}})
if num_docs == 0:
close_db_client(c)
close_sql_connection(sql_engine)
return
symbols = DB.get_symbols_from_sql(country, sql_engine)
#symbols = get_symbols_from_mongo(collection)
if country == 'India':
indices = India_indices
else:
indices = US_indices
stk = {}
stk['bscs']={}
stk['General']={}
num_processes = DB.num_cores * 8
sem = multiprocessing.BoundedSemaphore(num_processes)
processes = [None]*num_processes
try:
## ETFs are not Common Stock, so update them explicitly before the
## regular stock query below.
#for k in etfs:
# etf_docs = collection.find({'bscs.symbol': k}, no_cursor_timeout=True).batch_size(10).sort([["sno", 1]])
# if etf_docs.count() == 1:
# etf_stk = etf_docs[0]
# print("Price Change: ETF: %r, Name: %r" %(etf_stk['bscs']['symbol'], etf_stk['General']['Name']))
# update_price_change(country, copy.deepcopy(etf_stk), 0, sem=None, index=False)
#Indices
for i, k in enumerate(indices.keys()):
stk['bscs']['symbol'] = k
stk['bscs']['name'] = indices[k]
stk['General']['Code'] = k
stk['General']['Name'] = indices[k]
DB.write_to_collection(collection, stk)
sem.acquire()
update_price_change(country, stk, 1, sem, index=True)
#threading.Thread(target=update_price_change, args=(country, collection, copy.deepcopy(stk['bscs']['symbol']), sem, sql_engine,)).start()
#processes[i%num_processes] = multiprocessing.Process(target=update_price_change, args=(country, copy.deepcopy(stk), i%DB.num_cores, sem, True))
#processes[i%num_processes].start()
## Randomly get all records whose price is not updated till today
##pipeline = [{'$sample': {'size':num_docs}},
## {'$match' : {"dates.price_date": {'$ne':today}}},
## #{"$group": {"_id": _id, "count": {"$sum":1}}},
## #{"$group": {"_id": None, "total": {"$sum": 1}, "details":{"$push":{"groupby": "$_id", "count": "$count"}}}}
## ]