-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTrandingViewClasses.py
2034 lines (1622 loc) · 93.9 KB
/
TrandingViewClasses.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
#Imports
from timeit import default_timer as timer
start = timer()
import concurrent.futures
import logging
import sys
import sqlite3
import time
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import xlwings as xw
import yfinance as yf
from plotly.offline import iplot
from plotly.subplots import make_subplots
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
#logger setup
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
class START():
""" Get company data first from DataBase and if not available Scrape it from website """
companies = []
@classmethod
def get_data(cls, companies_urls):
DataBase.Start() #Connect to DataBase
urls_not_in_database = [] #collect urls not found in database
cls.companies = [] #reset companies variable
#run get-company-data process on separate threads
for url in companies_urls:
#get the data from DataBase
company_data = DataBase()
company_data.GetFromDataBase(company_url=url)
#if data is not loaded from Database
if company_data.income_statement is None or \
company_data.balanse_sheet is None or \
company_data.cashflow_statement is None or \
company_data.statistics is None or \
company_data.company_data is None:
#collect companies that needs to be scraped for the website
urls_not_in_database.append(url)
#if data loaded from DataBase
else:
cls.companies.append(company_data)
#get the data from the website
if urls_not_in_database: #if not empty
# #start website scraping in separate threads
max_thread = 4
with concurrent.futures.ThreadPoolExecutor(max_thread) as executor:
results = [executor.submit(cls.run_in_separate_thread, url) for url in urls_not_in_database ]
#when webscraping is completed
for item in concurrent.futures.as_completed(results):
company_data = item.result()
print(">"*50, type(company_data))
cls.companies.append(company_data)
DataBase.AddToDatabase(data=company_data)
#start website scraping in single thread:
# for url in urls_not_in_database:
# company_data = ScrapeTrendingView(company_url=url)
# cls.companies.append(company_data)
# DataBase.AddToDatabase(data=company_data)
DataBase.Stop() #Disconnect Database
return cls.companies #return company-data
@classmethod
def run_in_separate_thread(cls, url):
company_data = ScrapeTrendingView(company_url=url)
return(company_data)
class DataBase():
database_file = 'tradingview_database.db'
# database_file = 'database_test.db'
@classmethod
def Start(cls): #Connect to Database
cls.conn = sqlite3.connect(cls.database_file) #connect to sqlite3-database
cls.cursor = cls.conn.cursor()
logger.info('DataBase Connected')
@classmethod
def Stop(cls): #Disconnect/Commit to Database
cls.conn.commit() # Commit your changes in the database
cls.conn.close() #Closing the connection
logger.info('DataBase Disconnected')
@classmethod
def AddToDatabase(cls, data): #method that innitiates the write-to-database method with the needed parameters
"""
data = Instance of ScrapeTrendingView() Class
"""
cls.StoreInDatabase(data=data.income_statement, table_name=(data.company_url + '/Income-Statement'))
cls.StoreInDatabase(data=data.balanse_sheet, table_name=(data.company_url + '/Balance-Sheet'))
cls.StoreInDatabase(data=data.cashflow_statement, table_name=(data.company_url + '/Cashflow-Statement'))
cls.StoreInDatabase(data=data.statistics, table_name=(data.company_url + '/Ratios'))
if data.dividents is not None:
cls.StoreInDatabase(data=data.dividents, table_name=(data.company_url + '/Dividents'))
cls.StoreInDatabase(data=data.company_data, table_name=(data.company_url + '/Company-Data'))
@classmethod
def StoreInDatabase(cls, data, table_name, if_exists_value='replace', data_index=True): #method that writes the data into the database
"""data = ScrapeTrendingView().income_statement \n
data = ScrapeTrendingView().balanse_sheet \n
data = ScrapeTrendingView().cashflow_statement \n
data = ScrapeTrendingView().statistics \n
data = ScrapeTrendingView().company_data \n\n
table_name = Exchange-Ticker/Statement-Type \n
Examples: \n
table_name = NASDAQ-AAPL/Income-Statement \n
table_name = NASDAQ-AAPL/Balance-Sheet \n
table_name = NASDAQ-AAPL/Cashflow-Statement \n
table_name = NASDAQ-AAPL/Ratios \n
table_name = NASDAQ-AAPL/Company-Data \n
"""
logger.info(f'Storring {table_name} in {cls.database_file}')
data.to_sql(name=table_name, con=cls.conn, if_exists=if_exists_value, index=data_index) #store dataframe to sqlite-database
@classmethod
def ReadFromDatabase(cls, table_name): #read data from Database, if available return the data if not return None
"""
table_name = Exchange-Ticker/Statement-Type \n
Examples: \n
table_name = NASDAQ-AAPL/Income-Statement \n
table_name = NASDAQ-AAPL/Balance-Sheet \n
table_name = NASDAQ-AAPL/Cashflow-Statement \n
table_name = NASDAQ-AAPL/Ratios \n
table_name = NASDAQ-AAPL/Company-Data \n
"""
try: #get the data from database and put it in pandas-dataframe
output = pd.read_sql_query(f"SELECT * from '{table_name}'", cls.conn, index_col='index')
logger.info(f"Load {table_name} from DataBase")
except : #if data not available, return None
logging.error(f'ERROR: {table_name}, not found in {cls.database_file}')
return None
return output
@classmethod
def DropTable(cls, table_name_prefix):
"""table_name=NASDAQ-AAPL"""
table_name_suffix = ['/Income-Statement', '/Balance-Sheet', '/Cashflow-Statement', '/Ratios', '/Company-Data', '/Dividents']
#Connecting to sqlite
#Droping table if already exists
for i in range(0,len(table_name_suffix)):
try:
cls.cursor.execute(f"DROP TABLE '{table_name_prefix + table_name_suffix[i]}'")
logger.info(f"Table {table_name_prefix + table_name_suffix[i]} dropped... ")
except sqlite3.OperationalError:
logging.error(f' Error removing {table_name_prefix + table_name_suffix[i]}. Table is probably not availabe in the database!')
@classmethod
def DropAllTables(cls):
# Get a list of all tables in the database
tables = cls.ListAllTables()
# Drop all tables in the list
for table in tables:
print(table)
cls.cursor.execute(f"DROP TABLE '{table}'")
@classmethod
def ListAllTables(cls):
cls.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
output_temp = cls.cursor.fetchall()
output = []
for item in output_temp:
output.append(item[0])
return(output)
@classmethod
def ListTableRows(cls, table_name):
cls.cursor.execute(f"SELECT * FROM '{table_name}'")
output = cls.cursor.fetchall()
return output
@classmethod
def ListRowByName(cls, row_name, table_name):
cls.cursor.execute(f'SELECT * FROM "{table_name}" WHERE "index"="{row_name}"')
output = cls.cursor.fetchone()
return output
@classmethod
def ListByColumnName(cls, column_name, table_name):
cls.cursor.execute(f'SELECT "{column_name}" FROM "{table_name}"')
output = cls.cursor.fetchall()
return output
@classmethod
def ListIndexColumn(cls, table_name):
output = cls.ListByColumnName(column_name="index", table_name=table_name)
return output
@classmethod
def GetTableShema(cls,table_name):
cls.cursor.execute(f'PRAGMA table_info("{table_name}")')
output = cls.cursor.fetchall()
return output
@classmethod
def RenameColumn(cls, col_old_name, col_new_name, table_name):
cls.cursor.execute(f'ALTER TABLE "{table_name}" RENAME COLUMN "{col_old_name}" TO "{col_new_name}"')
@classmethod
def RenameTable(cls, table_name_old, table_name_new):
cls.cursor.execute(f'ALTER TABLE "{table_name_old}" RENAME TO "{table_name_new}"')
@classmethod
def UpdateValue(cls,table_name, col_to_update, new_value, search_col, search_value):
cls.cursor.execute(f'UPDATE "{table_name}" SET "{col_to_update}"="{new_value}" WHERE "{search_col}"="{search_value}"')
#UPDATE "ARCA-BATL/Company-Data" SET "value"="1234567" WHERE "index" = "company_data_url"
@classmethod
def DeleteAllRowsFromTable(cls,table_name):
cls.cursor.execute(f'DELETE FROM "{table_name}"')
@classmethod
def InsertRows(cls, table_name, columns_tuple, values_tuple):
cls.cursor.execute(f'INSERT INTO "{table_name}" {columns_tuple} VALUES {values_tuple}')
# INSERT INTO "ARCA-BATL/Company-Data" ("index", "value") VALUES ("1", "2")
@classmethod
def InsertRowIfNotExists(cls, table_name, input_columns, input_values):
# logger.info(f'Insert or Ignore Into {table_name} in {cls.database_file}')
# logger.info(f"columns = {input_columns} \n values = {input_values}")
cls.cursor.execute(f'INSERT OR IGNORE INTO "{table_name}" {input_columns} VALUES {input_values}')
@classmethod
def FindElementsInTableColumn(cls, table_name, column_name, search_text):
result = cls.cursor.execute(f'SELECT "{column_name}" FROM "{table_name}" WHERE "{column_name}"="{search_text}"')
output = result.fetchall()
print(len(output))
return output
@classmethod
def FindNumberOfSectorElements(cls, table_name, market, symbol, exchange, sector):
result = cls.cursor.execute(f'SELECT "sector" FROM "{table_name}" WHERE "market"="{market}" AND "symbol"="{symbol}" AND \
"exchange"="{exchange}" AND "sector"="{sector}"')
output = result.fetchall()
# logger.info(f"Number of Items found in DataBase {len(output)}")
return len(output)
@classmethod
def FindNumberOfExchangeElements(cls, table_name, market, symbol, exchange):
result = cls.cursor.execute(f'SELECT "exchange" FROM "{table_name}" WHERE "market"="{market}" AND "symbol"="{symbol}" AND "exchange"="{exchange}"')
output = result.fetchall()
# logger.info(f"Number of Items found in DataBase {len(output)}")
return len(output)
@classmethod
def Test(cls):
print("DataBase class is working")
def GetFromDataBase(self, company_url):
#get financial data from DataBase
self.income_statement = __class__.ReadFromDatabase(table_name= company_url + "/Income-Statement") #attempt to get the data from database
self.balanse_sheet = __class__.ReadFromDatabase(table_name= company_url + "/Balance-Sheet") #attempt to get the data from database
self.cashflow_statement = __class__.ReadFromDatabase(table_name= company_url + "/Cashflow-Statement") #attempt to get the data from database
self.statistics = __class__.ReadFromDatabase(table_name= company_url + "/Ratios") #attempt to get the data from database
self.company_data = __class__.ReadFromDatabase(table_name= company_url + "/Company-Data") #attempt to get the data from database
if self.company_data is not None:
self.company_name = self.company_data.loc['company_name'][0]
self.company_ticker = self.company_data.loc['company_ticker'][0]
self.company_url = self.company_data.loc['company_url'][0]
dividents_exists = self.company_data.loc['dividents'][0]
if dividents_exists == '1':
self.dividents = __class__.ReadFromDatabase(table_name= company_url + "/Dividents") #attempt to get the data from database
else:
self.dividents = None
class Excel(): #static class for exporting Excel files
#class variables
wb = None #excel workbook
sht = None #excel sheet
height = None #height of the inserted visual
width = None #width of the inserted visual
insert_row = None #cell-row where visual will be inserted, ex, 1,2,3,4
insert_col = None #cell-col when visual will be inserted, ex. A,B,C,D
@classmethod
def start(cls, name="Income Statement", height=375, width=550, insert_row=1, insert_col='A'): #innitite class
# Create an empty workbook & rename sheet
cls.wb = xw.Book() #start Excel
cls.sht = cls.wb.sheets[0] #crete sheet
cls.sht.name = name #set sheet name
cls.height = height #height of the inserted visual
cls.width = width #width of the inserted visual
cls.insert_row = insert_row #default insert cell-row
cls.insert_col = insert_col #default insert cell-column
# Create output directory
OUTPUT_DIR = Path.cwd() / 'Output'
OUTPUT_DIR.mkdir(exist_ok=True)
# Helper function to insert 'Headings' into Excel cells
@classmethod
def insert_heading(cls, cell_row, cell_col, text):
cell = cell_row + cell_col
rng = cls.sht.range(cell)
rng.value = text
rng.font.bold = True
rng.font.size = 24
rng.font.color = (0, 0, 139)
@classmethod
def insert_visual(cls, fig, name):
cell = cls.insert_col + str(cls.insert_row) #calculate the cell where the visual will be inserted
logger.info(cell)
cls.sht.pictures.add(fig,
name = name,
update = True,
left = cls.sht.range(cell).left,
top = cls.sht.range(cell).top,
height = cls.height,
width = cls.width)
cls.insert_row = cls.insert_row + 25 #increase row-number to offset the next visual
logger.info(cls.insert_row)
@classmethod
def close(cls):
cls.wb.save(cls.OUTPUT_DIR / "PythonCharts.xlsx")
if len(cls.wb.app.books) == 1:
cls.wb.app.quit()
else:
cls.wb.close()
class Helper():
def generateClassVariables(self, company_statement):
""" Generate Income Statement / Balance Sheet / Cashflow Statement / Statistics variables """
self.items = company_statement.transpose()
# self.item_keys = []
for item in self.items:
item_temp = item
item_temp = item_temp.lower()
item_temp = item_temp.replace(' - ', '_')
item_temp = item_temp.replace(' – ', '_')
item_temp = item_temp.replace('-', '_')
item_temp = item_temp.replace(' ', '_')
item_temp = item_temp.replace("'", '')
item_temp = item_temp.replace('"', '')
item_temp = item_temp.replace('(', '')
item_temp = item_temp.replace(')', '')
item_temp = item_temp.replace('&', 'and')
item_temp = item_temp.replace('.', '')
item_temp = item_temp.replace(',', '')
item_temp = item_temp.replace('/', '_')
item_temp = item_temp.replace('%', 'percent')
print(f'self.{item_temp}_str = "{item}"')
# self.item_keys.append(item_temp)
# self.res = {}
# for key in self.item_keys:
# for value in self.items:
# self.res[key] = value
# self.items.remove(value)
# break
# print(self.res)
# helper = Helper()
# helper.generateClassVariables(companies[0].statistics)
class ScrapeTrendingView():
maximum_number_of_colapsed_rows = 50
def __init__(self, company_url):
"""
company_url = Exchange-Ticker \n
company_url = NASDAQ-AAPL \n
"""
# innitialize and set chrome-webdriver options
chrome_options = Options()
chrome_options.add_argument("--start-maximized")
# self.chrome_options.add_argument("--window-size=1000,1080")
# chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome("chromedriver.exe", options=chrome_options)
self.driver.implicitly_wait(2)
self.time_sleep = 2
# self.driver.maximize_window()
self.scrapeIncomeStatement(company_url=company_url) #start Income-Statement scraping
self.scrapeBalanceSheet(company_url=company_url) #start Balance-Sheet scraping
self.scrapeCashFlow(company_url=company_url) #start Cashflow-Statement scraping
self.scrapeStatistics(company_url=company_url) #start Ratios scraping
self.scrapeDividents(company_url=company_url) #start Dividents scraping
self.scrapeCompanyData(company_url = company_url) #start Company-Data scraping
#add additional data to dataframe
self.companyData_to_dataframe()
self.driver.close()
def scrapeIncomeStatement(self, company_url):
self.income_statement_url = "https://www.tradingview.com/symbols/" + \
company_url + "/financials-income-statement/?selected="
self.driver.get(self.income_statement_url)
time.sleep(self.time_sleep)
self.switch_annual_data()
self.close_cookies_popup()
self.wait_page_to_load()
# expand income-statement collapsed rows
i = 0
while True:
i = i+1
if i > __class__.maximum_number_of_colapsed_rows:
logging.error(f'Break While loop i={i}')
break
try:
expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k']"
expand_arrow_element = self.driver.find_element_by_xpath(
expand_arrow_xpath)
# self.driver.execute_script("arguments[0].scrollIntoView();", expand_arrow_element) #scroll view to element
expand_arrow_element.click()
# print(expand_arrow_element.if_exists)
except:
break
# scrape the data
output = self.scrape_the_data()
self.income_statement = self.scraped_data_to_dataframe(output=output)
def scrapeBalanceSheet(self, company_url):
logger.info('Start Balance Sheet Scrape')
self.balanse_sheet_url = "https://www.tradingview.com/symbols/" + \
company_url + "/financials-balance-sheet/?selected="
self.driver.get(self.balanse_sheet_url)
time.sleep(self.time_sleep)
self.switch_annual_data()
self.wait_page_to_load()
# self.close_cookies_popup()
# expand balance-sheet collapsed-rows level-1
i = 0
while True:
# logger.info('Start Expanding Balance Sheet Rows Level-1')
i = i+1
if i > __class__.maximum_number_of_colapsed_rows:
logging.error(f'Break While loop i={i}')
break
try:
# expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k']"
expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k hasChanges-_PBNXQ7k']"
expand_arrow_element = self.driver.find_element_by_xpath(
expand_arrow_xpath)
# self.driver.execute_script("arguments[0].scrollIntoView();", expand_arrow_element) #scroll view to element
expand_arrow_element.click()
# print(expand_arrow_element.if_exists)
except:
# logger.info('End Expanding Balance Sheet Rows Level-1')
break
# expand balance-sheet collapsed-rows level-2
i = 0
while True:
# logger.info('Start Expanding Balance Sheet Rows Level-2')
i = i+1
if i > __class__.maximum_number_of_colapsed_rows:
logging.error(f'Break While loop i={i}')
break
try:
expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k']"
expand_arrow_element = self.driver.find_element_by_xpath(
expand_arrow_xpath)
# self.driver.execute_script("arguments[0].scrollIntoView();", expand_arrow_element) #scroll view to element
expand_arrow_element.click()
# print(expand_arrow_element.if_exists)
except:
# logger.info('End Expanding Balance Sheet Rows Level-2')
break
# scrape the data
output = self.scrape_the_data()
self.balanse_sheet = self.scraped_data_to_dataframe(output=output)
def scrapeCashFlow(self, company_url):
logger.info('Start CashFlow Scrape')
self.cashflow_url = "https://www.tradingview.com/symbols/" + \
company_url + "/financials-cash-flow/?selected="
self.driver.get(self.cashflow_url)
time.sleep(self.time_sleep)
self.switch_annual_data()
self.wait_page_to_load()
# self.close_cookies_popup()
# expand cash-flow collapsed-rows level-1
i = 0
while True:
# logger.info('Start Expanding CashFlow Rows Level-1')
i = i+1
if i > 20:
logger.info(f'Break While loop i={i}')
break
try:
# expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k']"
expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k hasChanges-_PBNXQ7k']"
expand_arrow_element = self.driver.find_element_by_xpath(
expand_arrow_xpath)
# self.driver.execute_script("arguments[0].scrollIntoView();", expand_arrow_element) #scroll view to element
expand_arrow_element.click()
# print(expand_arrow_element.if_exists)
except:
# logger.info('End Expanding CashFlow Rows Level-1')
break
# expand cash-flow collapsed-rows level-2
i = 0
while True:
# logger.info('Start Expanding CashFlow Rows Level-2')
i = i+1
if i > 20:
logger.info(f'Break While loop i={i}')
break
try:
expand_arrow_xpath = "//span[@class='arrow-_PBNXQ7k']"
expand_arrow_element = self.driver.find_element_by_xpath(
expand_arrow_xpath)
# self.driver.execute_script("arguments[0].scrollIntoView();", expand_arrow_element) #scroll view to element
expand_arrow_element.click()
# print(expand_arrow_element.if_exists)
except:
# logger.info('End Expanding CashFlow Rows Level-2')
break
# scrape the data
output = self.scrape_the_data()
self.cashflow_statement = self.scraped_data_to_dataframe(output=output)
def scrapeStatistics(self, company_url):
logger.info('Start Statistics Scrape')
self.statistics_url = "https://www.tradingview.com/symbols/" + company_url + "/financials-statistics-and-ratios/?selected="
self.driver.get(self.statistics_url)
time.sleep(self.time_sleep)
# self.close_cookies_popup()
self.switch_annual_data()
self.wait_page_to_load()
statistics_table_xpath = "//div[@class='container-YOfamMRP']/div"
statistics_table_rows = self.driver.find_elements_by_xpath(
statistics_table_xpath)
# for item in financial_table[1]:
# print(item)
# print(self.financial_table.text)
# print(len(statistics_table_rows))
output = []
for item in statistics_table_rows:
item_list = item.text.splitlines()
output_temp = []
# skip non-data items like Key stats, Profitability ratios, Liquidity ratios, Solvency ratios
if len(item_list) == 1:
continue
else:
for i in range(len(item_list)):
output_temp.append(item_list[i].replace(
'\u202a', '').replace('\u202c', ''))
# print(temp[i])
# print(type(temp), len(temp))
# print(temp)
output.append(output_temp)
# for item in output:
# print(len(item),item)
# pass
self.statistics = self.scraped_data_to_dataframe(output=output)
def scrapeDividents(self,company_url):
logger.info('Start Dividents Scrape')
self.dividents_url = "https://www.tradingview.com/symbols/" + company_url + "/financials-dividends/?selected="
self.driver.get(self.dividents_url)
time.sleep(self.time_sleep)
# self.close_cookies_popup()
self.wait_page_to_load()
# scrape dividents
try: #if dividents exists
output = self.scrape_the_data()
self.dividents = self.scraped_data_to_dataframe(output=output)
except: #if dividents not exists, return none
self.dividents = None
# print(self.dividents)
def scrapeCompanyData(self, company_url):
# self.company_data_url = "https://www.tradingview.com/symbols/" + company_url + "/forecast/"
self.company_data_url = "https://www.tradingview.com/symbols/" + company_url + "/technicals/"
self.driver.get(self.company_data_url)
time.sleep(self.time_sleep)
self.wait_page_to_load()
self.company_url = company_url
company_name_css = "h2[class='tv-symbol-header__first-line']"
company_name_element = self.driver.find_element(By.CSS_SELECTOR, company_name_css)
self.company_name = company_name_element.text
# print(self.company_name)
# company_ticker_css = "span[class='tv-symbol-header__second-line tv-symbol-header__second-line--with-hover js-symbol-dropdown'] span[class='tv-symbol-header__second-line--text']"
company_ticker_css = '.tv-symbol-header__second-line--text'
company_ticker_element = self.driver.find_element(By.CSS_SELECTOR, company_ticker_css)
self.company_ticker = company_ticker_element.text
# print(self.company_ticker)
# exchage_css = "span[class='tv-symbol-header__second-line tv-symbol-header__second-line--with-hover js-symbol-dropdown'] span[class='tv-symbol-header__exchange']" #NASDAQ/NYSE
# exchage_css = ".tv-symbol-header__exchange" #NASDAQ/NYSE
# exchage_element = self.driver.find_element(By.CSS_SELECTOR, exchage_css)
# exchange_xpath = "//span[@class='tv-symbol-header__second-line tv-symbol-header__second-line--with-hover js-symbol-dropdown']/span[2]"
# exchange_xpath = "//span[@class='tv-symbol-header__second-line']/span[2]"
# exchage_element = self.driver.find_element(By.XPATH, exchange_xpath)
# self.exchange = exchage_element.text
def companyData_to_dataframe(self):
data = {'company_url':self.company_url,
'income_statement_url': self.income_statement_url,
'balanse_sheet_url': self.balanse_sheet_url,
'cashflow_url': self.cashflow_url,
'statistics_url': self.statistics_url,
'company_data_url': self.company_data_url,
'company_name':self.company_name,
'company_ticker': self.company_ticker} #,"exchange": self.exchange}
if self.dividents is None:
data.update({"dividents": False})
else:
data.update({"dividents": True})
self.company_data = pd.DataFrame.from_dict(data, orient='index', columns=['value'])
def close_cookies_popup(self):
cookie_button_xpath = "//button[@class='acceptAll-WvyPjcpY button-OvB35Th_ size-xsmall-OvB35Th_ color-brand-OvB35Th_ variant-primary-OvB35Th_']"
cookie_button_element = self.driver.find_element_by_xpath(
cookie_button_xpath)
cookie_button_element.click()
def switch_annual_data(self):
annual_button_xpath = "//button[@id='FY']"
annual_button_element = self.driver.find_element_by_xpath(
annual_button_xpath)
annual_button_element.click()
def scraped_data_to_dataframe(self, output):
output_index = []
output_values = []
output_colums = output[0][1:]
self.currency = output[0][0].replace('Currency: ', '')
# print(self.currency)
for i in range(1, len(output)):
output_index.append(output[i][0])
output_values.append(output[i][1:])
# apply neccessery correction to fix the values-data
output_values = self.fix_data_values(input_data=output_values)
df = pd.DataFrame(output_values, columns=output_colums,
index=output_index) # add scraped data to dataframe
return df
def scrape_the_data(self):
# financial_table_xpath = "//div[@class='container-YOfamMRP']"
financial_table_xpath = "//div[@class='container-YOfamMRP']/div"
financial_table_rows = self.driver.find_elements_by_xpath(
financial_table_xpath)
# print(len(financial_table_rows))
output = []
number_of_periods = len(financial_table_rows[0].text.splitlines())
for item in financial_table_rows:
item_list = item.text.splitlines()
output_temp = []
if len(item_list) == number_of_periods: # rows without YOY-grow
for i in range(len(item_list)):
output_temp.append(item_list[i].replace(
'\u202a', '').replace('\u202c', ''))
else: # rows with YOY-grow
if 'YoY growth' in item_list: # Quarterly
for i in range(0, len(item_list), 2): # skip YOY-grow row
output_temp.append(item_list[i].replace(
'\u202a', '').replace('\u202c', ''))
else: # Anual report
output_temp.append(item_list[0])
for i in range(1, len(item_list), 2): # skip YOY-grow row
output_temp.append(item_list[i].replace(
'\u202a', '').replace('\u202c', ''))
output.append(output_temp)
return output
def fix_data_values(self, input_data):
output = []
for row in input_data:
output_row = []
for item in row:
# print(f'item={item}')
if '−' in item: # convert minus sign to real minus, for some reason the sign is not recognized as minus
item = item.replace('−', '-')
if 'T' in item: # convert Trillion-values to numeric
item = item.replace('T', '')
item = float(item)
item = item*1000000000000
# item = int(item)
elif 'B' in item: # convert Billion-values to numeric
item = item.replace('B', '')
item = float(item)
item = item*1000000000
# item = int(item)
elif 'M' in item: # convert Milion-values to numeric
item = item.replace('M', '')
item = float(item)
item = item*1000000
# item = int(item)
elif 'K' in item: # convert Thousants-values to numeric
item = item.replace('K', '')
item = float(item)
item = item*1000
# item = int(item)
if isinstance(item, str): # if item is not integer (0.00, ---, -)
if '—' in item: # set value to None
item = None
elif '.' in item: # convert value to float
item = float(item)
if self.currency != 'USD': # convert values to USD
if self.currency == 'KRW':
self.multiplier = 0.000700680009950
# check if item is int or float
if isinstance(item, float) or isinstance(item, int):
item = item*self.multiplier
output_row.append(item)
output.append(output_row)
return output
def wait_page_to_load(self):
"""wait the page to be fully loaded before proceeding with the scraping procedures"""
price_css = "div[class='tv-symbol-price-quote__value js-symbol-last']"
price_element = self.driver.find_element(By.CSS_SELECTOR, price_css)
currency_symbol_css = ".tv-symbol-price-quote__currency.js-symbol-currency"
currency_symbol_element = self.driver.find_element(By.CSS_SELECTOR, currency_symbol_css)
prince_increase_css = ".js-symbol-change.tv-symbol-price-quote__change-value"
prince_increase_element = self.driver.find_element(By.CSS_SELECTOR, prince_increase_css)
prince_increase_percent_css = ".js-symbol-change-pt.tv-symbol-price-quote__change-value"
prince_increase_percent_element = self.driver.find_element(By.CSS_SELECTOR, prince_increase_percent_css)
class ScrapeTrandingViewScreener():
def __init__(self):
self.screener_url = "https://www.tradingview.com/screener/"
# innitialize and set chrome-webdriver options
chrome_options = Options()
chrome_options.add_argument("--start-maximized")
# self.chrome_options.add_argument("--window-size=1000,1080")
# chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome("chromedriver.exe", options=chrome_options)
self.driver.implicitly_wait(5)
self.time_sleep = 1
# self.driver.maximize_window()
self.driver.get(self.screener_url)
# time.sleep(self.time_sleep)
#define filters
self.market = "USA"
self.symbol = "Common Stock"
self.exchange = "NYSE"
#self.exchange = "NASDAQ"
# self.sector = "Communications" # "Commercial Services" # #"Finance"
#start scraping
self.hide_show_columns()
self.reset_filters()
self.set_filter_symbol_type(symbox_type_text=self.symbol)
# self.set_filter_exchange(exchange_text=self.exchange)
# self.set_filter_sector(sector_text=self.sector)
# The Main Loop
# loop over filter exchange
exchange = self.get_items_filter_exchange()
for i in range(len(exchange)):
logger.info(f"{i+1}/{len(exchange)} Exchange={exchange[i]}")
self.set_filter_exchange(exchange_text=exchange[i])
self.exchange = exchange[i]
#get number of tickers in DataBase
DataBase.Start()
number_tickers_database = DataBase.FindNumberOfExchangeElements(table_name="Tickers", market=self.market, symbol=self.symbol, exchange=self.exchange)
DataBase.Stop()
result = self.get_number_of_rows_in_table() #get the number of the items to be scraped.
if result == None:
logger.info(f"Number of Rows = {result}. Scraping not needed!")
elif result <= 1000: #if result is less than 1000, scrape the tickers for all sectors
logger.info(f"Number of Rows = {result} <= 1000")
logger.info(f"Number of items with Exchange = {self.exchange} in DataBase: {number_tickers_database}")
if result != number_tickers_database:
logger.info(f"Number of items in DataBase {number_tickers_database} NOT equals Number of Items on Page {result}. Start Scraping per Exchange!")
else:
logger.info(f"Number of items in DataBase {number_tickers_database} equals Number of Items on Page {result}. Scraping not needed!")
elif result >1000: #if result is greater than 1000, scrate the tickers per sector
logger.info(f"Number of Rows = {result} > 1000")
logger.info(f"Number of items with Exchange = {self.exchange} in DataBase: {number_tickers_database}")
if result != number_tickers_database:
logger.info(f"Number of items in DataBase {number_tickers_database} NOT equals Number of Items on Page {result}. Start Scraping per Sectors!")
# loop over filter sector
#get all filter-sectors and loop over them
sectors = self.get_items_filter_sector()
for i in range(len(sectors)):
# logger.info(' '.join(map(str, sectors)))
logger.info(f"{i+1}/{len(sectors)} Sector={sectors[i]}")
self.set_filter_sector(sector_text=sectors[i])
self.sector = sectors[i]
self.get_main_table_rows()
self.reset_filter_sector()
else:
logger.info(f"Number of items in DataBase {number_tickers_database} equals Number of Items on Page {result}. Scraping not needed!")
# self.driver.close()
def reset_filters(self):
#open filters popup page
filters_btn_xpath = "//div[@class='tv-screener-toolbar__button tv-screener-toolbar__button--options tv-screener-toolbar__button--filters apply-common-tooltip common-tooltip-fixed']"
self.filters_btn = self.driver.find_element(by=By.XPATH, value=filters_btn_xpath)
self.filters_btn.click()
#filters popup page
reset_all_btn_xpath = "//div[@class='tv-screener-search__reset js-search-reset']"
self.reset_all_btn = self.driver.find_element(by=By.XPATH, value=reset_all_btn_xpath)
self.reset_all_btn.click()
#close filters popup page
webdriver.ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()
def set_filter_symbol_type(self, symbox_type_text):
#open filters popup page
self.filters_btn.click()
#click filters>symbol-type button to display dropdown menu
filters_symbol_type_btn_xpath = "//div[@class='tv-screener-dialog__selectbox-container js-filter-field-name js-dropdown-toggle']//span[@class='tv-screener-dialog__filter-field-content-value'][normalize-space()='Any']"
self.filters_symbol_type_btn = self.driver.find_element(by=By.XPATH, value=filters_symbol_type_btn_xpath)
self.filters_symbol_type_btn.click()
#click on selected sector in dropdown
self.select_from_dropdown_menu(selection_text=symbox_type_text)
#close filters popup page
webdriver.ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()
def set_filter_exchange(self, exchange_text):
#open filters popup page
self.filters_btn.click()
#reset filter exchange
try:
reset_filter_exchange_xpath = "//div[@class='tv-screener-dialog__filter-field js-filter-field js-filter-field-exchange tv-screener-dialog__filter-field--cat1 js-wrap tv-screener-dialog__filter-field--active']/div[@class='tv-screener-dialog__filter-field-reset apply-common-tooltip js-reset']"
reset_filter_exchange_btn = self.driver.find_element(by=By.XPATH, value=reset_filter_exchange_xpath)
reset_filter_exchange_btn.click()
logger.info("Reset Filter Exchange")
except:
logger.info("Filter Exchange does not need reset")
#click filters>exchange btn to show dropdown window
filters_exchange_btn_xpath = "//div[@class='tv-screener-dialog__selectbox-container js-filter-field-exchange js-dropdown-toggle']//span[@class='tv-screener-dialog__filter-field-content-value'][normalize-space()='Any']"
self.filters_exchange_btn = self.driver.find_element(by=By.XPATH, value=filters_exchange_btn_xpath)
self.filters_exchange_btn.click()