Exemplo n.º 1
0
class TopTrader(QMainWindow, ui):
    def __init__(self):
        super().__init__()
        # self.setupUi(self)  # load app screen
        self.logger = TTlog().logger
        self.dbm = DBM('TopTrader')
        self.mongo = MongoClient()
        self.db = self.mongo.TopTrader
        self.slack = Slack(config_manager.get_slack_token())
        self.kw = Kiwoom()
        self.login()
        self.main()

    def load_tick_data(self,
                       code,
                       stock_name,
                       date,
                       tick="1",
                       screen_no="1234"):
        """특정 종목의 하루단위 tick data를 가져오는 함수
        tick_data가 DB에 있으면 DB에서 가져오고, 없으면 kw module로부터 가져온다.

        :param code:
        :param stock_name:
        :param date:
        :param tick:
        :param screen_no:
        :return:
        """
        ret, cur = self.dbm.check_tick_cache(code, date, tick="1")

        if ret:
            tick_data = cur.next()
        else:
            base_date = datetime(date.year, date.month, date.day, 0, 0, 0)
            raw_data = self.kw.stock_price_by_tick(code,
                                                   tick=tick,
                                                   screen_no=screen_no,
                                                   date=base_date)
            tick_data = {
                'code':
                code,
                'stock_name':
                stock_name,
                'date':
                base_date,
                'time_series_1tick': [{
                    'timestamp': _d['date'],
                    '현재가': _d['현재가'],
                    '거래량': _d['거래량']
                } for _d in raw_data]
            }
        return tick_data

    def collect_tick_data(self,
                          code,
                          stock_name,
                          s_date,
                          e_date,
                          tick="1",
                          screen_no="1234"):
        """특정 종목의 일정 기간의 tick data를 DB에 저장하는 함수
        DB에 이미 값이 저장되어 있으면 저장하지 않고 skip 한다.
        s_date, e_date는 초단위까지 지정이 가능하지만, 저장은 일단위로 저장한다.
        tick은 1, 3, 5, 10, 30 선택 가능하다.

        :param code:
        :param stock_name:
        :param tick:
        :param s_date:
        :param e_date:
        :return:
        """
        s_base_date = datetime(s_date.year, s_date.month, s_date.day, 0, 0, 0)
        e_base_date = datetime(e_date.year, e_date.month, e_date.day, 0, 0, 0)
        days = (e_base_date - s_base_date).days + 1
        date_list = [s_base_date + timedelta(days=x) for x in range(0, days)]
        for base_date in date_list:
            ret, cur = self.dbm.check_tick_cache(code, base_date, tick="1")
            if ret:
                self.logger.debug(
                    "No need to save data. already has data in DB")
                continue

            raw_data = self.kw.stock_price_by_tick(code,
                                                   tick=tick,
                                                   screen_no=screen_no,
                                                   date=base_date)
            tick_data = {
                'code':
                code,
                'stock_name':
                stock_name,
                'date':
                base_date,
                'time_series_1tick': [{
                    'timestamp': _d['date'],
                    '현재가': _d['현재가'],
                    '거래량': _d['거래량']
                } for _d in raw_data]
                # 'time_series': [{'timestamp': _d['date'], '현재가': _d['현재가'], '거래량': _d['거래량']} for _d in raw_data]
            }
            # DB에 없으면 수행되는 부분이라서 insert 함수를 사용.
            self.dbm.save_tick_data(tick_data, tick="1")

    def main(self):
        # 사용자 정의 부분_S
        # 8/2일자 조건검색식으로 검출된 모든 종목의 1tick data를 수집한다.
        with open("base_date_when_collect_tick_data.txt") as f:
            year, month, day = [int(i) for i in f.read().strip().split(" ")]
        self.base_date = datetime(year, month, day)
        # 사용자 정의 부분_E

        # kospi, kosdaq 모든 종목의 코드와 종목명 정보를 불러온다.
        self.stock_info = self.kw.get_stock_basic_info()

        code_list = self.dbm.get_code_list_condi_search_result(self.base_date)
        code_list.sort()
        self.dbm.record_collect_tick_data_status("START",
                                                 self.base_date,
                                                 tick="1")
        for num, code in enumerate(code_list, 1):
            stock_name = self.stock_info[code]["stock_name"]
            if self.dbm.already_collect_tick_data(code,
                                                  self.base_date,
                                                  tick="1"):
                self.logger.debug(
                    "{}/{} - {}:{} Skip. Already saved data!".format(
                        num, len(code_list), code, stock_name))
                continue

            self.logger.debug("{}/{} - {}:{} Start !".format(
                num, len(code_list), code, stock_name))
            self.collect_tick_data(code,
                                   stock_name,
                                   self.base_date,
                                   self.base_date,
                                   tick="1",
                                   screen_no="1234")
            self.logger.debug("{}/{} - {}:{} Completed !".format(
                num, len(code_list), code, stock_name))

            self.dbm.save_collect_tick_data_history(code,
                                                    self.base_date,
                                                    tick="1")
            self.dbm.record_collect_tick_data_status("WORKING",
                                                     self.base_date,
                                                     tick="1")

        self.dbm.record_collect_tick_data_status("END",
                                                 self.base_date,
                                                 tick="1")
        self.logger.debug("save all 1tick information..")
        exit(0)  # program exit

    def login(self):
        err_code = self.kw.login()
        if err_code != 0:
            self.logger.error("Login Fail")
            exit(-1)
        self.logger.info("Login success")
