示例#1
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
示例#2
0
 def get_corps_maket_cap(self, date=None):
     if date == None:
         date = DateUtils.today_str()  # 오늘 날짜
     else:
         date = date.replace(".", "").replace("-", "")
     for i in range(30):
         try:
             year = date[0:4]
             file_path = os.path.join(self.DIR, "files", "corps_market_cap",
                                      year, "market_cap_" + date + ".txt")
             if not os.path.isfile(file_path):
                 master_data = self.get_coprs_master_price_from_krx(date)
                 market_cap = master_data[['종목코드', '시가총액']]
                 DataUtils.save_csv(market_cap, file_path)
             else:
                 market_cap = pd.read_csv(file_path)
             break
         except:
             print(date, "에 시가총액 데이터를 가져오는데 에러 발생하여 이전 데이터 사용")
             date = DateUtils.add_days(date, -i, '%Y%m%d')
     return market_cap
示例#3
0
    def get_coprs_master_price_from_krx(self, date=None):
        if date is None:
            date = DateUtils.today_str('%Y%m%d')
        else:
            date = date.replace(".", "").replace("-", "")
        df = None
        for i in range(30):
            date = DateUtils.add_days(date, -i, '%Y%m%d')

            # STEP 01: Generate OTP
            gen_otp_url = 'https://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx'
            gen_otp_data = {
                'name': 'fileDown',
                'filetype': 'csv',
                'url': 'MKD/04/0404/04040200/mkd04060200_01',
                'market_gubun': 'ALL',  # 시장구분: ALL=전체
                'indx_ind_cd': '',
                'sect_tp_cd': '',
                'schdate': date,
                'pagePath': '/contents/MKD/04/0404/04040200/MKD04040200.jsp',
            }

            r = requests.post(gen_otp_url,
                              gen_otp_data,
                              headers=self.KTX_HEADER)
            code = r.content  # 리턴받은 값을 아래 요청의 입력으로 사용.

            #STEP 02: download
            down_url = 'http://file.krx.co.kr/download.jspx'
            down_data = {'code': code}
            r = requests.post(down_url, down_data, headers=self.KTX_HEADER)
            df = pd.read_csv(BytesIO(r.content), header=0, thousands=',')
            if len(df) > 0:
                break

        return df