Simulator_Api.py 61.7 KB
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
import datetime
from sqlalchemy import *
import pymysql
from pandas import *

from Logger import *
import cf

class Simulator_Api:
    def __init__(self,simul_num,op,db_name):
        self.simul_num=int(simul_num)

        if self.simul_num==-1:
            self.set_date()

        elif op=='reset':
            self.op='reset'
            self.simul_reset=True
            self.set_variable()
            self.rotate_date()

        elif op=='real':
            self.op='real'
            self.simul_reset=False
            self.db_name=db_name
            self.set_variable()

        elif op=='continue':
            self.op='continue'
            self.simul_reset=False
            self.set_variable()
            self.rotate_date()

        else:
            logger.error("Invalid option")

    # 오늘 날짜를 설정하는 함수
    def set_date(self):
        self.today=datetime.datetime.today().strftime("%Y%m%d")
        self.today_with_time=datetime.datetime.today().strftime("%Y%m%d%H%M")
        self.today_form=datetime.datetime.strptime(self.today,"%Y%m%d").date()

    # 사용되는 변수를 설정하는 함수
    def set_variable(self):
        self.set_date()
        self.simul_end_date=self.today          # 시뮬레이션이 끝나는 날짜
        self.start_min="0900"                   # 장 시작 시간 : 9시

        self.use_min=False                      # 분별 시뮬레이션을 사용하는 변수
        self.use_nine=True                      # 9시에만 거래를 수행하는 변수
        self.buy_stop=False                     # 거래를 중지하는 변수
        self.trade_check_num=False              # 실시간 조건 매수 옵션. 분별 시뮬레이팅의 경우 True, 일별 시뮬레이팅의 경우 False

        print("simul_num : ",self.simul_num)

        if self.simul_num==1:
            self.simul_start_date="20190101"

            # 매수/매도 알고리즘 설정
            self.buy_algorithm=1
            self.sell_algorithm=1

            # 시뮬레이션 변수 설정
            self.start_invest_price=1000000     # 초기 투자자금
            self.invest_unit=100000             # 매수 금액 단위
            self.limit_money=300000             # 자산 중 최소로 남겨 둘 금액
            self.sell_point=10                  # 익절 수익률 기준
            self.losscut_point=-2               # 손절 수익률 기준

            self.invest_limit_rate=1.01         # 매수하는 순간 종목의 최신 종가보다 가격이 n%이상 상승했을 때는 매수하지 않음
            self.invest_min_limit_rate=0.98     # 매수하는 순간 종목의 최신 종가보다 가격이 n%이상 하락했을 경우 매수하지 않음

        elif self.simul_num==2:
            self.simul_start_date="20190101"

            self.buy_algorithm=2
            self.sell_algorithm=2

            self.start_invest_price=1000000
            self.invest_unit=100000
            self.limit_money=300000
            self.sell_point=10
            self.losscut_point=-2

            self.invest_buy_limit_rate=1.01
            self.invest_sell_limit_rate=0.98

        elif self.simul_num==3:
            self.simul_start_date = "20190101"

            self.buy_algorithm = 3
            self.sell_algorithm = 3

            self.start_invest_price = 1000000
            self.invest_unit = 100000
            self.limit_money = 300000
            self.sell_point = 10
            self.losscut_point = -2

            self.invest_buy_limit_rate = 1.01
            self.invest_sell_limit_rate = 0.98

        else:
            logger.error("Invalid simul_num")

        self.set_db_control()

        if self.op!='real':
            self.set_table()
            self.get_date_for_simul()

            self.total_valuation_profit=0                       # 매도 종목들에 대한 총 수익
            self.sum_valuation_profit=0                         # 실제 수익 = 매도종목에 대한 수익 + 현재 보유 종목의 수익
            self.total_invest_price=self.start_invest_price     # 총자산 : 투자금액 + 실제 수익
            self.total_purchase_price=0                         # 투자금
            self.d2_deposit=self.start_invest_price             # 예수금 = 초기자본 + 매도수익 - 투자금

            self.update_balance()                               # 일별 정산

            self.tax_rate=0.0025                                # 거래 세금
            self.fees_rate=0.00015                              # 거래 수수료

            self.simul_reset_lock=False                         # 시뮬레이터를 멈춘 지점부터 다시 돌릴 것인지를 선택하는 변수

    # database를 control하기 위한 eninge 및 connection을 저장하는 함수
    def set_db_control(self):
        # simul database에 접속하는 engine
        if self.op=='real':
            self.engine_simul=create_engine("mysql+pymysql://" + cf.db_id + ":" + cf.db_pw + "@" + cf.db_ip + ":" +
                                            cf.db_port + "/" + str(self.db_name), encoding='utf-8')
        else:
            self.db_name="simul"+str(self.simul_num)
            self.engine_simul=create_engine("mysql+pymysql://" + cf.db_id + ":" + cf.db_pw + "@" + cf.db_ip + ":" +
                                            cf.db_port + "/" + str(self.db_name), encoding='utf-8')
        # daily_craw database에 접속하는 engine
        # daily_craw        :   각 종목에 대해 날짜별 데이터를 저장하는 데이터베이스
        self.engine_daily_craw = create_engine("mysql+pymysql://" + cf.db_id + ":" + cf.db_pw + "@" + cf.db_ip + ":" +
                                          cf.db_port + "/daily_craw" , encoding='utf-8')
        # min_craw database에 접속하는 engine
        # min_craw          :   각 종목에 대해 분별 데이터를 저장하는 데디터베이스
        self.engine_craw = create_engine("mysql+pymysql://" + cf.db_id + ":" + cf.db_pw + "@" + cf.db_ip + ":" +
                                          cf.db_port + "/min_craw", encoding='utf-8')
        # daily_buy_list database에 접속하는 engine
        # daily_buy_list    :   날짜별로 종목에 대한 데이터를 저장하는 데이터베이스
        self.engine_daily_buy_list = create_engine("mysql+pymysql://" + cf.db_id + ":" + cf.db_pw + "@" + cf.db_ip + ":" +
                                          cf.db_port + "/daily_buy_list", encoding='utf-8')

        # mysql에 접속하는 객체 생성
        self.db_conn = pymysql.connect(
            host=cf.db_ip,
            port=int(cf.db_port),
            user=cf.db_id,
            password=cf.db_pw,
            charset='utf8'
        )

    # 데이터베이스와 테이블을 설정
    def set_table(self):
        # simul_reset==True인 경우, 시뮬레이터를 초기화하고 다시 구축
        if self.simul_reset:
            self.init_database()

        # simul_reset==False인 경우, 시뮬레이터를 초기화하지 않고 마지막으로 끝난 시점 부터 다시 구동
        else:
            # 시뮬레이터 데이터베이스, transaction 테이블, account_balance 테이블이 모두 존재하는 경우 이어서 시뮬레이션
            if (self.is_simul_database_exist() and
                    self.is_simul_table_exist(self.db_name,"transaction") and
                    self.is_simul_table_exist(self.db_name,"account_balance")):
                self.init_df_transaction()
                self.init_df_account_balance()
                self.last_simul_date=self.get_last_date_account_balance()
            # 필요한 데이터베이스와 테이블이 모두 존재하지 않는 경우, 다시 생성
            else:
                self.init_database()
                self.simul_reset=True

    # 시뮬레이터 데이터베이스 초기화
    def init_database(self):
        self.drop_database()
        self.create_database()
        self.init_df_account_balance()
        self.init_df_transaction()

    # 시뮬레이터 데이터베이스 삭제
    def drop_database(self):
        if self.is_simul_database_exist():
            query=f"drop DATABASE {self.db_name}"
            self.db_conn.cursor().execute(query)
            self.db_conn.commit()

    # 시뮬레이터 데이터베이스 생성
    def create_database(self):
        if not self.is_simul_database_exist():
            query=f"create DATABASE {self.db_name}"
            self.db_conn.cursor().execute(query)
            self.db_conn.commit()

    # 시뮬레이터 데이터베이스가 존재하는지 확인하는 함수
    def is_simul_database_exist(self):
        query = f"SELECT 1 FROM Information_schema.SCHEMATA WHERE SCHEMA_NAME = '{self.db_name}'"
        result=self.engine_daily_buy_list.execute(query).fetchall()
        if len(result):
            return True
        else:
            return False

    # 시뮬레이터 데이터베이스 안에 특정 이름을 가진 테이블이 존재하는지 확인하는 함수
    def is_simul_table_exist(self,db_name,table_name):
        query = f"select 1 from information_schema.tables where table_schema = '{db_name}' and table_name = '{table_name}'"
        result=self.engine_simul.execute(query).fetchall()
        if len(result)==1:
            return True
        else:
            return False

    # account_balance table 생성
    def init_df_account_balance(self):
        a_balance={'id':[]}
        self.account_balance=DataFrame(a_balance,
                                       columns=['date', 'today_earning_rate', 'sum_valuation_profit', 'total_profit',
                                                'today_profit','today_profitcut_count', 'today_losscut_count',
                                                'today_profitcut','today_losscut','d2_deposit', 'total_possess_count',
                                                'today_buy_count', 'total_invest',
                                                'sum_item_total_purchase', 'total_evaluation', 'today_rate',
                                                'today_invest_price','today_sell_price', 'volume_limit', 'sell_point',
                                                'invest_unit','limit_money', 'total_profitcut',
                                                'total_losscut','total_profitcut_count','total_losscut_count',
                                                'today_buy_today_sell_count','today_buy_today_possess_count',
                                                'today_buy_today_profitcut_count','today_buy_today_losscut_count',
                                                'today_buy_today_profitcut_rate','today_buy_today_losscut_rate'],
                                       index=a_balance['id'])

    # transaction table 생성
    def init_df_all_stocks(self):
        all_stocks={'id':[]}
        self.df_all_stocks=DataFrame(all_stocks,
                                     columns=['id', 'order_num', 'code', 'code_name', 'rate', 'purchase_rate',
                                              'purchase_price','present_price', 'valuation_price','valuation_profit',
                                              'holding_amount', 'buy_date', 'item_total_purchase','chegyul_check',
                                              'invest_unit','sell_date', 'sell_price', 'sell_rate',
                                              'yes_close','d1_diff_rate', 'd1_diff',
                                              'open', 'close','high','low','volume',
                                              'clo5', 'clo10', 'clo20', 'clo60','clo120',
                                              "clo5_diff_rate", "clo10_diff_rate","clo20_diff_rate",
                                              "clo60_diff_rate", "clo120_diff_rate"])

    # account_balance(잔고 데이터)에 저장된 가장 최근의 날짜를 가져오는 함수
    def get_last_date_account_balance(self):
        query = "SELECT date from account_balance order by date desc limit 1"
        result=self.engine_simul.execute(query).fechall()
        return result[0][0]

    # 시뮬레이팅 할 날짜 리스트를 가져오는 함수
    # 장이 열렸던 날을 self.date_rows에 담기 위해 gs글로벌의 date값을 이용
    def get_date_for_simul(self):
        query = f"select date from `gs글로벌` " \
                f"where date >= '{self.simul_start_date}' and date <= '{self.simul_end_date}' group by date"
        self.date_rows = self.engine_daily_craw.execute(query).fetchall()

    # 거래한 데이터를 바탕으로 거래이력(transaction) 테이블을 정산하는 함수
    def update_balance(self):
        # transaction table이 존재하지 않을 경우 return
        if not self.is_simul_table_exist(self.db_name,"transaction"):
            return

        query="select sum(valuation_profit) from transaction"
        self.sum_valuation_profit=self.engine_simul.execute(query).fethcall()[0][0]     # 총수익금 (종목별 평가 금액의 합)

        self.total_invest_price=self.start_invest_price+self.sum_valuation_profit       # 총자산

        query="select sum(item_total_purchase) from transaction where sell_date='%s'"
        self.total_purchase_price=self.engine_simul.execute(query%(0)).fethcall()[0][0] # 총투자금액
        if self.total_purchase_price is None:
            self.total_purchase_price=0

        query="select sum(valuation_profit) from transaction where sell_date!='%s'"
        self.total_valuation_profit=self.engine_simul.execute(query%(0)).fetchall()[0][0]   # 매도 종목들에 대한 수익
        if self.total_valuation_profit is None:
            self.total_valuation_profit=0

        self.d2_deposit=self.start_invest_price+self.total_valuation_profit-self.total_purchase_price   # 예수금

    # 날짜별로 돌아가면서 시뮬레이션을 실행하는 함수
    def rotate_date(self):
        for i in range(self.date_rows):
            date_rows_today=self.date_rows[i][0]        # 시뮬레이팅 할 날짜
            date_rows_yesterday=self.date_rows[i-1][0]  # 시뮬레이팅 하루 전 날짜

            # simul_reset=False인 경우, 시뮬레이터를 멈춘 지점부터 다시 시작
            if not self.simul_reset and not self.simul_reset_lock:
                if int(date_rows_today)<=int(self.last_simul_date):
                    continue
                else:
                    self.simul_reset_lock=True

            # 분별 시뮬레이션
            if self.use_min:
                self.simul_by_min(date_rows_today,date_rows_yesterday,i)
            # 일별 시뮬레이션
            else:
                self.simul_by_date(date_rows_today,date_rows_yesterday,i)
        # 시뮬레이션을 완료한 후 account_balance 테이블 업데이트
        self.arrange_account_balance()

    # 하루에 대한 시뮬레이션이 끝난 뒤 해당 날짜의 잔고(account_balance)정보를 업데이트하는 함수
    def arrange_account_balance(self):
        if self.engine_simul.dialect.has_table(self.engine_simul,"account_balance"):
            len_date=self.get_len_account_balance_data()
            query="select date from account_balance"
            rows=self.engine_simul.execute(query).fetchall()

            logger.debug("account balance 최종 정산")

            for i in range(len_date):
                # today_buy_count : 오늘 매수한 종목의 수
                query="update account_balance " \
                      "set " \
                      "today_buy_count=(select count(*) from (select code from transaction where buy_date like '%s')) "\
                      "where date='%s'"
                self.engine_simul.execute(query%("%%"+str(rows[i][0])+"%%",rows[i][0]))

                # today_buy_today_sell_count : 오늘 매수하고 오늘 매도한 종목의 수
                query="update account_balance " \
                      "set " \
                      "today_buy_today_sell_count=" \
                      "(select count(*) from " \
                      "(select code from transaction where buy_date like '%s' and sell_date!=0 group by code)) " \
                      "where date='%s'"
                self.engine_simul.execute(query%("%%"+str(rows[i][0])+"%%",rows[i][0]))

                # today_buy_today_possess_count : 오늘 매수하였으나 매도하지 않은 종목의 수
                query="update account_balance " \
                      "set" \
                      "today_buy_today_possess_count=" \
                      "(select count(*) from " \
                      "(select code from transaction where buy_date like '%s' and sell_date='%s' group by code)) " \
                      "where date='%s'"
                self.engine_simul.execute(query%("%%"+rows[i][0]+"%%",0,rows[i][0]))

                # today_buy_today_profitcut_count : 오늘 매수하고 익절한 종목의 수
                query="update account_balance " \
                      "set " \
                      "today_buy_today_profitcut_count=" \
                      "(select count(*) from " \
                      "(select code from transaction " \
                      "where buy_date like '%s' and sell_date like '%s' and sell_rate>'%s' group by code)) " \
                      "where date='%s'"
                self.engine_simul.execute(query%("%%" + rows[i][0] + "%%", "%%" + rows[i][0] + "%%", 0, rows[i][0]))

                # today_buy_today_profitcut_rate : 오늘 매수하고 익절한 종목의 수익률
                query = "update account_balance " \
                        "set " \
                        "today_buy_today_profitcut_rate=round(today_buy_today_profitcut_count /today_buy_count *100,2) "\
                        "where date = '%s'"
                self.engine_simul.execute(query%(rows[i][0]))

                # today_buy_today_losscut_count : 오늘 매수하고 손절한 종목의 수
                query = "update account_balance " \
                        "set " \
                        "today_buy_today_losscut_count=" \
                        "(select count(*) from " \
                        "(select code from transaction " \
                        "where buy_date like '%s' and sell_date like '%s' and sell_rate < '%s'  group by code)) " \
                        "WHERE date='%s'"
                self.engine_simul.execute(query%("%%" + rows[i][0] + "%%", "%%" + rows[i][0] + "%%", 0, rows[i][0]))

                # today_buy_today_losscut_rate : 오늘 매수하고 손절한 종목의 수익률
                query = "update account_balance " \
                        "set " \
                        "today_buy_today_losscut_rate=round(today_buy_today_losscut_count /today_buy_count *100,2) " \
                        "WHERE date = '%s'"
                self.engine_simul.execute(query%(rows[i][0]))

                # total_profitcut_count : 총 익절한 종목의 수
                query = "update account_balance " \
                        "set " \
                        "total_profitcut_count=" \
                        "(select count(*) from " \
                        "(select code from transaction where sell_rate >= '%s'  group by code)) "\
                        "WHERE date='%s'"
                self.engine_simul.execute(query%(0, rows[i][0]))

                # total_profitcut : 총 익절한 금액 (매도가 - 매수가)
                query = "update account_balance " \
                        "set " \
                        "total_profitcut=sum" \
                        "(select sell_price-purchase_price from transaction " \
                        "where sell_price>=purchase_price group by code))" \
                        "WHERE date = '%s'"
                self.engine_simul.execute(query%(rows[i][0]))

                # total_losscut_count : 총 손절한 종목의 수
                query = "update account_balance " \
                        "set " \
                        "total_losscut_count=" \
                        "(select count(*) from " \
                        "(select code from transaction where sell_rate < '%s'  group by code )) " \
                        "WHERE date='%s'"
                self.engine_simul.execute(query%(0,rows[i][0]))

                # total_losscut : 총 손절한 금액 (매수가 - 매도가)
                query = "update account_balance " \
                        "set " \
                        "total_losscut=sum" \
                        "(select purchase_price-sell_price from transaction " \
                        "where purchase_price>=sell_price)) " \
                        "where date='%s'"
                self.engine_simul.execute(query%(rows[i][0]))
        print("account balance 정산 완료")

    # account_balance에 저장된 일자를 반환하는 함수
    def get_len_account_balance_data(self):
        query="select date from account_balance"
        rows=self.engine_simul.execute(query).fetchall()
        return len(rows)

    # 분별 시뮬레이팅
    def simul_by_min(self, date_rows_today, date_rows_yesterday, i):
        print("**************************   date: " + date_rows_today)
        # 시뮬레이팅 전에 변수 초기화
        self.set_daily_variable()
        # daily_buy_list에 시뮬레이팅 할 날짜에 해당하는 테이블과 전 날 테이블이 존재하는지 확인
        if self.is_date_exist(date_rows_today) and self.is_date_exist(date_rows_yesterday):
            self.db_to_realtime_daily_buy_list(date_rows_today, date_rows_yesterday, i)     # 매수리스트 확인
            self.trading_by_min(date_rows_today, date_rows_yesterday, i)                    # 시뮬레이팅 시작
            self.db_to_account_balance(date_rows_today)                                     # 잔고 테이블 업데이트

            # transaction 테이블이 존재하고, 현재 보유 중인 종목이 있는 경우, 해당 종목에 대해 데이터베이스 업데이트
            if self.is_simul_table_exist(self.db_name, "transaction") and len(self.get_data_from_possessed_item()) != 0:
                self.update_transaction_by_date(date_rows_today, option='ALL')

        else:
            print("테이블이 존재하지 않습니다")

    # 매일 시뮬레이션이 돌기 전에 변수를 초기화하는 함수
    def set_daily_variable(self):
        self.buy_stop=False
        self.today_invest_price=0

    # daily_buy_list에 특정 날짜의 이름을 가진 테이블이 존재하는지 확인하는 함수
    def is_date_exist(self,date):
        query = f"select 1 from information_schema.tables where table_schema ='daily_buy_list' and table_name ='{date}'"
        result = self.engine_daily_buy_list.execute(query).fetchall()
        if len(result) == 1:
            return True
        else:
            return False

    # 매수 할 종목의 리스트를 선정하는 함수
    def db_to_realtime_daily_buy_list(self,date_rows_today,date_rows_yesterday,i):
        to_buy_list=None

        # (5,20) 골든크로스
        if self.buy_algorithm == 1:
            query=f"select * from '{date_rows_yesterday}' " \
                  f"where yes_clo20>yes_clo5 and clo5>clo20 and close<'{self.invest_unit}' group by code"
            to_buy_list=self.engine_daily_buy_list.execute(query).fetchall()

        # (20,60) 골든크로스
        elif self.buy_algorithm == 2:
            query = f"select * from '{date_rows_yesterday}' " \
                    f"where yes_clo40 > yes_clo5 and clo5 > clo40 and close < '{self.invest_unit}' group by code"
            to_buy_list = self.engine_daily_buy_list.execute(query).fetchall()

        else:
            logger.error("Invalid Algorithm Setting...")

        # 알고리즘에 의해 선택된 항목이 존재한다면 데이터베이스에 해당 항목 업데이트
        if len(to_buy_list) > 0:
            df_to_buy_list = DataFrame(to_buy_list,
                                       columns=['index', 'index2', 'date', 'check_item', 'code',
                                                'code_name', 'd1_diff','d1_diff_rate',
                                                'close', 'open', 'high','low', 'volume',
                                                'clo5', 'clo10', 'clo20', 'clo60', 'clo120',
                                                "clo5_diff_rate", "clo10_diff_rate", "clo20_diff_rate",
                                                "clo60_diff_rate", "clo120_diff_rate",
                                                'yes_clo5', 'yes_clo10', 'yes_clo20', 'yes_clo60','yes_clo120',
                                                'vol5', 'vol10', 'vol20', 'vol60', 'vol120'])

            # to_buy_list 중 종목 code가 6자리의 정수로 된 항목만 선택
            to_buy_list['code'] = to_buy_list['code'].apply(lambda x: "{:0>6d}".format(int(x)))

            # 시뮬레이터
            if self.op != 'real':
                to_buy_list['check_item'] = int(0)
                to_buy_list.to_sql('realtime_daily_buy_list', self.engine_simul, if_exists='replace')

                # 현재 보유 중인 종목은 매수 리스트(realtime_daily_buy_list) 에서 제거
                if self.is_simul_table_exist(self.db_name, "transaction"):
                    query = "delete from realtime_daily_buy_list " \
                            "where code in " \
                            "(select code from transaction where sell_date = '0')"
                    self.engine_simul.execute(query)

                # realtime_daily_buy_list 테이블에 저장 된 종목들을 저장
                self.get_realtime_daily_buy_list()

            # 모의투자 / 실전투자
            else:
                to_buy_list['check_item'] = int(0)
                to_buy_list.to_sql('realtime_daily_buy_list', self.engine_simul, if_exists='replace')

                # 현재 보유 중인 종목들은 삭제
                query = "delete from realtime_daily_buy_list where code in (select code from possessed_item)"
                self.engine_simul.execute(sql)
        else:
            self.len_df_realtime_daily_buy_list = 0

    # realtime_daily_buy_list 테이블의 매수 리스트를 가져오는 함수
    def get_realtime_daily_buy_list(self):
        # check_item = 매수 했을 시 날짜. 매수 하지 않았을 때는 0
        query = "select * from realtime_daily_buy_list where check_item = '0' group by code"
        realtime_daily_buy_list=self.engine_simul.execute(query).fetchall()

        self.df_realtime_daily_buy_list=DataFrame(realtime_daily_buy_list,
                                                  columns=['index', 'index2', 'date', 'check_item', 'code',
                                                           'code_name', 'd1_diff','d1_diff_rate',
                                                           'close', 'open', 'high','low', 'volume',
                                                           'clo5', 'clo10', 'clo20', 'clo60', 'clo120',
                                                           "clo5_diff_rate", "clo10_diff_rate", "clo20_diff_rate",
                                                           "clo60_diff_rate", "clo120_diff_rate",
                                                           'yes_clo5', 'yes_clo10', 'yes_clo20', 'yes_clo60','yes_clo120',
                                                           'vol5', 'vol10', 'vol20', 'vol60', 'vol120'])

        self.len_df_realtime_daily_buy_list = len(self.df_realtime_daily_buy_list)

    # 분별 시뮬레이팅 함수
    # 기능 : 새로운 종목 매수 / 보유종목 매도 / 보유종목 업데이트
    def trading_by_min(self,date_rows_today,date_rows_yesterday,i):
        self.show_info(date_rows_today)

        # 현재 보유중인 종목이 존재한다면, 보유 종목의 주가를 업데이트
        if self.is_simul_table_exist(self.db_name,"transaction"):
            self.update_transaction_by_date(date_rows_today,option='OPEN')

        # 분별 시간 데이터를 가져오기
        self.get_min_data_for_simul(date_rows_today)
        if len(self.min_data_rows)!=0:
            # 분 단위로 시뮬레이팅
            for t in range(len(self.min_data_rows)):
                min=self.min_data_rows[t][0]
                # 현재 보유 종목이 있는 경우
                if self.is_simul_table_exist(self.db_name,"account_balance"):
                    self.show_info(min)
                    # 종목 데이터 업데이트
                    self.update_transaction_by_min(min)
                    self.update_transaction_etc()
                    # 매도
                    self.auto_trade_sell_stock(min,i)

                    # 매수를 진행할 금액이 남아있는 경우
                    if not self.buy_stop and self.check_balance():
                        # 매수할 종목리스트 저장
                        self.get_realtime_daily_buy_list()
                        # 매수할 종목이 존재한다면 매수
                        if self.len_df_realtime_daily_buy_list>0:
                            self.auto_trade_buy_stock(min,date_rows_today,date_rows_yesterday)
                        else:
                            print("금일 매수할 종목이 없습니다")
                # 보유 종목이 없는 경우
                else:
                    if not self.buy_stop and self.check_balance():
                        self.auto_trade_buy_stock(min,date_rows_today,date_rows_yesterday)

                if not self.buy_stop and self.use_nine:
                    print("9시 매수를 종료합니다")
                    self.buy_stop=True

    # 시뮬레이팅 정보를 출력하는 함수
    def show_info(self,date):
        print("simulator num : ",self.simul_num)
        if self.is_simul_table_exist(self.db_name,"transaction"):
            print("simulating 시간 : ",date)
            print("보유종목 수 : ",self.get_count_possess_item())

    # 현재 보유하고 있는 종목수를 반환하는 함수
    def get_count_possess_item(self):
        query="select count(*) from transaction where sell_date='0'"
        result=self.engine_simul.execute(query).fetchall()
        return result[0][0]

    # 보유 종목의 주가를 일별로 업데이트하는 함수
    def update_transaction_by_date(self,date,option='ALL'):
        possess_item_list=self.get_data_from_possess_item()

        if len(possess_item_list)==0:
            print("보유 종목이 없습니다")

        for i in range(len(possess_item_list)):
            code_name=possess_item_list[i][0]
            result=self.get_current_price_by_date(code_name,date)
            if result==False:
                continue
            d1_diff_rate = result[0][0]
            close = result[0][1]
            open = result[0][2]
            high = result[0][3]
            low = result[0][4]
            volume = result[0][5]
            clo5 = result[0][6]
            clo10 = result[0][7]
            clo20 = result[0][8]
            clo60 = result[0][9]
            clo120 = result[0][10]

            if open:
                self.db_to_transaction_update(code_name,d1_diff_rate,close,open,high,low,volume,
                                                  clo5,clo10,clo20,clo60,clo120,option)
            else:
                continue

    # 보유한 종목의 이름을 반환하는 함수
    def get_data_from_possess_item(self):
        query="select code_name from transaction where sell_date='0'"
        result=self.engine_simul.execute(query).fetchall()
        return result[0][0]

    # daily_buy_list를 통해 특정 날짜에 해당하는 주가정보를 가져오는 함수
    def get_current_price_by_date(self,code_name,date):
        query = f"select d1_diff_rate, close, open, high, low, volume, clo5, clo10, clo20, clo60, clo120 from `{date}` " \
                f"where code_name = '{code_name}' group by code"
        result=self.engine_daily_buy_list.execute(query).fetchall()

        if len(result)==1:
            return result
        else:
            return False

    # 현재의 주가를 거래이력(transaction)에 있는 보유 종목에 반영
    def db_to_transaction_update(self,code_name,d1_diff_rate,close,open,high,low,volume,
                                     clo5,clo10,clo20,clo60,clo120,option='ALL'):
        # 모의투자 / 실전투자의 경우 현재가를 종가로 업데이트
        if self.op=='real':
            present_price=close
        # 시뮬레이터의 경우 현재가를 시가로 업데이트
        else:
            present_price=open

        # option==ALL이면 모든 데이터를 업데이트
        if option=="ALL":
            query = f"update transaction " \
                    f"set " \
                    f"d1_diff_rate = {d1_diff_rate}, " \
                    f"close = {close}, open = {open}, high = {high}, low = {low}, volume = {volume}, " \
                    f"present_price = {present_price}, " \
                    f"clo5 = {clo5}, clo10 = {clo10}, clo20 = {clo20}, clo60 = {clo60}, clo120 = {clo120} " \
                    f"where code_name = '{code_name}' and sell_date = {0}"
        # option==open이면 open,present_price값만 업데이트
        else:
            query = f"update transaction " \
                    f"set " \
                    f"open = {open}, present_price = {present_price} " \
                    f"where code_name = '{code_name}' and sell_date = {0}"

        self.engine_simul.execute(query)

    # 분별 데이터를 가져오는 함수
    def get_min_data_for_simul(self,simul_start_date):
        simul_start_date_min=simul_start_date+self.start_min    # 장 시작시간 = 9시
        simul_end_date_min=simul_start_date+"1530"              # 장 마감시간 = 3시 30분

        query = f"select date from `gs글로벌` " \
                f"where date >= '{simul_start_date_min}' and date <='{simul_end_date_min}' and open != 0 group by date"
        self.min_data_rows = self.engine_craw.execute(query).fetchall()

    # 거래이력(transaction)의 시세(close) 데이터를 분 별로 업데이트
    def update_transaction_by_min(self,min):
        possess_item=self.get_data_from_possess_item()
        for i in range(len(possess_item)):
            code_name=possess_item[i][0]
            current_close_price=self.get_current_close_price_by_min(code_name,min)
            if current_close_price:
                self.db_to_transaction_update_present_price_by_min(code_name,current_close_price)
            else:
                continue

    # 분별 현재 종가(close)를 가져오는 함수
    # 분별 데이터에서 종가는 현재가를 의미하므로 1분마다 시세를 가져오는 함수
    def get_current_close_price_by_min(self,code_name,min):
        query=f"select close from '{code_name}' " \
              f"where date='{min}' and open!=0 and volume!=0 order by sum_volume desc limit 1"
        result=self.engine_craw.execute(query).fethcall()
        if len(result)==1:
            return result[0][0]
        else:
            return False

    # 보유한 종목에 현재가를 실시간으로 업데이트하는 함수
    def db_to_transaction_update_present_price_by_min(self,code_name,current_close_price):
        query=f"update transaction set present_price={current_close_price} " \
              f"where code_name={code_name} and sell_date='{0}'"
        self.engine_simul.execute(query)

    # 잔고 테이블의 주가 이외의 기타 정보를 업데이트
    def update_transaction_etc(self):
        # valuation_price : 평가금액
        # 평가금액 = (보유주 현재가 * 보유주 수량) - (총 구매금액 * 수수료) - (보유주 현재가 * 보유주 수량 * (수수료 + 세금))
        query = f"update transaction " \
              f"set " \
              f"valuation_price = " \
              f"round((present_price  * holding_amount) - item_total_purchase * {self.fees_rate} - " \
              f"present_price*holding_amount*{self.fees_rate + self.tax_rate}) " \
              f"where sell_date = '{0}'"
        self.engine_simul.execute(query)

        # rate              : 현재 실시간 수익률
        # valuation_profit  : 수익 금액
        # 수익 금액 = 평가금액 - 총 구매금액
        # 수익률   = 수익금액 / 구매금액 * 100
        query = "update account_balance " \
                "set " \
                "rate= round((valuation_price - item_total_purchase)/item_total_purchase*100,2), " \
                "valuation_profit = valuation_price - item_total_purchase " \
                "where sell_date = '0';"
        self.engine_simul.execute(query)

    # 매도 함수
    def auto_trade_sell_stock(self,date,i):
        # 매도할 리스트를 저장
        sell_list=self.get_sell_list(i)

        for j in range(len(sell_list)):
            sell_code=sell_list[j][0]
            sell_rate=sell_list[j][1]
            present_price=sell_list[j][2]
            valuation_profit=sell_list[j][3]

            if sell_rate<0:
                print("손절 매도!")
                print("=========================================")
                print("종목 코드    : ",sell_code)
                print("수익        : ",valuation_profit)
                print("수익률       : ",sell_rate)
                print("=========================================")

            else:
                print("익절 매도!")
                print("=========================================")
                print("종목 코드    : ",sell_code)
                print("수익        : ",valuation_profit)
                print("수익률       : ",sell_rate)
                print("=========================================")

            # 매도 결과를 데이터베이스에 반영
            self.send_sell_order(date,present_price,sell_rate,sell_code)

    # 매도한 결과를 transaction에 반영하는 함수
    def send_sell_order(self,min,sell_price,sell_rate,code):
        query=f"update transaction " \
              f"set " \
              f"sell_date='{min}', sell_price='{sell_price}', sell_rate='{sell_rate}' " \
              f"where code='{code}' and sell_date='{0}' order by buy_date desc limit 1"
        self.engine_simul.execute(query)
        # 매도 후 정산
        self.update_balance()

    # 매도함수를 이용하여 매도할 종목을 가져오는 함수
    def get_sell_list(self,i):
        sell_list=None

        # (5,20) 데드크로스
        # 또는 손절 기준 수익률 이하로 떨어졌을 경우 매도
        if self.sell_algorithm==1:
            query=f"select code,rate, present_price,valuation_price from transaction " \
                  f"where sell_date='0' and (clo5<clo20 or rate<='{self.losscut_point}') group by code"
            sell_list=self.engine_simul.execute(query).fetchall()

        # (20,60) 데드크로스
        elif self.sell_algorithm==2:
            query=f"select code,rate, present_price,valuation_price from transaction " \
                  f"where sell_date='0' and (clo20<clo60 or rate<='{self.losscut_point}') group by code"
            sell_list=self.engine_simul.execute(query).fetchall()

        # RSI
        #elif self.sell_algorithm==3:
        # RMI
        #elif self.sell_algorithm==4:

        else:
            logger.error("Invalid sell algorithm setting...")

        return sell_list

    # 남은 금액을 확인하는 함수
    # 남은 금액이 최소 보유금 + 투자단위금액 이상이면 True, 아니면 False 반환
    def check_balance(self):
        if int(self.d2_deposit)>=int(self.limit_money)+int(self.invest_unit):
            return True
        else:
            return False

    # 매수 함수
    def auto_trade_buy_stock(self,min,date_rows_today,date_rows_yesterday):
        # self.df_realtime_daily_buy_list에 있는 모든 종목을 매수
        for i in range(self.len_df_realtime_daily_buy_list):
            if self.check_balance():
                code=self.df_realtime_daily_buy_list.loc[i,'code'].rjust(6,"0")
                code_name=self.df_realtime_daily_buy_list.loc[i,'code_name']

                # 분별 시뮬레이팅인 경우
                if self.use_min:
                    # 분별 종목데이터가 존재하지 않는 항목이라면 매수하지 않음
                    if not self.is_min_craw_table_exist(code_name):
                        continue
                # 일별 시뮬레이팅인 경우
                else:
                    # 일별 종목데이터가 존재하지 않는 항목이라면 매수하지 않음
                    if not self.is_daily_craw_table_exist(code_name):
                        continue

                # 일별 시뮬레이팅인 경우
                if not self.use_min:
                    price=self.get_current_open_price_by_date(code,date_rows_today)
                else:
                    price=self.get_current_close_price_by_min(code_name,min)

                # 전날 종가를 저장
                yes_close=self.get_yes_close_price_by_date(code,date_rows_yesterday)

                # 종목명 또는 시작가가 존재하지 않는다면 매수하지 않음
                if code_name==False or price==0 or price==False:
                    continue

                # 분별 시뮬레이팅인 경우
                if self.use_min and not self.use_nine and self.trade_check_num:
                    open=self.get_current_open_price_by_date(code,date_rows_today)  # 시가
                    sum_volume=self.get_current_volume_by_min(code_name,min)        # 당일 누적 거래량

                    if open and sum_volume:
                        # 실시간 매수조건에 부합하지 않는 경우 매수하지 않음
                        if not self.check_trade(self.df_realtime_daily_buy_list.loc[i],open,price,sum_volume):
                            continue

                self.send_buy_order(min,code,code_name,price,yes_close,i)
            else:
                break

    # min_craw 데이터베이스에 code_name 테이블이 존재하는지 확인하는 함수
    def is_min_craw_table_exist(self,code_name):
        query = f"select 1 from information_schema.tables where table_schema = 'min_craw' and table_name = '{code_name}'"
        result = self.engine_craw.execute(query).fetchall()
        if len(result) == 1:
            return True
        else:
            return False

    # daily_craw 데이터베이스에 code_name 테이블이 존재하는지 확인하는 함수
    def is_daily_craw_table_exist(self,code_name):
        query = f"select 1 from information_schema.tables where table_schema = 'daily_craw' and table_name = '{code_name}'"
        result = self.engine_daily_craw.execute(query).fetchall()
        if len(result) == 1:
            return True
        else:
            return False

    # 특정 날짜의 테이블에서 특정 종목의 시가를 가져오는 함수
    def get_current_open_price_by_date(self,code,date):
        query=f"select open from `{date}` where code = '{code}' group by code"
        open=self.engine_daily_buy_list.execute(query).fetchall()
        if len(open)==1:
            return open[0][0]
        else:
            return False

    # 전날 종가(close)를 가져오는 함수
    def get_yes_close_price_by_date(self,code,date):
        query = f"select close from `{date}` where code = '{code}' group by code"
        result = self.engine_daily_buy_list.execute(query).fetchall()
        if len(result) == 1:
            return result[0][0]
        else:
            return False

    # 분별 현재 누적 거래량을 가져오는 함수
    def get_current_volume_by_min(self,code_name,min):
        query= f"select sum_volume from `{code_name}` " \
               f"where date = '{min}' and open != 0 and volume !=0 order by sum_volume desc limit 1"
        result = self.engine_craw.execute(query).fetchall()
        if len(result) == 1:
            return result[0][0]
        else:
            return False

    # 실시간 주가를 분석하여 매수 여부를 결정하는 함수
    # param     :   df_row - 매수 종목 리스트
    #               open_price - 시가
    #               current_price - 현재가
    #               current_sum_volume - 현재 누적 거래량
    # return    :   True인 경우 매수, False인 경우 매수하지 않음
    def check_trade(self,df_row,open_price,current_price,current_sum_volume):
        code_name = df_row['code_name']
        yes_vol20 = df_row['vol20']
        yes_close = df_row['close']
        yes_high = df_row['high']
        yes_low = df_row['low']
        yes_volume = df_row['volume']

        # 실시간 거래 대금 체크 알고리즘
        # 어제 종가 보다 현재가가 증가했고, 거래 대금이 어제 거래대금에 비해서 x배 올라갔을 때 매수
        if self.trade_check_num == 1:
            yes_total_tr_price = yes_close * yes_volume                     # 전날 거래 대금
            current_total_tr_price = current_price * current_sum_volume     # 현재 거래 대금

            if current_price > yes_close and current_total_tr_price > yes_total_tr_price * self.volume_up:
                return True
            else:
                return False

        # 현재가가 매수 가격 최저 범위와 매수 가격 최고 범위 안에 들어와 있다면 매수
        elif self.trade_check_num == 2:
            min_buy_limit = int(yes_close) * self.invest_min_limit_rate     # 매수가격 최저 범위
            max_buy_limit = int(yes_close) * self.invest_limit_rate         # 매수가격 최고 범위

            if min_buy_limit < current_price < max_buy_limit:
                return True
            else:
                return False

        # 래리 윌리엄스 변동성 돌파 알고리즘(매수)
        elif self.trade_check_num == 3:
            # 변동폭(range): 전일 고가(yes_high)에서 전일 저가(yes_low)를 뺀 가격
            # 매수시점 : 현재가 > 시작가 + (변동폭 * k)  [k는 0~1 사이 수]
            range = yes_high - yes_low
            if open_price + range * self.rarry_k < current_price:
                return True
            else:
                return False

        else:
            logger.error("Invalid trade_check_num")

    # 데이터베이스에 매수 내역 업데이트
    def send_buy_order(self,date,code,code_name,price,yes_close,j):
        # 가격이 invest_unit보다 작은 경우 매수
        if price < self.invest_unit:
            # 매수하는 경우 account_balance에 해당 내역을 추가
            self.db_to_transaction(date,self.df_realtime_daily_buy_list,j,code,code_name,price,yes_close)

            # 매수를 성공적으로 했으면 realtime_daily_buy_list 테이블의 check_item 에 매수 시간을 설정
            self.update_realtime_daily_buy_list(code, date)

            # 정산
            self.update_balance()

    # transaction 테이블에 추가하는 함수
    def db_to_transaction(self,min,df,index,code,code_name,purchase_price,yesterday_close):
        self.df_transaction.loc[0,'code']=code
        self.df_transaction.loc[0,'code_name']=code_name
        self.df_transaction.loc[0,'rate']=float(-0.33)

        if yesterday_close:
            self.df_transaction.loc[0, 'purchase_rate'] = round(
                (float(purchase_price) - float(yesterday_close)) / float(yesterday_close) * 100, 2)

        self.df_transaction.loc[0, 'purchase_price'] = purchase_price
        self.df_transaction.loc[0, 'present_price'] = purchase_price

        self.df_transaction.loc[0, 'holding_amount'] = int(self.invest_unit / purchase_price)
        self.df_transaction.loc[0, 'buy_date'] = min
        self.df_transaction.loc[0, 'item_total_purchase'] = self.df_transaction.loc[0, 'purchase_price'] * \
                                                            self.df_transaction.loc[0, 'holding_amount']

        self.today_invest_price = self.today_invest_price + self.df_transaction.loc[0, 'item_total_purchase']

        self.df_transaction.loc[0, 'chegyul_check'] = 0
        self.df_transaction.loc[0, 'id'] = 0
        self.df_transaction.loc[0, 'invest_unit'] = self.invest_unit

        self.df_transaction.loc[0, 'yes_close'] = yesterday_close
        self.df_transaction.loc[0, 'close'] = df.loc[index, 'close']

        self.df_transaction.loc[0, 'open'] = df.loc[index, 'open']
        self.df_transaction.loc[0, 'high'] = df.loc[index, 'high']
        self.df_transaction.loc[0, 'low'] = df.loc[index, 'low']
        self.df_transaction.loc[0, 'volume'] = df.loc[index, 'volume']

        self.df_transaction.loc[0, 'd1_diff_rate'] = float(df.loc[index, 'd1_diff_rate'])
        self.df_transaction.loc[0, 'clo5'] = df.loc[index, 'clo5']
        self.df_transaction.loc[0, 'clo10'] = df.loc[index, 'clo10']
        self.df_transaction.loc[0, 'clo20'] = df.loc[index, 'clo20']
        self.df_transaction.loc[0, 'clo60'] = df.loc[index, 'clo40']
        self.df_transaction.loc[0, 'clo120'] = df.loc[index, 'clo60']

        if df.loc[index, 'clo5_diff_rate'] is not None:
            self.df_transaction.loc[0, 'clo5_diff_rate'] = float(df.loc[index, 'clo5_diff_rate'])
        if df.loc[index, 'clo10_diff_rate'] is not None:
            self.df_transaction.loc[0, 'clo10_diff_rate'] = float(df.loc[index, 'clo10_diff_rate'])
        if df.loc[index, 'clo20_diff_rate'] is not None:
            self.df_transaction.loc[0, 'clo20_diff_rate'] = float(df.loc[index, 'clo20_diff_rate'])
        if df.loc[index, 'clo60_diff_rate'] is not None:
            self.df_transaction.loc[0, 'clo40_diff_rate'] = float(df.loc[index, 'clo40_diff_rate'])
        if df.loc[index, 'clo120_diff_rate'] is not None:
            self.df_transaction.loc[0, 'clo60_diff_rate'] = float(df.loc[index, 'clo60_diff_rate'])

        self.df_transaction.loc[0, 'valuation_profit'] = int(0)

        self.df_transaction=self.df_transaction.fillna(0)

        # 거래이력 테이블이 이미 존재한다면 데이터 추가
        if self.is_simul_table_exist(self.db_name, "transaction"):
            self.df_transaction.to_sql('transaction', self.engine_simul, if_exists='append')
        # 테이블이 존재하지 않는다면 생성
        else:
            self.df_transaction.to_sql('transaction', self.engine_simul, if_exists='replace')

    # 매수할 리스트(realtime_daily_buy_list)에서 특정 종목을 매수한 경우 check_item칼럼에 매수한 날짜를 저장하는 함수
    def update_realtime_daily_buy_list(self,code,min):
        query = f"update realtime_daily_buy_list set check_item = '{min}' where code = '{code}'"
        self.engine_simul.execute(query)

    # account_balance(잔고) 테이블을 생성 및 데이터를 추가하는 함수
    def db_to_account_balance(self,date_rows_today):
        self.update_balance()
        # 거래이력(transaction)테이블이 존재하지 않는다면 return
        if not self.is_simul_table_exist(self.db_name,"transaction"):
            return

        columns = ['date', 'today_earning_rate', 'sum_valuation_profit', 'total_profit',
                   'today_profit', 'today_profitcut_count', 'today_losscut_count',
                   'today_profitcut', 'today_losscut', 'd2_deposit', 'total_possess_count',
                   'today_buy_count','total_invest',
                   'sum_item_total_purchase', 'total_evaluation', 'today_rate',
                   'today_invest_price', 'today_sell_price', 'volume_limit', 'sell_point',
                   'invest_unit', 'limit_money', 'total_profitcut',
                   'total_losscut', 'total_profitcut_count', 'total_losscut_count']

        self.account_balance.loc[0,'date']=date_rows_today                                          # 구매일
        self.account_balance.loc[0, 'sum_valuation_profit'] = self.sum_valuation_profit             # 총평가금액
        self.account_balance.loc[0, 'total_profit'] = self.total_valuation_profit                   # 총수익
        self.account_balance.loc[0, 'today_profit'] = self.get_today_profit(date_rows_today)        # 당일수익

        self.account_balance.loc[0, 'today_profitcut_count'] = self.get_today_profitcut_count(date_rows_today)  # 당일 익절종목 수
        self.account_balance.loc[0, 'today_losscut_count'] = self.get_today_losscut_count(date_rows_today)      # 당일 손절종목 수
        self.account_balance.loc[0, 'today_profitcut'] = self.get_sum_today_profitcut(date_rows_today)          # 당일 익절금액
        self.account_balance.loc[0, 'today_losscut'] = self.get_sum_today_losscut(date_rows_today)              # 당일 손절금액

        self.account_balance.loc[0, 'd2_deposit'] = self.d2_deposit                                 # 예수금
        self.account_balance.loc[0, 'total_possess_count'] = self.get_total_possess_count()         # 보유종목 수
        self.account_balance.loc[0, 'today_buy_count'] = 0                                          # 오늘 구매한 종목수
        self.account_balance.loc[0, 'total_invest'] = self.total_invest_price                       # 총 투자금액

        self.account_balance.loc[0, 'sum_item_total_purchase'] = self.get_sum_item_total_purchase() # 총매입금액
        self.account_balance.loc[0, 'total_evaluation'] = self.get_sum_valuation_price()            # 총평가금액
        try:
            self.account_balance.loc[0, 'today_rate'] = round(
                (float(self.account_balance.loc[0, 'total_evaluation']) -
                 float(self.account_balance.loc[0, 'sum_item_total_purchase'])) /
                float(self.account_balance.loc[0, 'sum_item_total_purchase']) * (100 - 0.33), 2)    # 당일 기준 수익률
        except ZeroDivisionError:
            pass

        self.account_balance.loc[0, 'today_invest_price'] = float(self.today_invest_price)          # 당일 투자금액
        self.account_balance.loc[0, 'today_sell_price'] = self.get_sum_today_sell_price(date_rows_today)
        self.account_balance.loc[0, 'volume_limit'] = self.volume_limit
        self.account_balance.loc[0, 'sell_point'] = self.sell_point
        self.account_balance.loc[0, 'invest_unit'] = self.invest_unit

        self.account_balance.loc[0, 'limit_money'] = self.limit_money
        self.account_balance.loc[0, 'total_profitcut'] = self.get_sum_total_profitcut()
        self.account_balance.loc[0, 'total_losscut'] = self.get_sum_total_losscut()
        self.account_balance.loc[0, 'total_profitcut_count'] = self.get_sum_total_profitcut_count()
        self.account_balance.loc[0, 'total_losscut_count'] = self.get_sum_total_losscut_count()

        # 데이터베이스에 테이블 추가
        self.account_balance.to_sql('account_balance', self.engine_simul, if_exists='append')

        # 매도종목에 대한 당일 수익
        query = f"update account_balance " \
                f"set " \
                f"today_earning_rate =round(today_profit / total_invest * 100, 2) WHERE date='{date_rows_today}'"
        self.engine_simul.execute(query)

    # 당일 수익을 계산하는 함수
    def get_today_profit(self,date):
        query="SELECT sum(valuation_profit) from transaction where sell_date like '%s'"
        result=self.engine_simul.execute(query%("%%"+date+"%%")).fetchall()
        return result[0][0]

    # 당일 익절 종목 수를 반환하는 함수
    def get_today_profitcut_count(self,date):
        query = "SELECT count(code) from transaction where sell_date like '%s' and sell_rate>='%s'"
        return self.engine_simul.execute(query % ("%%" + date + "%%", 0)).fetchall()[0][0]

    # 당일 손절 종목 수를 반환하는 함수
    def get_today_losscut_count(self, date):
        query = "SELECT count(code) from transaction where sell_date like '%s' and sell_rate<'%s'"
        return self.engine_simul.execute(query % ("%%" + date + "%%", 0)).fetchall()[0][0]

    # 당일 익절 금액을 반환하는 함수
    def get_sum_today_profitcut(self, date):
        query = "SELECT sum(valuation_profit) from transaction where sell_date like '%s' and valuation_profit >= '%s' "
        return self.engine_simul.execute(query % ("%%" + date + "%%", 0)).fetchall()[0][0]

    # 당일 손절 금액을 반환하는 함수
    def get_sum_today_losscut(self, date):
        query = "SELECT sum(valuation_profit) from transaction where sell_date like '%s' and valuation_profit < '%s' "
        return self.engine_simul.execute(query % ("%%" + date + "%%", 0)).fetchall()[0][0]

    # 총 보유한 종목 수를 반환하는 함수
    def get_total_possess_count(self):
        query = "select count(code) from transaction where sell_date = '%s'"
        return self.engine_simul.execute(query % (0)).fetchall()[0][0]

    # 총 매입금액을 계산하는 함수
    def get_sum_item_total_purchase(self):
        query = "SELECT sum(item_total_purchase) from transaction where sell_date = '%s'"
        result = self.engine_simul.execute(query % (0)).fetchall()[0][0]
        if result is not None:
            return result
        else:
            return 0

    # 총평가금액을 계산하는 함수
    def get_sum_valuation_price(self):
        query = "SELECT sum(valuation_price) from transaction where sell_date = '%s'"
        result = self.engine_simul.execute(query % (0)).fetchall()[0][0]
        if result is not None:
            return result
        else:
            return 0

    # 당일 매도금액을 계산하는 함수
    def get_sum_today_sell_price(self, date):
        query = "SELECT sum(valuation_price) from transaction where sell_date like '%s'"
        return self.engine_simul.execute(query % ("%%" + date + "%%")).fetchall()[0][0]

    # 총 익절금액을 계산하는 함수
    def get_sum_total_profitcut(self):
        query = "SELECT sum(valuation_profit) from transaction where sell_date != 0 and valuation_profit >= '%s' "
        return self.engine_simul.execute(query % (0)).fetchall()[0][0]

    # 총 손절금액을 계산하는 함수
    def get_sum_total_losscut(self):
        query = "SELECT sum(valuation_profit) from transaction where sell_date != 0 and valuation_profit < '%s' "
        return self.engine_simul.execute(query % (0)).fetchall()[0][0]

    # 총 익절종목수를 반환하는 함수
    def get_sum_total_profitcut_count(self):
        query = "select count(code) from transaction where sell_date != 0 and valuation_profit >= '%s'"
        return self.engine_simul.execute(query % (0)).fetchall()[0][0]

    # 총 손절종목수를 반환하는 함수
    def get_sum_total_losscut_count(self):
        query = "select count(code) from transaction where sell_date != 0 and valuation_profit < '%s' "
        return self.engine_simul.execute(query % (0)).fetchall()[0][0]

    # 보유종목의 종목명을 반환하는 함수
    def get_data_from_possessed_item(self):
        query="SELECT code_name from transaction where sell_date = '%s'"
        return self.engine_simul.execute(query % (0)).fetchall()

    # 날짜별 시뮬레이팅 함수
    def simul_by_date(self,date_rows_today,date_rows_yesterday,i):
        # 시뮬레이팅 전 변수 초기화
        self.set_daily_variable()

        # daily_buy_list에 시뮬레이팅 할 날짜에 해당하는 테이블과 전 날 테이블이 존재하는지 확인
        if self.is_date_exist(date_rows_today) and self.is_date_exist(date_rows_yesterday):
            # 당일 매수 할 종목 저장
            self.db_to_realtime_daily_buy_list(date_rows_today, date_rows_yesterday, i)
            # 매수/매도
            self.trading_by_date(date_rows_today, date_rows_yesterday, i)

            if self.is_simul_table_exist(self.db_name, "transaction") and len(self.get_data_from_possessed_item()) != 0:
                # 보유 중인 종목들의 주가를 일별로 업데이트
                self.update_transaction_by_date(date_rows_today,option="ALL")

            # 정산
            self.db_to_account_balance(date_rows_today)

        else:
            print("날짜 테이블이 존재하지 않습니다.")

    # 날짜별 거래 함수
    def trading_by_date(self,date_rows_today,date_rows_yesterday,i):
        self.show_info(date_rows_today)

        # 보유주 정보 업데이트
        if self.is_simul_table_exist(self.db_name, "transaction") and len(self.get_data_from_possessed_item()) != 0:
            self.update_transaction_by_date(date_rows_today,option="OPEN")
            self.update_transaction_etc()

            # 매도
            self.auto_trade_sell_stock(date_rows_today,i)

            # 매수할 잔액이 존재한다면 매수
            if self.check_balance():
                self.auto_trade_buy_stock(str(date_rows_today) + "0900", date_rows_today, date_rows_yesterday)

        # 매도 리스트가 존재하지 않는다면 매수만 진행
        else:
            if self.check_balance():
                self.auto_trade_buy_stock(str(date_rows_today) + "0900", date_rows_today, date_rows_yesterday)

    # daily_buy_list 데이터베이스에서 가장 최근의 날짜 테이블을 가져오는 함수
    def get_recent_daily_buy_list_date(self):
        query="select TABLE_NAME from information_schema.tables " \
              "where table_schema = 'daily_buy_list' and TABLE_NAME like '%s' order by table_name desc limit 1"
        row = self.engine_daily_buy_list.execute(query % ("20%%")).fetchall()

        if len(row) == 0:
            return False
        return row[0][0]

    # 최근 daily_buy_list의 날짜 테이블에서 code에 해당하는 데이터만 가져오는 함수
    def get_daily_buy_list_by_code(self,code,date):
        query = f"select * from `{date}` where code = '{code}' group by code"

        daily_buy_list = self.engine_daily_buy_list.execute(query).fetchall()

        df_daily_buy_list = DataFrame(daily_buy_list,
                                      columns=['index', 'index2', 'date', 'check_item',
                                               'code', 'code_name', 'd1_diff', 'd1_diff_rate',
                                               'close', 'open','high', 'low', 'volume',
                                               'clo5', 'clo10', 'clo20', 'clo60', 'clo120',
                                               "clo5_diff_rate", "clo10_diff_rate", "clo20_diff_rate",
                                               "clo60_diff_rate", "clo120_diff_rate",
                                               'yes_clo5', 'yes_clo10', 'yes_clo20', 'yes_clo60','yes_clo120',
                                               'vol5', 'vol10', 'vol20', 'vol60', 'vol120'])
        return df_daily_buy_list