class TopTrader(QMainWindow, ui):
    def __init__(self):
        QMainWindow.__init__(self)

        # Application Configuration
        # UI
        self.setupUi(self)

        # Font(ko)
        self.set_ko_font()

        # Logger
        self.logger = TTlog(logger_name="TTRealCondi").logger

        # DB
        self.mongo = MongoClient()
        self.db = self.mongo.TopTrader

        # Slack
        self.slack = Slacker(config_manager.get_slack_token())

        # Kiwoom
        self.kw = Kiwoom()
        self.login()
        self.stock_info = self.kw.get_stock_basic_info()

        # app main
        self.main()

    def login(self):
        err_code = self.kw.login()
        if err_code != 0:
            self.logger.error("Login Fail")
            exit(-1)
        self.logger.info("Login success")

    def set_ko_font(self):
        # 그래프에서 마이너스 폰트 깨지는 문제에 대한 대처
        mpl.rcParams['axes.unicode_minus'] = False

        path = 'c:/Windows/Fonts/D2Coding-Ver1.3.2-20180524.ttf'
        font_name = fm.FontProperties(fname=path).get_name()
        plt.rcParams["font.family"] = font_name

    def main(self):
        print("Start Application")
        # 금일 급등했던 종목 정보를 가져온다.
        stock_info = self.kw.rapidly_rising_price_stock(market="000",
                                                        time_gubun="2",
                                                        time="0",
                                                        vol_gubun="00000",
                                                        screen_no="5000")

        # 급등했던 종목중 상위 20개를 추린다.
        stock_info = stock_info[:20]

        # 상위 20개에 대해 체결강도 정보를 수집하여 DB에 저장한다.
        for stock in stock_info:
            code = stock['종목코드']
            ret = self.kw.get_chegyul_info(code, "9000")
            pdb.set_trace()
            for data in ret:
                h, m, s = data['시간'][:2], data['시간'][2:4], data['시간'][4:]
                t = datetime.today()
                data['date'] = datetime(t.year, t.month, t.day, int(h), int(m),
                                        int(s))
                data['code'] = code
                data['stock_name'] = self.stock_info[code]["stock_name"]
                data['market'] = self.stock_info[code]["market"]
            self.db.short_trading_info_chegyul.insert(ret)
            print(ret)

        # 상위 20개에 대해 분봉/틱봉 정보를 수집하여 DB에 저장한다.
        t = datetime.today()
        s_date = datetime(t.year, t.month, t.day, 9, 0, 0)
        e_date = datetime(t.year, t.month, t.day, 17, 0, 0)

        for stock in stock_info:
            code = stock['종목코드']
            ret = self.kw.stock_price_by_min(code, "1", "9001", s_date, e_date)
            for data in ret:
                data['stock_name'] = self.stock_info[code]["stock_name"]
                data['market'] = self.stock_info[code]["market"]
            self.db.time_series_min1.insert(ret)

            ret = self.kw.stock_price_by_tick(code, "10", "9002", s_date,
                                              e_date)
            for data in ret:
                data['stock_name'] = self.stock_info[code]["stock_name"]
                data['market'] = self.stock_info[code]["market"]
            self.db.time_series_tick10.insert(ret)

        # 상위 20개에 대해 호가 정보를 수집하여 DB에 저장한다.
        # for stock in stock_info:
        #     code = stock['종목코드']
        #     ret = self.kw.get_hoga_info(code, "9001")
        #     self.db.short_trading_info_hoga.insert(ret)
        #     print(ret)
        print("end")
