-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdStockDataManager.py
2322 lines (1717 loc) · 88 KB
/
jdStockDataManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import FinanceDataReader as fdr
import yahooquery as yq
from yahooquery import Ticker
import pickle
import math
import numpy as np
import pandas as pd
import pandas_market_calendars as mcal
import os
import json
import datetime as dt
import time
from jdGlobal import get_yes_no_input
from jdGlobal import data_folder
from jdGlobal import metadata_folder
from jdGlobal import screenshot_folder
from jdGlobal import filteredStocks_folder
from jdGlobal import profiles_folder
import openpyxl
from openpyxl.styles import PatternFill, Font, Color
nyse = mcal.get_calendar('NYSE')
exception_ticker_list = {}
sync_fail_ticker_list = []
if not os.path.exists(data_folder):
os.makedirs(data_folder)
if not os.path.exists(metadata_folder):
os.makedirs(metadata_folder)
if not os.path.exists(filteredStocks_folder):
os.makedirs(filteredStocks_folder)
if not os.path.exists(screenshot_folder):
os.makedirs(screenshot_folder)
if not os.path.exists(profiles_folder):
os.makedirs(profiles_folder)
# for test
stockIterateLimit = 99999
# 딕셔너리를 JSON 파일로 저장
def save_to_json(data, filename):
full_path = os.path.join(metadata_folder, f'{filename}.json')
with open(full_path, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4, ensure_ascii=False)
print(f"dictionary data is saved as {full_path} ")
# JSON 파일을 딕셔너리로 로드
def load_from_json(filename):
full_path = os.path.join(metadata_folder, f'{filename}.json')
with open(full_path, 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
return loaded_data
class JdStockDataManager:
def __init__(self):
self.index_data = fdr.DataReader('US500')
self.stock_GICS_df = pd.DataFrame()
self.long_term_industry_rank_df = pd.DataFrame()
self.short_term_industry_rank_df = pd.DataFrame()
self.atrs_ranking_df = pd.DataFrame()
# ---------- cache datas -------------#
self.reset_caches()
def reset_caches(self):
self.cache_StockListFromLocalCsv = pd.DataFrame()
self.cache_getStockDatasFromCsv_out_tickers = None
self.cache_getStockDatasFromCsv_out_stock_datas_dic = None
# ------------------- private -----------------------------------------------
def _get_csv_names(self):
csv_names =[os.path.splitext(f)[0] for f in os.listdir(data_folder) if f.endswith('.csv')]
return csv_names
def _CookIndexData(self, index_data, n = 14):
index_new_data = index_data
# TR(True Range) 계산
high = index_new_data['High']
low = index_new_data['Low']
prev_close = index_new_data['Close'].shift(1)
d1 = high - low
d2 = np.abs(high - prev_close)
d3 = np.abs(low - prev_close)
tr = np.maximum(d1, d2)
tr = np.maximum(tr, d3)
# ATR(Average True Range)
atr = tr.rolling(n).mean()
index_new_data['ATR'] = atr
# TC(True Change) 계산
tc = (index_new_data['Close'] - index_new_data['Close'].shift(1)) / atr
index_new_data['TC'] = tc
# ATC(Average True Change) 계산
atc = tc.rolling(n).mean()
index_new_data['ATC'] = atc
return index_new_data
def _CookStockData(self, stock_data : pd.DataFrame):
new_data = stock_data
try:
# MRS 계산
n = 20
rs = (stock_data['Close'] / self.index_data['Close']) * 100
rs_ma = rs.rolling(n).mean()
mrs = ((rs / rs_ma) - 1) * 100
# MRS를 주식 데이터에 추가
new_data['RS'] = mrs
# 50MA
ma50 = stock_data['Close'].rolling(window=50).mean()
new_data['50MA'] = ma50
# 150MA
ma150 = stock_data['Close'].rolling(window=150).mean()
new_data['150MA'] = ma150
# 200MA
ma200 = stock_data['Close'].rolling(window=200).mean()
new_data['200MA'] = ma200
# 150MA Slope
ma_diff = stock_data['150MA'].diff()
new_data['MA150_Slope'] = ma_diff / 2
# 200MA Slope
ma_diff = stock_data['200MA'].diff()
new_data['MA200_Slope'] = ma_diff / 2
# TR 계산
high = stock_data['High']
low = stock_data['Low']
prev_close = stock_data['Close'].shift(1)
d1 = high - low
d2 = np.abs(high - prev_close)
d3 = np.abs(low - prev_close)
tr = np.maximum(d1, d2)
tr = np.maximum(tr, d3)
new_data['TR'] = tr
# DR% (Daily Range)
daily_range_percentages = high / low
# ADR% (20-days)
n = 20
adr = daily_range_percentages.rolling(n).mean()
adr = 100 * (adr - 1)
new_data['ADR'] = adr
# ATR 계산
n = 14
atr = tr.rolling(n).mean()
new_data['ATR'] = atr
# TC(True Change) 계산
tc = (stock_data['Close'] - stock_data['Close'].shift(1)) / atr
new_data['TC'] = tc
# ATC(Average True Change) 계산
atc = tc.rolling(n).mean()
new_data['ATC'] = atc
# True Range의 합계, 최대 고가, 최소 저가 계산
TrueRangeSum = tr.rolling(window=n).sum()
TrueHighMax = new_data['High'].rolling(window=n).max()
TrueLowMin = new_data['Low'].rolling(window=n).min()
# Choppiness와 표준편차는 눈으로 보는게 낫다. 갭 상승, 돌파 같은 주요 모멘텀을 고려하지 않기 때문.
# Choppiness Index 계산
#new_data['ChoppinessIndex'] = 100 * np.log10(TrueRangeSum / (TrueHighMax - TrueLowMin)) / np.log10(n)
# # 표준편차
# new_data['STD'] = new_data['Close'].rolling(window=14).std()
new_index_data = self._CookIndexData(self.index_data, 14)
# TRS(True Relative Strength)
sp500_tc = new_index_data['TC']
stock_tc = tc
trs = stock_tc - sp500_tc
new_data['TRS'] = trs
# ATRS (14 days Average True Relative Strength)
atrs = trs.rolling(n).mean()
new_data['ATRS'] = atrs
atrs_exp = trs.ewm(span=14, adjust=False).mean()
new_data['ATRS_Exp'] = atrs_exp
n = 150 # 이동평균 윈도우 크기
# ATRS150 (150 days Average True Relative Strength)
if len(new_data) < n:
atrs150 = trs.rolling(len(new_data)).mean()
new_data['ATRS150'] = atrs150
else:
atrs150 = trs.rolling(n).mean()
new_data['ATRS150'] = atrs150
# EMA
if len(new_data) < n:
new_data['ATRS150_Exp'] = trs.ewm(span=len(new_data), adjust=False).mean()
else:
new_data['ATRS150_Exp'] = trs.ewm(span=n, adjust=False).mean()
new_data = new_data.reindex(columns=['Symbol', 'Name', 'Industry',
'Open', 'High', 'Low', 'Close', 'Adj Close',
'Volume', 'RS','50MA', '150MA', '200MA',
'MA150_Slope', 'MA200_Slope',
'ADR', 'TR', 'ATR', 'TC', 'ATC', 'TRS', 'ATRS', 'ATRS_Exp', 'ATRS150', 'ATRS150_Exp',
'IsOriginData_NaN'])
new_data = new_data.round(5)
except Exception as e:
print(e)
raise
return new_data
def _getDatasFromWeb(self, stock_list, trading_days, out_data_dic):
# 모든 주식에 대해 해당 기간의 가격 데이터 가져오기
i = 0
stockNums = stock_list.shape[0]
max_retries = 3
retry_delay = 5 # seconds
for ticker in stock_list['Symbol']:
try:
stock_data = fdr.DataReader(ticker, trading_days[0])
except Exception as e:
print(f'fdr.DataReader({ticker}) failed: {e}')
for retryCnt in range(max_retries):
print(f'Retrying in {retry_delay * (retryCnt + 1)} seconds...')
time.sleep(retry_delay * (retryCnt + 1))
try:
stock_data = fdr.DataReader(ticker, trading_days[0])
if not stock_data.empty:
print(f'fdr.DataReader({ticker}) request success!')
break
except Exception as e:
print(f' fdr.DataReader({ticker}, {trading_days[0]}) failed {e} \n Retry cnt: {retryCnt + 1}')
else:
stock_data = pd.DataFrame()
if not stock_data.empty:
stock_data.reset_index(inplace=True)
stock_data.rename(columns={'index': 'Date'}, inplace=True)
stock_data.set_index('Date', inplace=True)
stock_data['Symbol'] = ticker
stock_data['Name'] = stock_list.loc[stock_list['Symbol'] == ticker, 'Name'].values[0]
stock_data['Industry'] = stock_list.loc[stock_list['Symbol'] == ticker, 'Industry'].values[0]
try:
stock_data = self._CookStockData(stock_data)
# 딕셔너리에 데이터 추가
out_data_dic[ticker] = stock_data
i = i+1
print(f"{i/stockNums*100:.2f}% Done")
if i > stockIterateLimit:
break
except Exception as e:
print(f"An error occurred: {e}")
name = stock_list.loc[stock_list['Symbol'] == ticker, 'Name'].values[0]
exception_ticker_list[ticker] = name
with open("DataReader_exception.json", "w") as outfile:
json.dump(exception_ticker_list, outfile)
def _getAllDatasFromWeb(self, daysNum = 5*365, all_list = pd.DataFrame()):
print("--- getAllDatasFromWeb ---")
if all_list.empty:
# 모든 상장 종목 가져오기
nyse_list = self.get_fdr_stock_list('NYSE', daysNum)
nasdaq_list = self.get_fdr_stock_list('NASDAQ', daysNum)
all_list = pd.concat([nyse_list, nasdaq_list])
# 미국 주식시장의 거래일 가져오기
schedule = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today())
trading_days = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today()).index
# ticker: data dictionary.
out_data_dic = {}
self._getDatasFromWeb(all_list, trading_days, out_data_dic)
return out_data_dic
def _ExportDatasToCsv(self, data_dic):
i = 0
for ticker, data in data_dic.items():
try:
save_path = os.path.join('StockData', f"{ticker}.csv")
data.to_csv(save_path, encoding='utf-8-sig')
i = i+1
print(f"{ticker}.csv", "is saved! {}/{}".format(i, len(data_dic.items())))
except Exception as e:
print(f"An error occurred: {e}")
def getStockListFromLocalCsv(self):
# [Optimize] 메모리 캐시가 있으면 먼저 메모리 캐시 사용
if not self.cache_StockListFromLocalCsv.empty:
return self.cache_StockListFromLocalCsv
# [Optimize] 아니면 데이터 캐시 사용후 메모리에 적재
try:
with open('cache_StockListFromLocalCsv', "rb") as f:
all_list = pickle.load(f)
self.cache_StockListFromLocalCsv = all_list
return all_list
except FileNotFoundError:
nyse_list = self.get_fdr_stock_list('NYSE')
nasdaq_list = self.get_fdr_stock_list('NASDAQ')
all_list = pd.concat([nyse_list, nasdaq_list])
# all_list에서 Symbol이 csv_names에 있는 경우만 추려냄
all_list = all_list[all_list['Symbol'].isin(self._get_csv_names())]
# 결과 로컬에 캐싱.(가끔 전체 주식 리스트 업데이트할때 캐시 지울 필요가 있따.)
with open('cache_StockListFromLocalCsv', "wb") as f:
pickle.dump(all_list, f)
return all_list
def _SyncStockDatas(self, daysToSync = 14):
print("-------------------SyncStockDatas-----------------\n ")
all_list = self.getStockListFromLocalCsv()
sync_data_dic = {}
stock_datas_fromWeb = self._getAllDatasFromWeb(daysToSync, all_list)
tickers = []
stock_datas_fromCsv = {}
self.getStockDatasFromCsv(all_list, tickers, stock_datas_fromCsv)
i = 0
tickerNum = len(tickers)
# tickers를 csv 파일 리스트로부터 가져오기 때문에 최근 상장한 주식은 포함하지 못하는 단점이 있다.
# 이건 주기적으로 전체 데이터를 받거나 해야될듯?
for ticker in tickers:
csvData = stock_datas_fromCsv.get(ticker, pd.DataFrame())
webData = stock_datas_fromWeb.get(ticker, pd.DataFrame())
if csvData.empty or webData.empty:
sync_fail_ticker_list.append(ticker)
continue
# 새로운 데이터프레임을 생성하여 webData_copy에 할당합니다.
webData_copy = webData.copy()
# IsOriginData_NaN 레이블을 추가하고, 기본값으로 False를 할당합니다.
csvData['IsOriginData_NaN'] = False
webData_copy['IsOriginData_NaN'] = False
# forward fill을 사용하여 NaN값을 이전 값으로 대체하면서, IsOriginData_NaN 레이블을 변경합니다.
#webData_copy.fillna(method='ffill', inplace=True)
webData_copy.ffill(inplace=True)
webData_copy.loc[webData['Open'].isnull(), 'IsOriginData_NaN'] = True
webData = webData_copy
# remove duplicate index from csvData.
csvData = csvData[~csvData.index.isin(webData.index)]
try:
# concatenate the two dataframes
df = pd.concat([csvData, webData])
df = self._CookStockData(df)
sync_data_dic[ticker] = df
i = i+1
print(ticker, ' sync Done. {}/{}'.format(i, tickerNum))
except Exception as e:
print(f"An error occurred during sync: {e}")
name = webData.loc[webData['Symbol'] == ticker, 'Name'].values[0]
exception_ticker_list[ticker] = name
self._ExportDatasToCsv(sync_data_dic)
with open('sync_fail_list.txt', 'w') as f:
outputTexts = str()
for ticker in sync_fail_ticker_list:
outputTexts += str(ticker) + '\n'
f.write(outputTexts)
def _getATRCondition_df(self, stock_list, ticker):
try:
save_path = os.path.join('StockData', f"{ticker}.csv")
data = pd.read_csv(save_path)
data.set_index('Date', inplace=True)
ATR = data['ATR']
volume_ma50 = data['Volume'].rolling(window=50).mean()
open = data['Open']
close = data['Close']
diff = close - open
bIsVolumeEnough = (volume_ma50 >= 2000000) & (close >= 10)
conditionA = bIsVolumeEnough & (diff > (1.0 * ATR))
conditionB = bIsVolumeEnough & (diff < (-1.5 * ATR))
except Exception as e:
print(f"An error occurred: {e}")
name = stock_list.loc[stock_list['Symbol'] == ticker, 'Name'].values[0]
self.exception_ticker_list[ticker] = name
conditionA = pd.Series()
conditionB = pd.Series()
return conditionA, conditionB
def _getUpDownConditions_df(self, stock_list):
l_A = []
l_B = []
for ticker in stock_list['Symbol']:
conditionA, conditionB = self._getATRCondition_df(stock_list, ticker)
l_A.append(conditionA)
l_B.append(conditionB)
all_conditions_A = pd.concat(l_A, axis=1, sort=True)
all_conditions_B = pd.concat(l_B, axis=1, sort=True)
all_conditions_A.columns = all_conditions_A.columns.to_list()
all_conditions_B.columns = all_conditions_B.columns.to_list()
daily_changes = pd.DataFrame(index=all_conditions_A.index, columns=['conditionA', 'conditionB'])
daily_changes['conditionA'] = all_conditions_A.sum(axis=1) # 조건 A를 만족하는 종목 수
daily_changes['conditionB'] = all_conditions_B.sum(axis=1) # 조건 B를 만족하는 종목 수
daily_changes['sum'] = daily_changes['conditionA'] - daily_changes['conditionB'] # 조건 A와 B의 차이
daily_changes['ma200_changes'] = daily_changes['sum'].rolling(200).mean() # 150일 이동 평균
daily_changes['ma50_changes'] = daily_changes['sum'].rolling(50).mean() # 150일 이동 평균
daily_changes['ma20_changes'] = daily_changes['sum'].rolling(20).mean() # 150일 이동 평균
return daily_changes
def _getCloseChanges_df(self, stock_list, ticker):
try:
save_path = os.path.join('StockData', f"{ticker}.csv")
data = pd.read_csv(save_path)
data.set_index('Date', inplace=True)
returns = (data['Close'] - data['Close'].shift(1)) / data['Close'].shift(1)
except Exception as e:
print(f"An error occurred: {e}")
name = stock_list.loc[stock_list['Symbol'] == ticker, 'Name'].values[0]
exception_ticker_list[ticker] = name
returns = pd.Series()
return returns
def _getUpDownChanges_df(self, stock_list):
# 모든 종목에 대한 전일 대비 수익률 계산
l = [self._getCloseChanges_df(stock_list, ticker) for ticker in stock_list['Symbol']]
all_returns = pd.concat(l, axis=1, sort=True)
all_returns.columns = all_returns.columns.to_list()
# all_returns의 각 행은 날짜, 각 열은 종목을 의미.
# sum의 axis = 0은 모든 행을 더하고, axis = 1은 모든 열을 더한다.
# (all_returns > 0)으로 all_returns의 모든 값을 True or False로 변경하고
# sum 함수를 이용해 모든 열을 더해 상승 종목 수와 하락 종목 수를 구한다.
daily_changes = pd.DataFrame(index=all_returns.index, columns=['up', 'down'])
daily_changes['up'] = (all_returns > 0).sum(axis=1)
daily_changes['down'] = (all_returns < 0).sum(axis=1)
daily_changes['sum'] = daily_changes['up'] - daily_changes['down']
daily_changes['ma150_changes'] = daily_changes['sum'].rolling(150).mean()
return daily_changes
# ------------------- public -----------------------------------------------
def get_fdr_stock_list(self, market : str, daysNum = 365*5, bIgnore_no_local_tickers = True):
"""
bIgnore_no_local_tickers: Set False if you want to get all stock list from web when you have no local stock data.
"""
fdr_stock_list = pd.DataFrame()
bHaveCache = False
cacheFileName = f"cache_fdr_{market}_list"
if market != 'NASDAQ' and market != 'NYSE' and market != 'S&P500':
print(f'get_fdr_stock_list(), invalid market type {0}!', market)
return fdr_stock_list
try:
with open(cacheFileName, "rb") as f:
fdr_stock_list = pickle.load(f)
bHaveCache = True
except Exception as e:
print(e)
bHaveCache = False
if not bHaveCache:
fdr_stock_list = fdr.StockListing(market)
if bIgnore_no_local_tickers:
fdr_stock_list = fdr_stock_list[fdr_stock_list['Symbol'].isin(self._get_csv_names())]
print('there\'s no cache. save the result newly.')
with open(cacheFileName, "wb") as f:
pickle.dump(fdr_stock_list, f)
return fdr_stock_list
def cook_ATR_Expansion_Counts(self, dyasNum = 365*5):
out_tickers = []
out_stock_datas_dic = {}
stock_data_len = 365*5 # 기본 데이터는 든든하게 미리 챙겨두기
stock_list = self.getStockListFromLocalCsv()
self.getStockDatasFromCsv(stock_list, out_tickers, out_stock_datas_dic, stock_data_len, True)
up_down_condition_df = self._getUpDownConditions_df(stock_list)
up_down_condition_df.to_csv(os.path.join(metadata_folder, 'ATR_Expansion_Counts.csv'))
def cookUpDownDatas(self, daysNum = 365*5):
# S&P 500 지수의 모든 종목에 대해 매일 상승/하락한 종목 수 계산
nyse_list = self.get_fdr_stock_list('NYSE', daysNum)
nyse_list = nyse_list[nyse_list['Symbol'].isin(self._get_csv_names())]
nasdaq_list = self.get_fdr_stock_list('NASDAQ', daysNum)
nasdaq_list = nasdaq_list[nasdaq_list['Symbol'].isin(self._get_csv_names())]
sp500_list = self.get_fdr_stock_list('S&P500', daysNum)
sp500_list = sp500_list[sp500_list['Symbol'].isin(self._get_csv_names())]
# 미국 주식시장의 거래일 가져오기
nyse = mcal.get_calendar('NYSE')
trading_days = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today()).index
valid_start_date = trading_days[0]
valid_end_date = trading_days[-1]
daily_changes_nyse_df = self._getUpDownChanges_df(nyse_list)
daily_changes_nyse_df.to_csv(os.path.join(metadata_folder, 'up_down_nyse.csv'))
daily_changes_nasdaq_df = self._getUpDownChanges_df(nasdaq_list)
daily_changes_nasdaq_df.to_csv(os.path.join(metadata_folder, 'up_down_nasdaq.csv'))
daily_changes_sp500_df = self._getUpDownChanges_df(sp500_list)
daily_changes_sp500_df.to_csv(os.path.join(metadata_folder, 'up_down_sp500.csv'))
with open("up_down_exception.json", "w") as outfile:
json.dump(exception_ticker_list, outfile, indent = 4)
return daily_changes_nyse_df, daily_changes_nasdaq_df, daily_changes_sp500_df
def cook_filter_count_data(self, filter_func, fileName : str, daysNum = 365, bAccumulateToExistingData = True):
out_tickers = []
out_stock_datas_dic = {}
stock_data_len = 365*5 # 기본 데이터는 든든하게 미리 챙겨두기
stock_list = self.getStockListFromLocalCsv()
bUseCachedCSV = bAccumulateToExistingData # 갱신이 아니라 새로 데이터를 뽑는 경우 역시나 든든하게..
self.getStockDatasFromCsv(stock_list, out_tickers, out_stock_datas_dic, stock_data_len, bUseCachedCSV)
# 뭔가 내부 함수 에러나면 라이브러리 업그레이드부터 할 것 =ㅅ=;
nyse = mcal.get_calendar('NYSE')
trading_days = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today()).index
valid_start_date = trading_days[0]
today_str = dt.date.today()
today_schedule = nyse.schedule(start_date=today_str, end_date=today_str)
# 오늘이 거래일이라면 -2가 마지막 거래일
end_date_index = 2
filter_index_offset = 1
# 오늘이 휴일인경우 -1이 마지막 거래일 맞음
if today_schedule.empty:
end_date_index = 1
filter_index_offset = 0
valid_end_date = trading_days[-end_date_index] # 어제가 마지막 거래일. trading_days[-1]은 오늘이고 trading_days[-2]가 어제다. (오늘이 거래일이라면)
days = []
cnts = []
trading_days_num = len(trading_days)
for i in range(end_date_index, trading_days_num):
day = trading_days[-i]
search_start_time = time.time()
selected_tickers = []
selected_tickers = filter_func(out_stock_datas_dic, -i + filter_index_offset) # filter_func[-1]은 어제이고 filter_func[-2]은 어저깨다. 1 더해줘야한다. (오늘이 거래일이라면)
cnt = len(selected_tickers)
#search_end_time = time.time()
#execution_time = search_end_time - search_start_time
#print(f"Search time elapsed: {execution_time}sec")
days.append(day)
cnts.append(cnt)
print(f'{fileName} cnt of {day}: {cnt}')
# days와 cnts 리스트로 데이터프레임 생성
days.reverse()
cnts.reverse()
data = {'Date': days, 'Count': cnts}
new_df = pd.DataFrame(data)
new_df['Date'] = pd.to_datetime(data['Date'])
new_df.set_index('Date', inplace=True)
save_path = os.path.join(metadata_folder, f'{fileName}.csv')
if bAccumulateToExistingData:
local_df = pd.read_csv(save_path)
local_df['Date'] = pd.to_datetime(local_df['Date'])
local_df.set_index('Date', inplace=True)
# 중복 인덱스 제거
local_df = local_df[~local_df.index.isin(new_df.index)]
concat_df = pd.concat([local_df, new_df])
concat_df.to_csv(save_path, encoding='utf-8-sig')
else:
# 데이터프레임을 CSV 파일로 저장
new_df.to_csv(save_path, encoding='utf-8-sig')
def get_count_data_from_csv(self, fileName : str, daysNum = 365*2):
"""
fileName: {fileName}_Counts.csv
"""
# ------------ nyse -------------------
data_path = os.path.join(metadata_folder, f"{fileName}_Counts.csv")
data = pd.read_csv(data_path)
# 문자열을 datetime 객체로 변경
data['Date'] = pd.to_datetime(data['Date'])
# Date 행을 인덱스로 설정
data.set_index('Date', inplace=True)
# 미국 주식시장의 거래일 가져오기
trading_days = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today()).index
startDay = trading_days[0].date()
endDay = min(trading_days[-1], data.index[-1]).date()
# 시작일부터 종료일까지 가져오기
cnt_data = data[startDay:endDay]
return cnt_data
def downloadStockDatasFromWeb(self, daysNum = 365 * 5, bExcludeNotInLocalCsv = True):
print("-------------------_downloadStockDatasFromWeb-----------------\n ")
inputRes = get_yes_no_input('It will override all your local .csv files. \n Are you sure to execute this? (y/n)')
if inputRes == False:
return
if bExcludeNotInLocalCsv == False:
nyse_list = self.get_fdr_stock_list('NYSE', daysNum, False)
nasdaq_list = self.get_fdr_stock_list('NASDAQ', daysNum, False)
all_list = pd.concat([nyse_list, nasdaq_list])
else:
all_list = self.getStockListFromLocalCsv()
sync_data_dic = {}
stock_data_dic_fromWeb = self._getAllDatasFromWeb(daysNum, all_list)
tickers = stock_data_dic_fromWeb.keys()
i = 0
tickerNum = len(tickers)
for ticker in tickers:
webData = stock_data_dic_fromWeb.get(ticker, pd.DataFrame())
if webData.empty:
sync_fail_ticker_list.append(ticker)
continue
# concatenate the two dataframes
df = self._CookStockData(webData)
sync_data_dic[ticker] = df
i = i+1
if i > stockIterateLimit:
break
print(ticker, ' download Done. {}/{}'.format(i, tickerNum))
self._ExportDatasToCsv(sync_data_dic)
with open('download_fail_list.txt', 'w') as f:
outputTexts = str()
for ticker in sync_fail_ticker_list:
outputTexts += str(ticker) + '\n'
f.write(outputTexts)
# cooking 공식이 변하는 경우 로컬 데이터를 업데이트하기 위해 호출
def cookLocalStockData(self, bUseLocalCache = False):
print("-------------------cookLocalStockData-----------------\n ")
all_list = self.getStockListFromLocalCsv()
tickers = []
stock_datas_fromCsv = {}
self.getStockDatasFromCsv(all_list, tickers, stock_datas_fromCsv, 365*6, bUseLocalCache)
cooked_data_dic = {}
for ticker in tickers:
csvData = stock_datas_fromCsv.get(ticker, pd.DataFrame())
if csvData.empty:
sync_fail_ticker_list.append(ticker)
continue
cookedData = self._CookStockData(csvData)
cooked_data_dic[ticker] = cookedData
print(ticker, ' cooked!')
self._ExportDatasToCsv(cooked_data_dic)
def syncCsvFromWeb(self, daysNum = 14):
self._SyncStockDatas(daysNum)
def getUpDownDataFromCsv(self, daysNum = 365*2):
updown_nyse = pd.DataFrame()
updown_nasdaq = pd.DataFrame()
updown_sp500 = pd.DataFrame()
# ------------ nyse -------------------
nyse_file_path = os.path.join(metadata_folder, "up_down_nyse.csv")
data = pd.read_csv(nyse_file_path)
# 문자열을 datetime 객체로 변경
data['Date'] = pd.to_datetime(data['Date'])
# Date 행을 인덱스로 설정
data.set_index('Date', inplace=True)
# 미국 주식시장의 거래일 가져오기
trading_days = nyse.schedule(start_date=dt.date.today() - dt.timedelta(days=daysNum), end_date=dt.date.today()).index
startDay = trading_days[0]
endDay = min(trading_days[-1], data.index[-1])
# 시작일부터 종료일까지 가져오기
data = data[startDay:endDay]
updown_nyse = data
# ------------ nasdaq -------------------
nasdaq_file_path = os.path.join(metadata_folder, "up_down_nasdaq.csv")
data = pd.read_csv(nasdaq_file_path)
# 문자열을 datetime 객체로 변경
data['Date'] = pd.to_datetime(data['Date'])
# Date 행을 인덱스로 설정
data.set_index('Date', inplace=True)
# 시작일부터 종료일까지 가져오기
data = data[startDay:endDay]
updown_nasdaq = data
# ------------ sp500 -------------------
sp500_file_path = os.path.join(metadata_folder, "up_down_sp500.csv")
data = pd.read_csv(sp500_file_path)
# 문자열을 datetime 객체로 변경
data['Date'] = pd.to_datetime(data['Date'])
# Date 행을 인덱스로 설정
data.set_index('Date', inplace=True)
# 시작일부터 종료일까지 가져오기
data = data[startDay:endDay]
updown_sp500 = data
return updown_nyse, updown_nasdaq, updown_sp500
def getStockDatasFromCsv(self, stock_list, out_tickers : list[str], out_stock_datas_dic : dict[str, pd.DataFrame], daysNum = 365*5, bUseCacheData = False):
"""
- Caution! : if bUseCacheData is true, just return last funciton result no matter what other parameter it is.
- It mean that your daysNum param will affect nothing if you use cache data.
"""
# out data must be set by extend()/update() method.
out_tickers.clear()
out_stock_datas_dic.clear()
if bUseCacheData:
try:
# [Optimize]
if self.cache_getStockDatasFromCsv_out_tickers != None:
out_tickers.extend(self.cache_getStockDatasFromCsv_out_tickers)
else:
with open('cache_getStockDatasFromCsv_out_tickers', "rb") as f:
cache_data = pickle.load(f)
out_tickers.extend(cache_data)
self.cache_getStockDatasFromCsv_out_tickers = out_tickers
# [Optimize]
if self.cache_getStockDatasFromCsv_out_stock_datas_dic != None:
out_stock_datas_dic.update(self.cache_getStockDatasFromCsv_out_stock_datas_dic)
else:
with open('cache_getStockDatasFromCsv_out_stock_datas_dic', "rb") as f:
cache_data = pickle.load(f)
out_stock_datas_dic.update(cache_data)
self.cache_getStockDatasFromCsv_out_stock_datas_dic = out_stock_datas_dic
return
except FileNotFoundError as e:
print('Fail to get local cache data in getStockDatasFromCsv(). Normal loading process will be excuted \n', e)
# # [Optimize] no local cache
else:
self.cache_getStockDatasFromCsv_out_tickers = None
self.cache_getStockDatasFromCsv_out_stock_datas_dic = None
print("--- getStockDatasFromCsv ---")
i = 0
stockNums = len(stock_list)
for ticker in stock_list['Symbol']:
try:
csv_path = os.path.join('StockData', f"{ticker}.csv")
data = pd.read_csv(csv_path)
# 문자열을 datetime 객체로 변경
data['Date'] = pd.to_datetime(data['Date'])
# Date 행을 인덱스로 설정
data.set_index('Date', inplace=True)
startDay = dt.date.today() - dt.timedelta(days=daysNum)
endDay = dt.date.today()
# 시작일부터 종료일까지 가져오기
data = data[startDay:endDay]
out_stock_datas_dic[ticker] = data
out_tickers.append(ticker)
i = i+1
print(f"{i/stockNums*100:.2f}% Done")
except Exception as e:
print(f"An error occurred: {e}")
name = stock_list.loc[stock_list['Symbol'] == ticker, 'Name'].values[0]
exception_ticker_list[ticker] = name
# cache the result
with open('cache_getStockDatasFromCsv_out_tickers', "wb") as f:
pickle.dump(out_tickers, f)
with open('cache_getStockDatasFromCsv_out_stock_datas_dic', "wb") as f:
pickle.dump(out_stock_datas_dic, f)
def remove_acquisition_tickers(self):
all_list = self.getStockListFromLocalCsv()
tickers = []
stock_datas_fromCsv = {}
self.getStockDatasFromCsv(all_list, tickers, stock_datas_fromCsv)
removeTargetTickers = []
for ticker in tickers:
data = stock_datas_fromCsv[ticker]
name = data['Name'].iloc[-1].lower()
try:
industry = data['Industry'].iloc[-1].lower()
except Exception as e:
removeTargetTickers.append(ticker)
print(e)
continue
if pd.isna(name) or pd.isna(industry):
removeTargetTickers.append(ticker)
continue
if 'acquisition' in name or '기타 금융업' in industry:
removeTargetTickers.append(ticker)
if 'acquisition' in name or '투자 지주 회사' in industry:
removeTargetTickers.append(ticker)
for ticker in removeTargetTickers:
file_path = os.path.join(data_folder, ticker + '.csv')
if os.path.exists(file_path):
os.remove(file_path)
print(file_path, 'is removed from local directory!')
def cook_Nday_ATRS150_exp(self, N=150):
all_list = self.getStockListFromLocalCsv()
propertyName = 'ATRS150_Exp'
tickers = []
stock_datas_fromCsv = {}
self.getStockDatasFromCsv(all_list, tickers, stock_datas_fromCsv)
date_list = None # 변수 초기화
atrs_dict = {}
for ticker in tickers:
data = stock_datas_fromCsv[ticker]
atrs_list = data[propertyName].iloc[-N:].tolist() # 최근 N일 동안의 ATRS150 값만 가져오기=
atrs_list = [x if not math.isnan(x) else -1 for x in atrs_list] # NaN의 경우 -1로 대체
while len(atrs_list) < N:
atrs_list.insert(0, -1) # 리스트앞에 -1을 추가하여 과거 NaN 데이터를 -1로 치환
if pd.notna(atrs_list).all() and len(atrs_list) == N: # ATRS150 값이 모두 유효한 경우에만 추가
atrs_dict[ticker] = atrs_list
if date_list is None: # 처음으로 유효한 atrs_list를 발견하면 날짜 정보를 가져옴
date_list = data.index[-N:].strftime('%Y-%m-%d').tolist()
atrs_df = pd.DataFrame.from_dict(atrs_dict)
atrs_df['Date'] = date_list
atrs_df = atrs_df.set_index('Date')
atrs_df = atrs_df.T # transpose
save_path = os.path.join(metadata_folder, f'{N}day_{propertyName}.csv')
atrs_df.to_csv(save_path, encoding='utf-8-sig', index_label='Symbol')
return atrs_df
def cook_ATRS150_exp_Ranks(self, N = 150):
propertyName = 'ATRS150_Exp'
csv_path = os.path.join(metadata_folder, f'{N}day_{propertyName}.csv')
data = pd.read_csv(csv_path)
data = data.set_index('Symbol')
rank_df = data.rank(axis=0, ascending=False, method='dense')
rank_df = rank_df
save_path = os.path.join(metadata_folder, f'{propertyName}_Ranking.csv')
rank_df.to_csv(save_path, encoding='utf-8-sig', index_label='Symbol')
def get_ATRS150_exp_Ranks_Normalized(self, Symbol):
propertyName = 'ATRS150_Exp'
try: