Ejemplo n.º 1
0
    def draw_predictions(self,
                         corp_name,
                         scaler_close,
                         data_params,
                         test_predict,
                         invest_predicts=None):
        """예측 그래프를 그린다."""
        dir = 'predicts'
        dir_chart = os.path.join(self.main.DIR_CHARTS, dir)
        DataUtils.create_dir(dir_chart)

        if invest_predicts is not None and test_predict is not None:
            predicts = np.append(test_predict, invest_predicts)
            #print(len(test_predict), len(invest_predicts))
        elif test_predict is not None:
            predicts = test_predict
        else:
            predicts = invest_predicts
        dataY = np.append(data_params.testY, data_params.investY)

        preds = []
        for pred in predicts:
            #print(pred, scaler_close)
            preds.append(DataUtils.inverse_scaled_data(scaler_close, pred))

        close_values = []
        for y in dataY:
            close_values.append(DataUtils.inverse_scaled_data(scaler_close, y))

        df_data = self.get_predicts_data(data_params, close_values, preds)
        df_data['date'] = pd.to_datetime(df_data['date'], format='%Y.%m.%d')
        df_data_index = df_data.set_index('date')
        self.draw_predictions_seaborn(df_data_index, dir, corp_name)
        self.save_csv(df_data, dir, corp_name)
Ejemplo n.º 2
0
 def invest_scaled_money(self, invest_scaled_predict, now_scaled_close,
                         scaler_close, now_money, now_stock_cnt):
     """예측 값에 따라 매수 매도를 실행한다."""
     now_close = DataUtils.inverse_scaled_data(scaler_close,
                                               now_scaled_close)
     if invest_scaled_predict == -1:
         invest_predict = -1
     else:
         invest_predict = DataUtils.inverse_scaled_data(
             scaler_close, invest_scaled_predict)
     return self.invest_money(invest_predict, now_close, now_money,
                              now_stock_cnt)
Ejemplo n.º 3
0
    def invest_scaled_money_before(self, before_scaled_close,
                                   before_scaled_predict, x, now_money,
                                   now_stock_cnt, scaler_close):
        x_high, x_low = self.get_high_n_low(x, scaler_close)

        before_invest_predict = DataUtils.inverse_scaled_data(
            scaler_close, before_scaled_predict)
        before_close = DataUtils.inverse_scaled_data(scaler_close,
                                                     before_scaled_close)
        return self.invest_money_before2(before_close, before_invest_predict,
                                         x_high, x_low, now_money,
                                         now_stock_cnt)
Ejemplo n.º 4
0
    def invest_n_all(self,
                     comp_code,
                     dataX_last,
                     data_params,
                     params_all,
                     scaler_close=None):
        """학습 후 모의 주식 거래를 한다."""

        ip = InvestParams()
        investX = data_params.investX
        invest_count = len(investX)
        ip.invest_money = self.params.invest_money

        now_stock_cnt = 0
        ip.index_money = ip.invest_money
        all_stock_count = 0
        before_scaled_close = None
        before_invest_predict = None
        now_scaled_close = None
        for i in range(invest_count):

            x = investX[i:i + 1]
            invest_predict = self._get_predict(self.params, comp_code, x)
            invest_predict_all = self._get_predict(params_all, comp_code, x)

            invest_predict = np.mean([invest_predict, invest_predict_all])
            ip.predict_list.append([invest_predict])
            x_last = x[:, -1][0]
            now_scaled_close = x_last[0]
            if i != 0:
                ip.invest_money, now_stock_cnt = self.invest_scaled_money_before(
                    before_scaled_close, before_invest_predict, x,
                    ip.invest_money, now_stock_cnt, scaler_close)

            ip.invest_money, now_stock_cnt = self.invest_scaled_money(
                invest_predict, now_scaled_close, scaler_close,
                ip.invest_money, now_stock_cnt)
            if i == 0:
                ip.index_money, all_stock_count = self.invest_scaled_money(
                    -1, now_scaled_close, scaler_close, ip.index_money,
                    all_stock_count)
            before_scaled_close = now_scaled_close
            before_invest_predict = invest_predict

        if now_scaled_close != None:
            now_close = DataUtils.inverse_scaled_data(scaler_close,
                                                      now_scaled_close)
            ip.invest_money += self.to_money(now_stock_cnt, now_close)
            ip.index_money += self.to_money(all_stock_count, now_close)

        # 마지막 예측 값을 구한다.
        ip.last_predict = self._get_predict(self.params, comp_code, dataX_last)
        last_predict_all = self._get_predict(params_all, comp_code, dataX_last)
        ip.last_predict = np.mean([ip.last_predict, last_predict_all])

        return ip
Ejemplo n.º 5
0
    def draw_invests(self, corp_name, invest_data, all_invest_data, scaler_close, data_params)->list:
        """모의 투자 결과 그래프를 그린다."""
        dir = 'invests'
        kospi = self.get_kospi_kosdaq('KOSPI')
        kosdaq = self.get_kospi_kosdaq('KOSDAQ')

        start_money = self.params.invest_money
        if self.params.index_money is not None:
            start_index_money = self.params.index_money
        else:
            start_index_money = start_money
        start_kospi = self.get_value(kospi, 0, 'close')
        start_kosdaq = self.get_value(kosdaq, 0, 'close')
        investY_date = data_params.investY_date
        invest_index = all_invest_data[0]
        money_index = invest_index[1]
        stock_cnt_index = invest_index[2]
        date = investY_date[0:1].values[0]
        date = DateUtils.add_days(date, -1, '%Y.%m.%d')
        invest_chart_data = [[date, 0, 0, 0, 0]]
        invest_daily = [[date, start_money, start_index_money, start_kospi, start_kosdaq]]
        for i in range(len(invest_data)):
            try:
                date = investY_date[i:i+1].values[0]
                invest = invest_data[i]
                close_scaled = invest[0]
                money = invest[1]
                stock_cnt = invest[2]
                kospi_amt = self.get_date_search_value(kospi, date, 'close')
                if kospi_amt == 0: continue
                kospi_percent = self.get_ratio(kospi_amt,start_kospi)
                kosdaq_amt = self.get_date_search_value(kosdaq, date, 'close')
                if kosdaq_amt == 0: continue
                kosdaq_percent = self.get_ratio(kosdaq_amt, start_kosdaq)
                close = DataUtils.inverse_scaled_data(scaler_close, close_scaled)
                eval_amt = money + close * stock_cnt
                eval_percent = self.get_ratio (eval_amt, start_money)
                eval_index_amt = money_index + close * stock_cnt_index
                eval_index_percent  = self.get_ratio (eval_index_amt, start_money)
                invest_chart_data.append([date, eval_percent, eval_index_percent, kospi_percent, kosdaq_percent])
                invest_daily.append([date, eval_amt, eval_index_amt, kospi_amt, kosdaq_amt])
            except Exception:
                pass
                #exc_type, exc_value, exc_traceback = sys.exc_info()
                #traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)

        #print(invest_chart_data)
        if self.params.debug == True:
            df_data = pd.DataFrame(invest_chart_data, columns=['date', 'invest', 'index', 'KOSPI', 'KOSDAQ'])
            self.draw_invest_seaborn(df_data, dir, corp_name)
            self.save_csv(df_data, dir, corp_name)
        return invest_daily
Ejemplo n.º 6
0
    def get_real_money(self, data_params, scaler_close, last_predict):
        """실제 가격을 가져온다."""

        invest_max_percent = self.params.invest_max_percent
        trade_min_percent = self.params.trade_min_percent

        close_scaled_money = data_params.testY[-1][0]
        close_money = DataUtils.inverse_scaled_data(scaler_close,
                                                    close_scaled_money)
        predict_money = DataUtils.inverse_scaled_data(scaler_close,
                                                      last_predict)
        if predict_money > close_money:
            trade_min_money = close_money * (1 + trade_min_percent / 100)
            trade_money = close_money + (predict_money - close_money) * (
                invest_max_percent / 100)
            if trade_money < trade_min_money:
                trade_money = trade_min_money
        else:
            trade_max_money = close_money * (1 - trade_min_percent / 100)
            trade_money = close_money - (close_money - predict_money) * (
                invest_max_percent / 100)
            if trade_money > trade_max_money:
                trade_money = trade_max_money
        return close_money, predict_money, trade_money
Ejemplo n.º 7
0
 def get_high_n_low(self, x, scaler_close):
     x_last = x[:, -1][0]
     x_high = DataUtils.inverse_scaled_data(scaler_close, x_last[2])
     x_low = DataUtils.inverse_scaled_data(scaler_close, x_last[3])
     return x_high, x_low
Ejemplo n.º 8
0
    def invest(self,
               comp_code: str,
               corp_name: str,
               tps: dict,
               invest_only: bool = False) -> InvestParams:
        """학습 후 모의 주식 거래를 한다."""

        ip = InvestParams()
        ip.predict_list, ip.last_predict, ip.test_predict = self.ensemble_predicts(
            comp_code, tps, invest_only)
        #print(ip.predict_list, ip.last_predict, ip.test_predict)

        tp = next(iter(tps.values()))
        investX = tp.data_params.investX

        #investY = data_params.investY
        invest_count = len(investX)
        ip.invest_money = self.params.invest_money
        #print('mockInvestment', 'invest', ip.invest_money)

        invest_line_trading = self.params.invest_line_trading
        now_stock_cnt = 0
        if self.params.index_money is not None:
            ip.index_money = self.params.index_money
        else:
            ip.index_money = ip.invest_money
        all_stock_count = now_stock_cnt

        invest_list = []
        index_invest_list = []

        before_scaled_close = None
        before_invest_predict = None
        now_scaled_close = None

        for i in range(invest_count):
            x = investX[i:i + 1]
            invest_predict = ip.predict_list[i][0]
            x_last = x[:, -1][0]
            now_scaled_close = x_last[0]
            if i != 0 and invest_line_trading == True:
                ip.invest_money, now_stock_cnt = self.invest_scaled_money_before(
                    before_scaled_close, before_invest_predict, x,
                    ip.invest_money, now_stock_cnt, tp.scaler_close)

            ip.invest_money, now_stock_cnt = self.invest_scaled_money(
                invest_predict, now_scaled_close, tp.scaler_close,
                ip.invest_money, now_stock_cnt)
            if i == 0:
                ip.index_money, all_stock_count = self.invest_scaled_money(
                    -1, now_scaled_close, tp.scaler_close, ip.index_money,
                    all_stock_count)
                index_invest_list.append(
                    [now_scaled_close, ip.index_money, all_stock_count])
                #print(ip.index_money, all_stock_count, scaler_close.inverse_transform(now_scaled_close)[0][0])
            before_scaled_close = now_scaled_close
            before_invest_predict = invest_predict
            invest_list.append(
                [now_scaled_close, ip.invest_money, now_stock_cnt])

        if now_scaled_close is not None:
            now_close = DataUtils.inverse_scaled_data(tp.scaler_close,
                                                      now_scaled_close)
            ip.invest_money += self.to_money(now_stock_cnt, now_close)
            ip.last_money = ip.invest_money
            ip.index_money += self.to_money(all_stock_count, now_close)
            invest_list.append([now_scaled_close, ip.invest_money, 0])
            index_invest_list.append([now_scaled_close, ip.index_money, 0])

            try:
                visualizer = InvestVisualizer(self.params)
                ip.daily_data = visualizer.draw_invests(
                    corp_name, invest_list, index_invest_list, tp.scaler_close,
                    tp.data_params)
            except Exception:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                traceback.print_exception(exc_type,
                                          exc_value,
                                          exc_traceback,
                                          file=sys.stdout)
        else:
            ip.last_money = ip.invest_money

        return ip