Exemplo n.º 3
0
class TopTrader(QMainWindow, ui):
    def __init__(self):
        QMainWindow.__init__(self)

        # Application Configuration
        # UI
        self.setupUi(self)

        # Font(ko)
        self.set_ko_font()

        # Logger
        self.logger = TTlog(logger_name="TTRealCondi").logger

        # DB
        self.mongo = MongoClient()
        self.db = self.mongo.TopTrader
        self.dbm = DBM('TopTrader')

        # Slack
        self.slack = Slack(cfg_mgr.get_slack_token())

        # Kiwoom
        self.kw = Kiwoom()
        self.login()
        cfg_mgr.STOCK_INFO = self.kw.get_stock_basic_info()

        # app main
        cfg_mgr.MODE = constant.DEBUG
        self.main()

    def login(self):
        err_code = self.kw.login()
        if err_code != 0:
            self.logger.error("Login Fail")
            exit(-1)
        self.logger.info("Login success")

    def set_ko_font(self):
        # 그래프에서 마이너스 폰트 깨지는 문제에 대한 대처
        mpl.rcParams['axes.unicode_minus'] = False
        try:
            path = 'c:/Windows/Fonts/D2Coding-Ver1.3-20171129.ttc'
            font_name = fm.FontProperties(fname=path).get_name()
            plt.rcParams["font.family"] = font_name
        except FileNotFoundError as e:
            path = 'c:/Windows/Fonts/D2Coding-Ver1.3.2-20180524.ttf'
            font_name = fm.FontProperties(fname=path).get_name()
            plt.rcParams["font.family"] = font_name

    def collect_1tick_data(self, code, stock_name, date):
        col_tick1 = self.db.time_series_tick1
        cur = col_tick1.find({'code': code, 'date': date})
        if cur.count() != 0:
            print("{}:{} Already save data. so Skip to save data !".format(
                code, stock_name))
            return

        s_date = date
        e_date = date + timedelta(days=1)
        raw_data = self.kw.stock_price_by_tick(code,
                                               tick="1",
                                               screen_no="1234",
                                               start_date=s_date,
                                               end_date=e_date)
        data = {
            'code':
            code,
            'stock_name':
            stock_name,
            'date':
            date,
            'time_series_1tick': [{
                'timestamp': _d['date'],
                '현재가': _d['현재가'],
                '거래량': _d['거래량']
            } for _d in raw_data]
        }
        # col_tick1.insert(data)
        return data

    def check_cache_tick1(self, code, s_date, e_date):
        col_tick1 = self.db.time_series_tick1
        s_base_date = datetime(s_date.year, s_date.month, s_date.day, 0, 0, 0)
        cur = col_tick1.find({
            'code': code,
            'date': {
                '$gte': s_base_date,
                '$lte': e_date
            }
        })
        if cur.count() != 0:
            return True, cur
        return False, None

    def main(self):
        # 목표 !!!
        # 하루 단위의 조건검색 결과를 분석한다.

        # 사용자 지정 변수__S
        self.target_date = datetime.today()
        self.target_date = datetime(2018, 8, 2)  # temp code
        # 사용자 지정 변수__E

        # 조건검색식 load
        condi_info = self.kw.get_condition_load()
        strg_list = []
        # loop를 돌면서 각각의 조건검색식에 대해 결과 분석
        for condi_name, condi_index in condi_info.items():
            # 특정일의 특정조건검색식을 특정전략으로 검증
            condi = ConditionalSearch.get_instance(condi_index, condi_name)

            self.logger.info("=======[ Smulation(%s) Start! ]=======" %
                             condi.condi_name)
            strg = Strategy("short_trading.strategy", condi)
            strg.simulate(self.target_date)
            strg_list.append(strg)
            self.logger.info("=======[ Smulation(%s) End! ]=======" %
                             condi.condi_name)
            self.logger.info("\n\n\n")

        self.logger.info("end")
        exit(0)