-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot_functions.py
1787 lines (1599 loc) · 74 KB
/
bot_functions.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
from bs4 import BeautifulSoup
from datetime import datetime
import json
import numpy as np
import os
import pandas as pd
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from tda import auth, client
import time
def start_bot(keys):
"""
Starts TD Ameritrade Scraping Bot. Takes input of dictionary containing
username and password which must have keys "user" and "pass" with the
values to be used. Returns webdriver object to be used for session.
:param keys: (dict) dictionary with username ("user") and password ("pass")
"""
driver = webdriver.Chrome()
#driver.implicitly_wait(20)
login_url = 'https://secure.tdameritrade.com/auth'
try:
driver.get(login_url)
except:
raise ValueError("Something went wrong")
else:
assert "TD Ameritrade" in driver.title
username = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_css_selector('input#username'))
username.send_keys(keys["user"])
password = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("password"))
password.send_keys(keys["pass"])
try:
driver.find_element_by_css_selector('input#accept.accept.button').click()
except:
raise ValueError("Something went wrong")
else:
try:
WebDriverWait(driver, 10).until(lambda x: EC.text_to_be_present_in_element(x, 'Use desktop website'))
time.sleep(3)
button = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH, value='//*[@id="app"]/div/div[2]/footer/div/ul/li[1]/button'))
button.click()
time.sleep(3)
home_url = driver.current_url
reduce_tabs(driver)
except:
return driver
return driver
def start_client(keys_path, token_path, redirect_url='https://localhost'):
"""
(Deprecated): Instead make client externally and pass into functions as
demonstrated in the notebooks.
This function creates a client for API through tda. For now I recommend
just making one externally, this is only here for if I turn the scraper
into a class object at some point.
"""
api_key = get_keys(keys_path)["consumer_key"]
c = auth.easy_client(api_key, redirect_url, token_path)
return c
def build_big_df(tickers, database_path):
"""
This function reads a previously scraped watchlist database at the provided
path, and combines all of the 'combined.csv' files into one dataframe.
:param tickers: (list-like) The securities to be gathered
:param database_path: (str) The location of the database
"""
big_df = pd.DataFrame()
for ticker in tickers:
file_path = database_path+'/{}/combined.csv'.format(ticker)
try:
temp = pd.read_csv(file_path, index_col='Unnamed: 0').T
except:
temp = pd.DataFrame(pd.read_csv(file_path)).T
big_df = pd.concat([big_df, temp.astype('float64',errors='ignore')], axis=0, sort=True)
new_df = pd.DataFrame()
for col in big_df:
new_df[col] = big_df[col].astype('float64', copy=True, errors='ignore')
for col in new_df.columns:
if col.endswith('since'):
new_df[col] = pd.to_datetime(new_df[col], infer_datetime_format=True)
return new_df
def calculate_intrinsic(c, ticker, root_dir, method, projection_period='5yr', verbose=False,
pe_growth='estimate', beta=None, rfr=None, market_return=None,
shares_out=None, price=None, eps=None):
"""
This function calculates the intrinsic value of a stock based on the growth metric
specified ('FCF', 'PB', 'PE', 'PR'), based on the data found at 'root_dir', which
has been scraped using the functions in this package.
:param c: (tda client) client object for session
:param ticker: (str) the ticker symbol for the company of interest
:param root_dir: (str) the root directory of the scraped watchlist
:param method: (str) growth metric to use for estimation
Options: 'FCF', 'PB', 'PE', 'PR'
:param projection_period: (str) the time frame to project growth over ('5yr')
:param verbose: (bool) if True, info for security used will be printed
:param pe_growth: (str) can be 'historic' or 'estimate'
Default is estimate because it uses analyst estimates for future
growth in calculation, and not just historic growth.
All of the variables below only need to be passed if using function repeatedly,
as when using get_intrinsic_range, which passes these automatically. This avoids
too many repetitive API calls. This means most users will not need to pass these
values into this function.
:param beta: (float) if not passed, will be requested through API
:param rfr: (float) risk-free rate of return, API queried if not passed
:param market_return: (float) the market return, will be calculated if not passed
:param shares_out: (float) the number of outstanding shares, API used if None
:param price: (float) price of the security, will be gotten from API if not passed
:param eps: (float) EPS value to be used, will be gotten from API if not passed
"""
if rfr is None or market_return is None:
rfr, market_return = get_market_info(c, projection_period=projection_period)
if rfr is None and market_return is None:
pass
else:
print("Retrieving market info, pass rfr and market_return to skip this")
if beta is None:
# Get fundamentals for ticker
print("getting beta")
beta = get_stock_data(c, ticker, 'fundamentals').loc[ticker]['beta']
capm = rfr + beta * (market_return - rfr)
def compound_int(principal, interest_rate, periods, per_period=1.0):
amount = principal * (1 + (interest_rate/per_period))**(periods*per_period)
return amount
if method == 'FCF':
if projection_period == '5yr':
try:
fcf = float(fetch_metric(ticker, 'Free Cash Flow', root_dir, 'fundies_yearly'))
except:
print('No FCF data for {}, skipping'.format(ticker))
return None
fcf_growth = float(fetch_metric(ticker, 'FCF Growth 5yr', root_dir, 'fundies'))
fcf_proj = compound_int(fcf, fcf_growth, 5.0)
if verbose:
print('Recent FCF:', fcf)
print('FCF Growth 5 yr:', fcf_growth)
print('FCF Projection:', fcf_proj)
print('Risk-free Rate:', rfr)
print('Beta:', beta)
# Get industry average from sp500
#sector = list(pd.read_excel('export-net.xlsx', skiprows=1)['Symbol'])
sector = [ticker]
pfcfs = []
for company in sector:
try:
fcf = float(fetch_metric(company, 'Free Cash Flow', root_dir, 'fundies_yearly'))
except:
continue
else:
#print(company)
if price is None:
price = c.get_quote(company).json()[company]['lastPrice']
pfcf = price/fcf
pfcfs.append(pfcf)
sector_avg_pfcf = np.mean(pfcfs)
#print(sector_avg_pfcf)
estimate = fcf_proj * 0.95 * sector_avg_pfcf * 0.90 * (1 - capm)
if verbose:
print('Intrinsic Value', estimate)
if method == 'PE':
if projection_period == '5yr':
valuation = pd.read_csv(root_dir+'/{}/valuation.csv'.format(ticker)).set_index('Unnamed: 0')
try:
industry_avg_pe = valuation.loc['Price/Earnings (TTM, GAAP)']['Industry']
except:
try:
industry_avg_pe = valuation.loc['Price/Earnings (TTM, GAAP)'][ticker]
except:
print('No P/E information available for {}, skipping'.format(ticker))
return None
# Filter out seemingly too large/nonsensical values sometimes found on website
if industry_avg_pe > 100:
industry_avg_pe = valuation.loc['Price/Earnings (TTM, GAAP)'][ticker]
if pe_growth == 'historic':
try:
eps_growth = float(fetch_metric(ticker, 'EPS Growth 5yr', root_dir, 'fundies'))
except:
print('EPS Growth 5yr not found for {}'.format(ticker))
return None
if pe_growth == 'estimate':
try:
eps_growth = float(fetch_metric(ticker, 'Growth 5yr Actual/Est', root_dir, 'earnings'))
except:
print('Growth 5yr Actual/Est not found for {}'.format(ticker))
return None
if np.isnan(eps_growth):
print('No EPS Growth for {}, skipping'.format(ticker))
return None
if eps is None:
eps = get_stock_data(c, ticker, 'fundamentals').loc[ticker]['epsTTM']
eps_proj = compound_int(eps, eps_growth, 5.0)
estimate = eps_proj * 0.95 * industry_avg_pe * 0.9 * (1 - capm)
if verbose:
print('EPS Growth 5yr:', eps_growth)
print('EPS TTM:', eps_ttm)
print('EPS Projection:', eps_proj)
print('Industry Avg P/E:', industry_avg_pe)
print('Intrinsic Value:', estimate)
if method == 'PR':
if projection_period == '5yr':
valuation = pd.read_csv(root_dir+'/{}/valuation.csv'.format(ticker)).set_index('Unnamed: 0')
try:
industry_avg_ps = valuation.loc['Price/Sales (TTM)']['Industry']
except:
try:
industry_avg_ps = valuation.loc['Price/Sales (TTM)'][ticker]
except:
print('No Price/Sales data for {}, skipping'.format(ticker))
return None
# Filter out seemingly too large/nonsensical values sometimes found on website
if industry_avg_ps > 100:
industry_avg_ps = valuation.loc['Price/Sales (TTM)'][ticker]
try:
rev_growth = float(fetch_metric(ticker, 'Revenue Growth 5yr', root_dir, 'fundies'))
except:
print('EPS Growth 5yr not found for {}'.format(ticker))
return None
try:
rev = float(fetch_metric(ticker, 'Total Revenue', root_dir, 'fundies_yearly'))
except:
rev = float(fetch_metric(ticker, 'NetInterIn after Loan Loss Provision',
root_dir, 'fundies_yearly'))
rev_proj = compound_int(rev, rev_growth, 5.0)
if shares_out is None:
shares_out = get_stock_data(c, ticker, 'fundamentals').loc[ticker]['sharesOutstanding']
estimate = rev_proj * 0.95 * industry_avg_ps * 0.9 * (1 - capm) / shares_out
if verbose:
print('Rev Growth 5yr:', rev_growth)
print('Current Revenue:', rev)
print('Rev Projection:', rev_proj)
print('Industry Avg P/R:', industry_avg_ps)
print('Intrinsic Value:', estimate)
if method == 'PB':
if projection_period == '5yr':
valuation = pd.read_csv(root_dir+'/{}/valuation.csv'.format(ticker)).set_index('Unnamed: 0')
try:
industry_avg_pb = valuation.loc['Price/Book (MRQ)']['Industry']
except:
try:
industry_avg_pb = valuation.loc['Price/Book (MRQ)'][ticker]
except:
print('Price/Book info not available for {}, skipping'.format(ticker))
return None
# Filter out seemingly too large/nonsensical values sometimes found on website
if industry_avg_pb > 100:
industry_avg_pb = valuation.loc['Price/Book (MRQ)'][ticker]
fundies_yrly = pd.read_csv(root_dir+'/{}/fundies_yearly.csv'.format(ticker)).set_index('Unnamed: 0')
fundies_yrly = fundies_yrly[[col for col in fundies_yrly.columns if col not in ['Report']]]
fundies_yrly = fundies_yrly.T
new_df = pd.DataFrame()
for col in ['Total Assets', 'Total Liabilities']:
new_df[col] = fundies_yrly[col].astype('float64')
fundies_yrly['Book Value'] = new_df['Total Assets'] - new_df['Total Liabilities']
#print(fundies_yrly['Book Value'])
fundies_yrly['Book Growth'] = fundies_yrly['Book Value'].pct_change()
book_growth = fundies_yrly['Book Growth'].mean()
assets = float(fetch_metric(ticker, 'Total Assets', root_dir, 'fundies_yearly'))
liabilities = float(fetch_metric(ticker, 'Total Liabilities', root_dir, 'fundies_yearly'))
book = assets - liabilities
book_proj = compound_int(book, book_growth, 5.0)
if shares_out is None:
shares_out = get_stock_data(c, ticker, 'fundamentals').loc[ticker]['sharesOutstanding']
estimate = book_proj * 0.95 * industry_avg_pb * 0.9 * (1 - capm) / shares_out
if verbose:
print('Book Growth 5yr:', book_growth)
print('Current Book:', book)
print('Book Projection:', book_proj)
print('Industry Avg P/B:', industry_avg_pb)
print('Intrinsic Value:', estimate)
return estimate
def compound_int(principal, interest_rate, periods, per_period=1):
amount = principal * (1 + (interest_rate/per_period))**(periods*per_period)
return amount
def get_intrinsic_range(c, tickers, root_dir, side=None, show_prices=True):
if type(tickers) == str:
tickers = [tickers]
estimates = {}
#if show_prices:
rfr, mr = get_market_info(c, projection_period='5yr')
stock_data = get_stock_data(c, tickers, 'both')[['lastPrice',
'beta',
'sharesOutstanding',
'epsTTM'
]]
prices = stock_data['lastPrice']
betas = stock_data['beta']
shares_out = stock_data['sharesOutstanding']
eps = stock_data['epsTTM']
for ticker in tickers:
success = False
tries = 0
while not success:
try:
estimates[ticker] = {}
for method in ['FCF', 'PE', 'PR', 'PB']:
estimate = calculate_intrinsic(c, ticker, root_dir, method,
rfr=rfr,
market_return=mr,
beta=betas.loc[ticker],
shares_out=shares_out.loc[ticker],
price=prices.loc[ticker],
eps=eps.loc[ticker]
)
estimates[ticker]['Intrinsic: '+method] = estimate
values = pd.Series(list(estimates[ticker].values())).dropna()
if len(values) >= 1:
try:
low = min(values)
high = max(values)
except:
for item in values:
print(item)
raise
else:
low = np.NaN
high = np.NaN
estimates[ticker]['Est Low'] = low
estimates[ticker]['Est High'] = high
if show_prices:
estimates[ticker]['Price'] = prices.loc[ticker]
success = True
except:
print(estimates)
print("Could not do {} on attempt {}".format(ticker, tries))
tries += 1
time.sleep(1)
if tries >= 5:
raise
continue
#time.sleep(.2)
estimates = pd.DataFrame.from_dict(estimates, orient='columns')
estimates = estimates.T
if side == 'long':
estimates['Margin of Safety'] = estimates['Est Low'] / estimates['Price'] - 1
elif side == 'short':
estimates['Margin of Safety'] = estimates['Price'] / estimates['Est High'] - 1
return estimates
def clean(x, show_errors=False):
"""
This function is used to clean strings containing numeric data of the
common issues found in TD Ameritrade's website
"""
#print("cleaning {} of type {}".format(x, type(x)))
not_date = True
multiple = 1
if isinstance(x, str):
check = re.split('/|-|, ', x)
x = x.strip()
x = x.replace(',','')
if x.startswith('(') and x.endswith(')'):
x = x.strip('(').strip(')')
x = '-'+x
if x.endswith('%'):
x = x.replace('%','')
multiple = 1/100
elif x.endswith('x'):
x = x.strip('x')
if x == '--':
x = np.NaN
else:
x = x
if x.endswith('k') or x.endswith('K'):
x = x.upper().replace('K','')
multiple = 1000
if x.startswith('$') or x.startswith('-$'):
x = x.replace('$','')
elif len(check) > 1 and check[-1].isdigit():
not_date = False
if x.startswith('(Unconfirmed)'):
x = x.replace('(Unconfirmed) ','')
x = pd.to_datetime(x, infer_datetime_format=True)
if x == '--':
x = np.NaN
if not_date:
try:
x = float(x) * multiple
except:
if show_errors:
print(x)
x = np.NaN
#print('returning {}'.format(x))
return x
def fetch_metric(ticker, metric, root_dir, file_name, year=None):
if year is None:
year = datetime.now().year
if file_name == 'fundies':
df = retrieve_df(ticker, root_dir, file_name)
try:
datum = df.loc[metric, ticker]
except:
raise
elif file_name == 'fundies_yearly':
df = retrieve_df(ticker, root_dir, file_name)
if pd.notnull(df.loc[metric, str(year)]):
datum = df.loc[metric, str(year)]
else:
try:
datum = df.loc[metric, (str(year-1))]
except:
raise
elif file_name == 'earnings':
df = retrieve_df(ticker, root_dir, file_name)
try:
datum = df.loc[metric, ticker]
except:
raise
return datum
def get_market_info(c, projection_period='5yr'):
if projection_period == '5yr':
# Get risk-free rate:
rfr = c.get_quote('$FVX.X').json()['$FVX.X']['lastPrice'] / 1000
# Get 5 yr avg yearly market growth
r = c.get_price_history(symbol='$SPX.X',
period=client.Client.PriceHistory.Period.FIFTEEN_YEARS,
period_type=client.Client.PriceHistory.PeriodType.YEAR,
).json()
df = pd.DataFrame(r['candles'])
df = df.iloc[-61:] # set to an extra month back to leave out most recent month
# Make new dataframe to copy yearly rows to
df2 = pd.DataFrame()
for i in range(len(df)):
if i % 12 == 0:
df2 = pd.concat([df2, df.iloc[i]], axis=1, sort=True)
df2 = df2.T
df2['growth'] = df2.close.pct_change()
market_return = df2.growth.mean()
return rfr, market_return
def get_stock_data(c, instruments, query='both', step_size=250, verbose=False):
'''
This function uses the TD Ameritrade API to get data
:param c: tda-api client
:param instruments: (list-like or DataFrame) list of ticker symbols.
Can also pass a DataFrame with index of symbols
:param query: (string) 'fundamentals', 'quotes', or 'both'
:param step_size: (int) how many securities to query at once
'''
# Adjust for a single string
if type(instruments) == str:
instruments = [instruments]
total_num = len(instruments)
# Allows returned stock data to be concatenated to an input dataframe
if type(instruments) == pd.DataFrame:
data = instruments.copy()
instruments = list(sorted(instruments.index))
# Create new dataframe if instruments is a list
else:
data = pd.DataFrame()
instruments = sorted(instruments)
if verbose:
print("Getting {} for {} instruments".format(query, total_num))
low = 0
# Helper functions to be used in loop:
def get_fundies(ticks, errs):
if len(ticks) == 1 and type(ticks) == list:
ticks = [ticks[0]]
if errs > 10:
print("More than 10 errors on tickers {}".format(ticks))
return None
r = c.search_instruments(ticks,
projection=client.Client.Instrument.Projection.FUNDAMENTAL)
if not r.ok:
print("Fundamentals problem for {}".format(ticks))
errs += 1
time.sleep(3)
get_fundies(ticks, errs)
return r
def get_quotes(ticks, errs):
if len(ticks) == 1 and type(ticks) == list:
ticks = [ticks[0]]
if errs > 10:
print("More than 10 errors on tickers {}".format(ticks))
return None
r = c.get_quotes(ticks)
if not r.ok:
print("Quote problem for {}".format(ticks))
errs += 1
time.sleep(3)
get_quotes(ticks, errs)
return r
# Run a query for a number of tickers equal to step_size
for i in range(total_num//step_size + 1):
high = low + step_size
if high > total_num:
high = total_num
ticks = list(instruments[low:high])
errs = 0
if query == 'fundamentals' or query == 'both':
errs = 0
# Get response from API
r = get_fundies(ticks, errs)
# Convert to dataframe
temp = pd.DataFrame.from_dict([r.json()[x]['fundamental'] for x in r.json().keys()], orient='columns')
# drop peRatio in favor of more current value from quote query
if query == 'both':
temp.drop(columns=['peRatio'], inplace=True)
temp['Symbol'] = r.json().keys()
# drop duplicate symbol column and set index
temp.drop(columns='symbol', inplace=True)
temp.set_index('Symbol', inplace=True)
if query == 'quotes' or query == 'both':
errs = 0
# Get response from API
r = get_quotes(ticks, errs)
# Convert to dataframe
temp2 = pd.DataFrame.from_dict([r.json()[x] for x in r.json().keys()], orient='columns')
temp2['Symbol'] = r.json().keys()
# Drop duplicate symbol column and set index
temp2.drop(columns='symbol', inplace=True)
temp2.set_index('Symbol', inplace=True)
# Concat to dataframe
if query == 'fundamentals':
data = pd.concat([data, temp], axis=0)
elif query == 'quotes':
data = pd.concat([data, temp2], axis=0)
elif query == 'both':
temp = pd.concat([temp, temp2], axis=1, join='inner', sort=True)
data = pd.concat([data, temp], axis=0)
# Increment variable for next step
low+=step_size
return data
def get_keys(path):
"""
This function will get dictionary of keys from a stored json file
:param path: (str) directory path for the .json file with keys
"""
with open(path) as f:
return json.load(f)
def get_tab_links(driver):
"""
(Depracated) Function used to get html links for each tab on a stock's
page. Replaced in favor of using xpaths with selenium, as pressing the
buttons does not reload the entire webpage, as is done when using a
html link.
:param driver: (Selenium webdriver) driver returned from start_bot()
"""
driver.switch_to.default_content()
iframes = WebDriverWait(driver, 10).until(lambda x: x.find_elements_by_tag_name("iframe"))
driver.switch_to.frame(iframes[3])
soup = BeautifulSoup(driver.page_source, 'html.parser')
stockTabs = soup.find_all('nav', {'class': 'stockTabs'})
info = stockTabs[0].find_all('a')
texts = [x.get_text() for x in info]
links = [x.get('href') for x in info]
tabs = dict(zip(texts,links))
return tabs
def get_tickers(index):
'''
Function to generate a dataframe of securities traded based on exchange.
Uses data from old.nasdaq.com
:param index: What group of tickers to gather:
Options: 'sp500', nsdq', 'nyse', 'amex', 'all'
'''
def filter_stocks(dataframe):
"""
This function formats the dataframe produced by get_tickers() to function with the
tdameritrade API
"""
dataframe.Symbol = dataframe.Symbol.astype('str')
dataframe.Symbol = dataframe.Symbol.map(lambda x: x.strip())
dataframe = dataframe[dataframe.Symbol != 'ACCP']
print("Number of tickers before trim:", len(dataframe))
dataframe = dataframe[dataframe.Symbol.str.isalpha()]
print("Number of tickers after trim:", len(dataframe))
dataframe = dataframe.set_index('Symbol')
return dataframe
if index not in ['nsdq', 'nyse', 'amex', 'sp500', 'all']:
raise ValueError("Unrecognized index given.")
elif index == 'nsdq':
nsdq = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download')
return filter_stocks(nsdq)
elif index == 'nyse':
nyse = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nyse&render=download')
return filter_stocks(nyse)
elif index == 'amex':
amex = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=amex&render=download')
return filter_stocks(amex)
elif index == 'sp500':
sp500 = pd.read_csv('sp500.txt')
return filter_stocks(sp500)
elif index == 'all':
nsdq = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download')
nyse = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nyse&render=download')
amex = pd.read_csv('https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=amex&render=download')
nsdq['Exchange'] = 'NASDAQ'
nyse['Exchange'] = 'NYSE'
amex['Exchange'] = 'AMEX'
us_stocks = pd.concat([nsdq, nyse, amex], axis=0)
# Removing duplicate entries:
us_stocks.drop_duplicates(subset='Symbol',inplace=True)
return filter_stocks(us_stocks)
def reduce_tabs(driver):
"""
This function is used when an action opens the result on a new tab, in
order to reduce the number of browser tabs back to 1, and switch to the
intended tab.
:param driver: (Selenium webdriver)
"""
if len(driver.window_handles) > 1:
driver.switch_to.window(driver.window_handles[0])
driver.close()
driver.switch_to.window(driver.window_handles[0])
def retrieve_df(ticker, root_dir, names):
dfs = []
if type(names) == str:
names = [names]
for name in names:
path = root_dir + '/{}/{}.csv'.format(ticker, name)
df = pd.read_csv(path).set_index('Unnamed: 0')
dfs.append(df)
if len(dfs) == 1:
dfs = dfs[0]
return dfs
def search_symbol(driver, ticker):
"""
This function searches for a ticker symbol on TD Ameritrade website once
user is logged in.
:param driver: (Selenium webdriver) webdriver returned from start_bot()
:param ticker: (str) ticker symbol to search
"""
# Attempt the more expedient symbol lookup, rever to main search otherwise
try:
search = driver.find_element_by_xpath('//*[@id="symbol-lookup"]')
search.click()
search.clear()
except:
driver.switch_to.default_content()
search = driver.find_element_by_name("search")
kind = 'search'
else:
kind = 'symbol'
# Enter ticker symbol to search and click search button
search.send_keys(ticker)
if kind == 'symbol':
driver.find_element_by_xpath('//*[@id="layout-full"]/div[1]/div/div[1]/div/a').click()
elif kind == 'search':
driver.find_element_by_id("searchIcon").click()
# Give extra time for webpage to load
time.sleep(4)
def scrape_analysts(driver, ticker, search_first=True, internet_speed='fast'):
"""
This function scrapes the "Analyst Reports" tab of a TD Ameritrade security
lookup page
:param driver: (Selenium webdriver) webdriver returned from start_bot()
:param ticker: (str) ticker symbol to scrape
:param search_first: (bool) allows for chain of scrapes to be done on one
security when set to False. Leave set to True
unless you are sure you are already on the
desired security, or the wrong data will scrape
:param internet_speed: (str) set to 'slow' if bot is not working properly due
to slow page loading times.
"""
# Search symbol first if flag is True
if search_first:
search_symbol(driver, ticker)
if internet_speed == 'slow':
time.sleep(1)
if internet_speed == 'fast':
sleep_time = 1
elif internet_speed == 'slow':
sleep_time = 2
# Find iframe with tabs (main iframe)
driver.switch_to.default_content()
iframes = WebDriverWait(driver, 10).until(lambda x: x.find_elements_by_tag_name("iframe"))
driver.switch_to.frame(iframes[3])
# Switch to Analyst Reports tab
WebDriverWait(driver, 10).until(lambda x: EC.text_to_be_present_in_element(x, 'Summary'))
driver.find_element_by_xpath('//*[@id="layout-full"]/nav/ul/li[8]/a').click()
time.sleep(sleep_time)
# Wait for conditions before soup is made
driver.switch_to.default_content()
iframes = WebDriverWait(driver, 10).until(lambda x: x.find_elements_by_tag_name("iframe"))
driver.switch_to.frame(iframes[3])
WebDriverWait(driver, 10).until(lambda x: EC.text_to_be_present_in_element(x, 'Archived Reports'))
# Make soup and find container and elements
soup = BeautifulSoup(driver.page_source, 'html.parser')
contain = soup.find('table', {'class':'ui-table provider-table'}).find('tbody')
trs = contain.find_all('tr')
analysts = []
ratings = []
dates = []
for tr in trs:
divs = tr.find_all('div')
analyst = divs[0].get('class')[1].strip()
try:
# Skip vickers
if analyst == 'vickers':
continue
# Special treatment for marketEdge
else:
# Get date or NaN otherwise
try:
txt = tr.find('p', {'class':'rating-since'}).get_text()
date = txt.replace('Rating Since ','')
except:
date = NaN
# Special treatment for marketEdge
if analyst == 'marketEdge':
analysts.append(analyst+' opinion')
rating = divs[2].get('class')[2]
ratings.append(rating)
dates.append(date)
flag = False
i = 0
while flag == False:
i += 1
rating = divs[3].get('class')[1][-i].strip()
try:
rating = float(rating)
if i != 1:
rating = -rating
flag = True
except:
flag = False
# Special treatment for cfra
elif analyst == 'cfra':
rating = divs[2].get('class')[1][-1].strip()
try:
int(rating)
except:
rating = np.NaN
else:
rating = divs[2].get('class')[1].strip()
# Try to make ratings numeric
try:
rating = int(rating)
except:
rating = rating
except:
rating = np.NaN
date = np.NaN
analysts.append(analyst)
ratings.append(rating)
dates.append(date)
# Create dataframe
analyst_dict = dict(zip(analysts,zip(ratings,dates)))
temp = pd.DataFrame.from_dict(analyst_dict,
orient='index',
columns=[ticker,'Rating Since'],
)
# Convert date column to datetime
temp['Rating Since'] = pd.to_datetime(temp['Rating Since'], infer_datetime_format=True)
return temp
def scrape_earnings(driver, ticker, search_first=True, internet_speed='fast'):
"""
This function scrapes the "Earnings" tab of a TD Ameritrade security
lookup page
:param driver: (Selenium webdriver) webdriver returned from start_bot()
:param ticker: (str) ticker symbol to scrape
:param search_first: (bool) allows for chain of scrapes to be done on one
security when set to False. Leave set to True
unless you are sure you are already on the
desired security, or the wrong data will scrape
:param internet_speed: (str) set to 'slow' if bot is not working properly due
to slow page loading times.
"""
# Search for symbol if flag is True
if search_first:
search_symbol(driver, ticker)
if internet_speed == 'slow':
time.sleep(1)
if internet_speed == 'fast':
sleep_time = 1
elif internet_speed == 'slow':
sleep_time = 2
# Find main iframe:
driver.switch_to.default_content()
iframes = WebDriverWait(driver, 10).until(lambda x: x.find_elements_by_tag_name("iframe"))
driver.switch_to.frame(iframes[3])
# Switch to Earnings tab:
WebDriverWait(driver,10).until(lambda x: x.find_element_by_xpath('//*[@id="layout-full"]/nav/ul/li[4]/a')).click()
time.sleep(1)
# Switch to Earnings Analysis (1st sub tab)
WebDriverWait(driver,10).until(lambda x: x.find_element_by_xpath('//*[@id="layout-full"]/div[4]/nav/nav/a[1]')).click()
time.sleep(sleep_time)
# Wait for conditions before making soup
WebDriverWait(driver, 10).until(lambda x: EC.text_to_be_present_in_element(x, 'Annual Earnings History and Estimates'))
element = driver.find_element_by_xpath('//*[@id="main-chart-wrapper"]')
WebDriverWait(driver, 10).until(lambda x: EC.visibility_of_element_located(element))
# Make soup and find container/elements
soup = BeautifulSoup(driver.page_source, 'html.parser')
earn_dict = {}
earnings_dict = {}
contain = soup.find('div', {'data-module-name':'EarningsAnalysisModule'})
header = contain.find('div', {'class':'row contain earnings-data'})
#key = header.find('td', {'class':'label bordered'}).get_text()
earn_dict['Next Earnings Announcement'] = header.find('td', {'class':'value week-of'}).get_text()
# Get number of analysts reporting on security
analysts = header.find_all('td', {'class':'label'})[1].get_text().split()
for word in analysts:
# The number of analysts will be the only numerical string
try:
earn_dict['Growth Analysts'] = float(word)
except:
continue
# Find chart object in container, then bars
chart = contain.find('div', {'id':'main-chart-wrapper'})
bars = chart.find_all('div', {'class':'ui-tooltip'})
for bar in bars:
text = bar.get_text('|').split('|')
# text[0] is the year
year = text[0]
earnings_dict[year] = {}
# There is more text when there is a earnings surprise
if len(text) > 4:
earnings_dict[year]['Earnings Result'] = text[1]
earnings_dict[year][text[2].strip('"').strip().strip(':')] = float(text[3].replace('$',''))
earnings_dict[year][text[4].split(':')[0]] = text[4].split(':')[1].strip()
else:
earnings_dict[year]['Earnings Result'] = 'Neutral'
# Should be a string: 'Actual' or 'Estimate'
est_string = text[1].strip('"').strip().strip(':')
# The actual consensus estimate
est = float(text[2].replace('$',''))
earnings_dict[year][est_string] = est
# Should be a string: 'Estimate range'
est_range_string = text[3].split(':')[0]
# The estimate range as a string
est_range = text[3].split(':')[1].strip()
# Convert to
earnings_dict[year][est_range_string] = est_range
# Create df and all useful columns
earnings_yrly = pd.DataFrame.from_dict(earnings_dict, orient='index')
earnings_yrly['Growth'] = earnings_yrly['Actual'].pct_change()
earnings_yrly['Low Estimate'] = earnings_yrly['Estimate range'].map(lambda x: float(x.split()[0].replace('$','')), na_action='ignore')
earnings_yrly['Low Growth Est'] = earnings_yrly['Low Estimate'].pct_change()
earnings_yrly['High Estimate'] = earnings_yrly['Estimate range'].map(lambda x: float(x.split()[2].replace('$','')), na_action='ignore')
earnings_yrly['High Growth Est'] = earnings_yrly['High Estimate'].pct_change()
# Take average of high and low for years where 'Estimate' not available
earnings_yrly['Consensus Estimate'] = (earnings_yrly['High Estimate'] + earnings_yrly['Low Estimate']) / 2
# Supercede these values where consensus estimates are available
idx_to_change = earnings_yrly[earnings_yrly['Estimate'].notnull()].index
earnings_yrly.loc[idx_to_change, 'Consensus Estimate'] = earnings_yrly.loc[idx_to_change, 'Estimate']
# Make new column that contains the actuals and consensus estimates
earnings_yrly['Actual/Estimate'] = earnings_yrly['Actual']
earnings_yrly.loc[idx_to_change, 'Actual/Estimate'] = earnings_yrly.loc[idx_to_change, 'Estimate']
earnings_yrly['A/E Growth'] = earnings_yrly['Actual/Estimate'].pct_change()
if 'Consensus estimate' in earnings_yrly.columns:
# Sometimes ranges aren't given, and Consensus estimate given instead, fill holes caused
earnings_yrly['Consensus Estimate'].fillna(earnings_yrly[earnings_yrly['Consensus estimate'].notnull()]['Consensus estimate'].map(lambda x: float(x.replace('$',''))), inplace=True)
earnings_yrly.drop(columns=['Consensus estimate'], inplace=True)
earnings_yrly.drop(columns=['Estimate range'], inplace=True)
earnings_yrly['Consensus Growth Est'] = (earnings_yrly['High Growth Est']+earnings_yrly['Low Growth Est']) / 2
low_1yr_growth_est = earnings_yrly.iloc[-2,:]['Low Growth Est']
high_1yr_growth_est = earnings_yrly.iloc[-2,:]['High Growth Est']
cons_1yr_growth_est = earnings_yrly.iloc[-2,:]['Consensus Growth Est']
growth_2yr_low_est = earnings_yrly.iloc[-2:]['Low Growth Est'].mean()
growth_2yr_high_est = earnings_yrly.iloc[-2:]['High Growth Est'].mean()
growth_2yr_cons_est = (growth_2yr_low_est + growth_2yr_high_est) / 2
earn_dict['Growth 1yr Low Est'] = low_1yr_growth_est
earn_dict['Growth 1yr High Est'] = high_1yr_growth_est
earn_dict['Growth 1yr Consensus Est'] = cons_1yr_growth_est
earn_dict['Growth 2yr Low Est'] = growth_2yr_low_est
earn_dict['Growth 2yr High Est'] = growth_2yr_high_est
earn_dict['Growth 2yr Consensus Est'] = growth_2yr_cons_est
earn_dict['Growth 5yr Low Est'] = earnings_yrly['Low Growth Est'].mean()
earn_dict['Growth 5yr High Est'] = earnings_yrly['High Growth Est'].mean()
earn_dict['Growth 5yr Consensus Est'] = earnings_yrly['Consensus Growth Est'].mean()
earn_dict['Growth 5yr Actual/Est'] = earnings_yrly['A/E Growth'].mean()
earn_dict['Growth 3yr Historic'] = earnings_yrly['Growth'].mean()
earn_df = pd.DataFrame.from_dict(earn_dict, orient='index', columns=[ticker])
earn_df[ticker] = earn_df[ticker].map(clean)
return earn_df, earnings_yrly
def scrape_fundamentals(driver, ticker, search_first=True, internet_speed='fast'):
"""
This function scrapes the "Fundamentals" tab of a TD Ameritrade security
lookup page
:param driver: (Selenium webdriver) webdriver returned from start_bot()
:param ticker: (str) ticker symbol to scrape
:param search_first: (bool) allows for chain of scrapes to be done on one
security when set to False. Leave set to True
unless you are sure you are already on the
desired security, or the wrong data will scrape
:param internet_speed: (str) set to 'slow' if bot is not working properly due
to slow page loading times.
"""
# Search symbol first if flag is True
if search_first:
search_symbol(driver, ticker)
#tabs = get_tab_links()
if internet_speed == 'fast':
sleep_time = 1
elif internet_speed == 'slow':
sleep_time = 2
time.sleep(1)
# Gets Overview
driver.switch_to.default_content()