주식투자 Tool 업데이트
본문 바로가기
파이썬으로 만든 것들/배당투자를 위한 도구

주식투자 Tool 업데이트

by Squat Lee 2022. 12. 4.

주식투자 보조툴을 업데이트 했습니다.

크게 3가지가 개선 되었습니다.

 

1. 종목선별 기준

종목을 선별할때 과거 10년치의 가장 높은 DIV 값의 90% 이상 되는 녀석들만 가져왔습니다. 이 방법으로 백테스트도 진행했고, 나쁘지 않은데 조금 더 고려해야 할 부분이 생각났습니다.

 

DIV는 0부터 시작하지 않습니다. 대부분 '3 ~ 8' 또는 '4 ~ 6' 이런 식으로 움직이는 범위가 있습니다. 그런데 만약 '5 ~ 6' 범위로 움직이는 종목이 있다고 가정했을때 최대치의 90%는 5.4가 됩니다. 이 값은 DIV 범위로만 보면 중간 이하의 값이 되는거죠. 

 

어차피 제가 투자하는 방법이 Dividend Range를 이용해서 차익을 얻고, 수익을 실현하기에(배당을 포함해서) 왜곡을 피하고자 코드를 다소 수정했습니다.

과거 10년치의 '(최대배당률-최소배당률) X 90%' 의 식으로 변경했습니다. 좀 더 경험이 쌓여봐야 검증이 가능하겠지만, 생각 만으로는 이 방법이 합당한 것 같습니다. 

 

 

2. 미국채권 장단기금리차

10년 - 2년 채권 금리차를 나타내야 하는데 2년 채권금리를 가져오지 못해서 원래 3개월로 보여 주었습니다.

 

FinanceDataReader 라이브러리에서는 10년-2년 금리차를 제공해 준다는 사실을 발견했습니다. 그래서 장단기 금리차를 가져오는 코드를 수정했습니다.

 

KOSPI도 같은 라이브러리에서 가져오려고 했지만, 에러가 계속 발생했습니다. 그래서 코스피는 기존과 동일하게 야후파이낸스에서 데이터를 가져왔습니다. 

 

장단기 금리차를 계산하는 과정이 없어지니 처리속도가 개선되었습니다. 

 

3. 보유주식 DIV 검토

위의 1번과 마찬가지로 보유주식 검토 부분도 장단기 금리차를 배당률 범위를 적용하였습니다.

 

DIV Ragne가 작은 종목 같은 경우에는 사자마자 팔아야 되는 말도 안되는 일이 벌어질 수 있습니다. 그래서  '{(과거 10년동안의 Max DIV) - (과거 3년 동안의 Min DIV)}  X 0.85' 이렇게 식을 수정하였습니다.

 

매수할 때는 최대한 저렴한 값에 사기위해 10년 동안의 최대치를 적용했습니다. 왜냐하면, 대략 10년 동안에 한 번 이상의 폭락장은 나오기 때문입니다. 과거 기간을 짧게 할 경우에 폭락장에서 대처가 되지 않습니다. 그래서 되도록 Max값은 큰 값을 가져오기로 했습니다.

 

대신 매도는 짧은 기간으로 산정하였습니다. 종목에 따라 다르겠지만 성장하는 기업의 경우 배당률의 최소값도 지속적으로 높아지는 경우가 있습니다. 보통 배당을 지속적으로 증가하는 기업이 이런 경우인데, 매도시점을 찾기가 어려워집니다.

KSS해운 같은 경우에는 2017년에 주식을 매수 했다고 가정하면 현재(2022년 12월)까지 주식을 매도할 타이밍을 찾을 수 없습니다.

 

당연히 좋은 기업의 주식은 평생 가지고 있는것이 좋겠죠. 하지만, 저는 좋은 기업을 판별할 능력이 되지 않습니다. 그래서 적당히 수익을 실현하고 나오는 방법을 택했습니다.

 

매수시점은 DIV Max-Min 값의 85%로, 매도시작지점은 DIV Max-Min 값의 40%로 세팅 했습니다. 근거나 테스트를 진행해 보지는 않았고, 순전히 감으로 세팅하였습니다. 투자 하면서 조금씩 개선해 나가려고 합니다.

 

혹시 종목마다 배당률의 흐름이 다르니 투자 타이밍도 달라야 하는게 아닌가 하는 생각을 할 수 있습니다. 저도 이런 생각에 일정부분 동의합니다. 하지만, 저 같은 초보이자 일반투자자는 원칙을 지키는 것이 중요하다고 생각합니다.

 

나중에 경험과 데이터가 좀 더 쌓이면 달라지겠지만, 지금은 보수적으로 투자를 하는것이 마음이 편할 것 같습니다.

 

전체 코드는 아래와 같습니다.

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
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtGui import QIcon
from pykrx import stock
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data as pdr
import FinanceDataReader as fdr
import time
import numpy as np
import sqlite3
import random
 
ui = 'INVEST TOOL_221112.ui'
 
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(selfNone)
        uic.loadUi(ui, self)
 
        self.btn.clicked.connect(self.input_data)
        self.btn_ex_kospi.clicked.connect(self.kospi_ex)
        self.btn_div.clicked.connect(self.filtered_by_div)
        self.btn_diff_tr.clicked.connect(self.diff_tr_kospi)
        self.btn_dns.clicked.connect(self.dns)
        self.btn_my_div.clicked.connect(self.my_div)
        self.initUI()
 
    # 창이 밋밋해서 아이콘도 넣었다.
    def initUI(self):
        self.setWindowIcon(QIcon('cooldog.png'))
 
    def input_data(self):
        con = sqlite3.connect('krx_data.db')
 
        today_df = pd.read_sql("SELECT 일자 FROM fundamental ORDER BY ROWID DESC LIMIT 1", con)  # DB에서 마지막 행 구하기
        today = today_df['일자'].iloc[0]  # 마지막 행에서 날짜 구하기
 
        # 이름을 받아서 code 입력
        def code_by_name(name):
            code_df = pd.read_sql("SELECT 일자, code, 종목명 FROM fundamental WHERE 종목명 = '" + name + "' AND 일자 = "
                                  + today, con)
            return code_df['code'].iloc[-1]
 
        name = self.le_name.text()
        code = code_by_name(name)
        self.textEdit.clear()
        self.lbl_code.setText(code)
 
        if not self.le_start.text(): #le_start 가 비었으면
            start = str(int(today[:4]) - 10+ today[-4:]  # 10년전 날짜
        else:
            start = self.le_start.text() #아니면 원하는 날짜에 시작
 
        df = pd.read_sql("SELECT 일자, code, 종목명, 종가, DIV, DPS FROM fundamental WHERE code = '" + code +
                           "' AND 일자 >= " + start, con)
 
        # 년도별 배당금 표시하기
        dps_li = []
        try:
            i = 1
            for y in range(int(start[:4]), int(today[:4]) + 1):
                day = stock.get_nearest_business_day_in_a_week(str(y) + '0530')
                df_f = stock.get_market_fundamental_by_ticker(date=day, market='ALL')  # BPS, PER, PBR, EPS, DIV, DPS
                df_f = df_f.loc[code]  # 원하는 종목의 코드에 해당하는 데이터만 필터
                print(df_f)
                prb = int(i)/((int(today[:4]) + 1- int(start[:4])) * 100
                print(prb)
                self.prb.setValue(prb)
                dps = int(df_f['DPS'])  # 배당금을 dps 변수에 저장
                dps_li.append([y - 1, dps])  # 년도와 배당금을 리스트로 저장(년도는 전년도로 저장)
 
                i += 1
        except:
            pass
        print(dps_li)
 
        for data in dps_li:
            exist = self.textEdit.toPlainText()
            self.textEdit.setText(exist + '연도 : ' + str(data[0]) + ' / 배당금 : ' + str(format(data[1], ",")) + '\n')
 
        # 주가, 배당수익률 비교 그래프
        df_f = stock.get_market_fundamental(start, today, code, freq='d')  # BPS, PER, PBR, EPS, DIV, DPS
        name = stock.get_market_ticker_name(code)
        df_f = df_f['DIV']
 
        df_p = stock.get_market_ohlcv(start, today, code)
        df_p = df_p['종가']
 
        df_t = pd.merge(df_p, df_f, left_index=True, right_index=True)
        df_t.columns = ['price''DIV']
        p_max = str(format(df_t['price'].max(), ","))
        p_min = str(format(df_t['price'].min(), ","))
        d_max = str(round(df_t['DIV'].max(), 3))
        d_min = str(round(df_t['DIV'].min(), 3))
        price = str(format(df_t['price'].iloc[-1], ","))
        div = str(round(df_t['DIV'].iloc[-1], 3))
 
        self.lbl_pmax.setText(p_max)
        self.lbl_pmin.setText(p_min)
        self.lbl_dmax.setText(d_max)
        self.lbl_dmin.setText(d_min)
        self.lbl_price.setText(price)
        self.lbl_div.setText(div)
        self.le_start.setText(start)
 
        plt.rcParams['figure.figsize'= (169)
 
        fig, ax1 = plt.subplots()
        ax1.set_xlabel('Date')
        ax1.set_ylabel('price')
        ax1.plot(df_t.index, df_t['price'], color='red', label='Price')
        ax1.legend(loc='upper left')
 
        ax2 = ax1.twinx()
        ax2.set_ylabel('DIV')
        ax2.plot(df_t.index, df_t['DIV'], color='blue', label='DIV')
        ax2.legend(loc='upper right')
        plt.title(name)
        plt.show()
 
    def kospi_ex(self):
        ex = pdr.get_data_yahoo('USDKRW=X''2000-01-04')  # 환율데이터 가져오기
        kospi = pdr.get_data_yahoo('^KS11''2000-01-04')  # KOSPI 데이터 가져오기
 
        df = pd.DataFrame({'KOSPI': kospi['Adj Close'], 'Exchange': ex['Adj Close']})
        df.dropna(inplace=True)
 
        plt.rcParams['figure.figsize'= (169)
 
        fig, ax1 = plt.subplots()
        ax1.set_xlabel('DATE')
        ax1.set_ylabel('KOSPI')
        ax1.plot(df.index, df['KOSPI'], color='red', label='KOSPI INDEX')
        ax1.legend(loc='upper right')
 
        ax2 = ax1.twinx()
        ax2.set_ylabel('Exchange Rate')
        ax2.plot(df.index, df['Exchange'], color='blue', label='Exchange Rate')
        ax2.legend(loc='lower right')
 
        plt.title('Exchange Rate VS KOSPI Index')
 
        exchange = round(df['Exchange'][-1], 2)
        kospi_index = round(df['KOSPI'][-1], 2)
        date = df.index[-1]
 
        self.lbl_date.setText(str(date))
        self.lbl_kospi.setText(str(kospi_index))
        self.lbl_ex.setText(str(exchange))
 
        plt.show()
 
    # 배당수익률을 기준으로 종목 선정하기
    def filtered_by_div(self):
        self.db_update()
        con = sqlite3.connect('krx_data.db')
 
        div = self.le_div.text()
 
        # 과거 10년간의 Dataframe 구하기
        def filter_by_period(today, ticker):
            start = str(int(today[:4]) - 10+ today[-4:]
            end = str(today)
            df = pd.read_sql("SELECT 일자, code, 종목명, DIV, DPS FROM fundamental WHERE code = '" + ticker + "'" +
                             " AND 일자 >= " + start + " AND 일자 < " + end, con)
            return df
 
        div = self.le_div.text()
 
        today_df = pd.read_sql("SELECT 일자 FROM fundamental ORDER BY ROWID DESC LIMIT 1", con)
        # DB에서 마지막 행 구하기
        today = today_df['일자'].iloc[0]  # 마지막 행에서 날짜 구하기
        today_df = pd.read_sql("SELECT 일자, code, 종목명, DIV, DPS, EPS FROM fundamental WHERE 일자 = "
                               + today + " AND EPS > 0" + " AND DPS > 0 AND DIV > " +
                               str(div), con)
 
        # 오늘 날짜 기준으로 Data를 분석하기
        to_see_codes = []
        count = 0
        for code in today_df['code']:
            try:
                print(len(today_df['code']) - count)
                t_df = today_df[today_df['code'== code]
                name = t_df['종목명'].iloc[0]
                t_div = t_df['DIV'].iloc[0]  # 기준일자의 DIV
 
                df = filter_by_period(today, code)
                m = int(len(df['DPS']) / 2)
                if df['DPS'].iloc[0<= df['DPS'].iloc[-1and df['DPS'].iloc[0!= 0 and \
                        df['DPS'].iloc[m] <= df['DPS'].iloc[-1]:
                    if (df['DIV'].max() - df['DIV'].min()) * 0.9 < t_div:
                        to_see_codes.append([today, code, name, t_div])
            except:
                pass
            count += 1
            self.prb.setValue(int(count/len(today_df)*100))
 
        total_df = pd.DataFrame(data=to_see_codes, columns=['기준일''Code''종목명''배당률'])
        print(total_df)
        for i in range(len(total_df)):
            print(i)
            exist = self.te_div.toPlainText()
            self.te_div.setText(exist + '기준일 : ' + str(total_df['기준일'].iloc[i]) +
                                ' / CODE : ' + str(total_df['Code'].iloc[i]) +
                                ' / 종목명 : ' + str(total_df['종목명'].iloc[i]) +
                                ' / 배당률 : ' + str(round(total_df['배당률'].iloc[i], 2)) + '\n')
 
        total_df.to_excel('배당률로 선별한 종목 DIV ' + str(div) + '이상' + today + '.xlsx')
 
    # 장단기 미국채권 금리차와 코스피지수 비교
    def diff_tr_kospi(self):
        kospi = pdr.get_data_yahoo('^KS11''2000-01-04')
        print(kospi)
        T10Y2Y = fdr.DataReader('T10Y2Y''2000-01-04', data_source='fred')  # 미국 장단기 금리차
        print(T10Y2Y)
 
        df = pd.DataFrame({'KOSPI': kospi['Adj Close'], 'T10Y2Y': T10Y2Y['T10Y2Y']})
        df.dropna(inplace=True)
 
        self.lbl_kospi_index.setText(str('{:0,.2f}'.format(int(df['KOSPI'].iloc[-1]))))  # 최근 코스피지수
        self.lbl_diff_tr.setText(str(round(df['T10Y2Y'].iloc[-1], 2)))  # 최근 미국채권 장단기금리 차
        minus_df = df[df['T10Y2Y'< 0]  # 금리가 역전된 최근 일자의 데이터 프레임
        self.lbl_diff_rate.setText(str('{0:,.2f}'.format(minus_df['T10Y2Y'].iloc[-1]))) # 최근 마이너스 금리차
        self.lbl_diff_date.setText(datetime.strftime(minus_df.index[-1], '%Y%m%d'))  # 최근 금리차 역전된 날짜
 
        plt.rcParams['figure.figsize'= (169)
 
        fig, ax1 = plt.subplots()
        ax1.set_xlabel('DATE')
        ax1.set_ylabel('KOSPI')
        ax1.plot(df.index, df['KOSPI'], color='red', label='KOSPI INDEX')
        ax1.legend(loc='upper right')
 
        ax2 = ax1.twinx()
        ax2.set_ylabel('T10Y2Y')
        ax2.plot(df.index, df['T10Y2Y'], color='blue', label='10Y - 2Y Treasury')
        ax2.legend(loc='upper left')
 
        plt.title('USA 10Year-2Year Treasury VS KOSPI')
 
        plt.show()
 
    # DOW, NASDAQ, S&P500 지수 보여주기
    def dns(self):
        dow = pdr.get_data_yahoo('^DJI''2000-01-04')
        snp = pdr.get_data_yahoo('^GSPC''2000-01-04')
        nasdaq = pdr.get_data_yahoo('^IXIC''2000-01-04')
 
        df = pd.DataFrame({'DOW': dow['Adj Close'], 'S&P500': snp['Adj Close'], 'NASDAQ': nasdaq['Adj Close']})
 
        self.lbl_dow.setText(str('{:0,.2f}'.format(df['DOW'].iloc[-1])))
        self.lbl_snp.setText(str('{:0,.2f}'.format(df['S&P500'].iloc[-1])))
        self.lbl_nasdaq.setText(str('{:0,.2f}'.format(df['NASDAQ'].iloc[-1])))
 
        plt.rcParams['figure.figsize'= (169)
 
        fig, ax1 = plt.subplots()
        ax1.set_xlabel('DATE')
        ax1.set_ylabel('DOW, NASDAQ')
        ax1.plot(df.index, df['DOW'], color='red', label='DOW')
        ax1.plot(df.index, df['NASDAQ'], color='blue', label='NASDAQ')
        ax1.legend(loc='upper left')
 
        ax2 = ax1.twinx()
        ax2.set_ylabel('S&P500')
        ax2.plot(df.index, df['S&P500'], color='black', label='S&P500')
        ax2.legend(loc='center right')
 
        plt.title('DOW & NASDAQ & S&P500')
 
        plt.show()
 
    # DB 업데이트
    def db_update(self):
        con = sqlite3.connect('krx_data.db')
 
        # 오늘날짜 기준으로 아직 받지않은 Data를 DB에 다운로드 받기
        # 영업일을 List로 가져오기
        def make_date_list(start, end):
            start = datetime.strptime(start, '%Y%m%d')
            end = datetime.strptime(end, '%Y%m%d')
            dates = [(start + timedelta(days=i)).strftime('%Y%m%d'for i in range((end - start).days + 1)]
            b_dates = []
            for d in dates:
                b_day = stock.get_nearest_business_day_in_a_week(d)
                if not b_day in b_dates:
                    b_dates.append(b_day)
                    s = random.randint(13)
                    time.sleep(s)
 
            return b_dates
 
        # Data를 다운로드 받기
        def data_download(date):
            codes = stock.get_market_ticker_list(date, market='ALL')  # code list 만들기
            corp = []  # Code와 Name을 저장할 List
            for code in codes:
                name = stock.get_market_ticker_name(code)  # 종목 이름 가져오기
                corp.append([code, name])  # Code와 이름으로 리스트를 만들기
            df1 = pd.DataFrame(data=corp, columns=['code''종목명'])  # code와 종목명을 데이터프레임으로 만들기
            df1.index = df1['code']  # index를 코드로 만들기
 
            df_f = stock.get_market_fundamental_by_ticker(date=date,
                                                          market='ALL')  # BPS, PER, PBR, EPS, DIV, DPS 가져와서 데이터 프레임 만들기
            df_c = stock.get_market_cap_by_ticker(date=date, market='ALL')  # 종가, 시가총액, 거래량, 거래대금, 상장주식수 가져오기
 
            time.sleep(1)
 
            df = pd.merge(df1, df_c, left_index=True, right_index=True)  # 종목명, 종가, 시가총액, 거래량, 거래대금, 상장주식수
            df = pd.merge(df, df_f, left_index=True, right_index=True)  # 위에 df + PER, PBR...
            # column은 '종목명', '종가', '시가총액', '거래량', '거래대금', '상장주식수', 'BPS', 'PER', 'PBR', 'EPS', 'DIV', 'DPS'
 
            df['일자'= np.array([date] * len(df))
            df = df.set_index('일자')
 
            return df
 
        # DB에서 마지막 행 구하기
        db_last_df = pd.read_sql("SELECT 일자, code, 종목명, DIV, DPS FROM fundamental ORDER BY ROWID DESC LIMIT 1", con)
        db_last_date = db_last_df['일자'].iloc[0]  # 마지막 행에서 날짜 구하기
        db_last_date = datetime.strptime(db_last_date, '%Y%m%d')
        start_date = (db_last_date + timedelta(days=1)).strftime('%Y%m%d')
 
        # 오늘날짜 구하기
        today = datetime.today().strftime('%Y%m%d')
        end_date = stock.get_nearest_business_day_in_a_week(today, prev=True)
 
        # 데이터 받아서 데이터프레임으로 합치고, DB에 저장
        if start_date < end_date:
            try:
                dates = make_date_list(start_date, end_date)
                print(dates)
                for n, date in enumerate(dates):
                    print(date)
                    if n == 0:
                        t_df = data_download(date)
                    else:
                        t_df = pd.concat([t_df, data_download(date)])
                    time.sleep(1)  # 혹시나 차단될 수 있으니깐
                print(t_df)
                con = sqlite3.connect("krx_data.db")
                t_df.to_sql('fundamental', con, if_exists='append')
            except:
                pass
 
    # 보유주식 검토
    def my_div(self):
 
        self.db_update()
 
        con = sqlite3.connect('krx_data.db')
 
        today = datetime.today()
        today = datetime.strftime(today, '%Y%m%d')  # 오늘일자를 str으로
        start = str(int(today[:4]) - 10+ today[-4:]  # 10년전 날짜
        start_s = str(int(today[:4]) -3+ today[-4:]  # 3년전 날짜(파는 것은 좀 더 보수적으로 하기 위해 짧게 잡기)
 
        codes = ['009150''044450''005090''130580''003540''029780''214320''136540''000140',
                 '271560''005380''005930''002990''005940']
 
        i = 1
        for code in codes:
            df = pd.read_sql("SELECT 일자, code, 종목명, DIV FROM fundamental WHERE code = '" + code + "'" +
                             " AND 일자 >= " + start, con) #10년을 기준으로 한 Dataframe
            df_s = pd.read_sql("SELECT 일자, code, 종목명, DIV FROM fundamental WHERE code = '" + code + "'" +
                               " AND 일자 >= " + start_s, con) #3년을 기준으로 한 Dataframe
            name = df['종목명'].iloc[-1]
            div_max = round(df['DIV'].max(), 2#검토기간 중 가장 높은 값
            div_today = round(df['DIV'].iloc[-1], 2#오늘기준 배당률
            div_min = round(df_s['DIV'].min(), 2#최소값
            div_base = round((div_max - div_min) * 0.85 + div_min, 2)  # 매수를 할 기준값
            div_min_base = round((div_max-div_min) * 0.4 + div_min, 2#매도할 기준값
 
            print(name + ' 85% :' + str(round((div_max - div_min) * 0.85 + div_min, 2)))
            print(name + ' 80% :' + str(round((div_max - div_min) * 0.8 + div_min, 2)))
            print(name + ' 70% :' + str(round((div_max - div_min) * 0.7 + div_min, 2)))
            print(name + ' 40% :' + str(round((div_max - div_min) * 0.4 + div_min, 2)))
            print(name + ' 30% :' + str(round((div_max - div_min) * 0.3 + div_min, 2)))
            print(name + ' 20% :' + str(round((div_max - div_min) * 0.2 + div_min, 2)))
 
            # 매수, 매도, 보유 판단하기
            if div_max <= div_today:
                comment = '  (적극매수)   '
            elif (div_max-div_min) * 0.85 + div_min <= div_today:
                comment = '(매수시작) ' + str(round((div_max-div_min) * 0.85 + div_min, 2)) + '이상   '
            elif (div_max-div_min) * 0.7 + div_min <= div_today:
                comment = '(매수관심) ' + str(round((div_max-div_min) * 0.7 + div_min, 2)) + '이상   '
            elif (div_max-div_min) * 0.4 + div_min > div_today:
                comment = '(20% 매도시작) ' + str(round((div_max-div_min) * 0.4 + div_min, 2)) + '이하 '
            elif (div_max-div_min) * 0.3 + div_min > div_today:
                comment = '(40% 매도시작) ' + str(round((div_max-div_min) * 0.3 + div_min, 2)) + '이하 '
            elif (div_max-div_min) * 0.2 + div_min > div_today:
                comment = '(60% 매도시작) ' + str(round((div_max-div_min) * 0.2 + div_min, 2)) + '이하 '
            elif (div_max-div_min) * 0.1 + div_min > div_today:
                comment = '(80% 매도시작) ' + str(round((div_max-div_min) * 0.1 + div_min, 2)) + '이하 '
            elif div_min >= div_today:
                comment = '   (전량매도)   '
            else:
                comment = '  (No Action) '
 
            # TextEdit에 표시
            exist = self.te_my_div.toPlainText()
            self.te_my_div.setText(exist + '[' + code + '  ' + name + ']  ' + comment + '   <<오늘 DIV : ' +
                                   str(div_today) + '>>  /  Max : ' + str(div_max) + '  /  매수시작점 : ' +
                                   str(div_base) + '  /  Min : ' + str(div_min) + '  /  매도시작점 : ' +
                                   str(div_min_base) + '\n')
 
            self.prb.setValue(int(i / len(codes) * 100))  # 진행 상태바 표시
 
            i += 1
 
        today_df = pd.read_sql("SELECT 일자 FROM fundamental ORDER BY ROWID DESC LIMIT 1", con) # DB에서 마지막 행 구하기
        today = today_df['일자'].iloc[0# 마지막 행에서 날짜 구하기
        self.lbl_my_today.setText(today + '기준 - 검토완료')
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    Window = MainWindow()
    Window.show()
    app.exec_()
cs
728x90
반응형

댓글