workspace.ipynb 47.4 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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import FinanceDataReader as fdr\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def basicinform(input):\n",
    "    stocks = pd.read_csv('stockcodename.csv',index_col=0)\n",
    "    symbol = ''\n",
    "    for i in enumerate(stocks.Name) :\n",
    "        if i[1] == input:\n",
    "            symbol = (stocks.iloc[i[0]].Symbol)\n",
    "            break\n",
    "    df = fdr.DataReader(symbol)\n",
    "    ror_df = df.Close.pct_change()\n",
    "    volume = df.Volume.iloc[-1]\n",
    "    price = df.Close.iloc[-1]\n",
    "    ror = ror_df[-1]\n",
    "    #print(\"현재가: \", price)\n",
    "    #print(\"거래량: \", volume)\n",
    "    #print(\"전일 대비 수익률:\", ror)\n",
    "    #display(df)\n",
    "    value = {\"현재가\": price ,\n",
    "              \"거래랑\": volume ,\n",
    "              \"전일 대비 수익률:\" : ror\n",
    "            }\n",
    "    return value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'현재가': 82800, '거래랑': 29341312, '전일 대비 수익률:': 0.024752475247524774}\n"
     ]
    }
   ],
   "source": [
    "print(basicinform('삼성전자'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "stocks = fdr.StockListing('KOSPI') # 코스피\n",
    "stocks.to_csv(\"stockcodename.csv\",mode='w', encoding='utf-8-sig')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import FinanceDataReader as fdr\n",
    "from scipy.optimize import minimize\n",
    "import json\n",
    "from datetime import date\n",
    "import math\n",
    "import itertools as it\n",
    "import operator\n",
    "from datetime import datetime\n",
    "from scipy import stats\n",
    "from scipy.stats import norm\n",
    "from dateutil import rrule\n",
    "from calendar import monthrange\n",
    "from dateutil.relativedelta import relativedelta\n",
    "from ast import literal_eval\n",
    "\n",
    "#소숫점 표현\n",
    "pd.options.display.float_format = '{:.3f}'.format\n",
    "np.set_printoptions(precision=3, suppress=True)\n",
    "\n",
    "class c_Models:\n",
    "    #Input 값으로, 자산 list, 사용자 포트폴리오 비중, 시작일, 마지막일\n",
    "    def __init__(self, assets, assets_w, start, end):\n",
    "        self.result = None\n",
    "        self.graph = None\n",
    "    \n",
    "        stocks = pd.read_csv('stockcodename.csv', index_col=0)\n",
    "        symbol = ''\n",
    "        self.asset_name = assets[:]\n",
    "        for k in range(len(assets)):\n",
    "            for i in enumerate(stocks.Name):\n",
    "                if i[1] == assets[k]:\n",
    "                    assets[k] = (stocks.iloc[i[0]].Symbol)\n",
    "                    break\n",
    "\n",
    "        data = pd.DataFrame()\n",
    "        # 전체 자산 data들을 가지고 온 후, 정리함\n",
    "        \n",
    "        for asset in assets: #total_list:\n",
    "            tmp = fdr.DataReader(asset,start,end).Close\n",
    "            if len(data) == 0 :\n",
    "                data = tmp\n",
    "            else:\n",
    "                data = pd.concat([data,tmp], axis=1)\n",
    "   \n",
    "        data.columns = self.asset_name\n",
    "   \n",
    "        if data.isnull().values.any() == True: #불러온 data에 오류가 있다면\n",
    "            return \"No Data\",''\n",
    "\n",
    "        else:\n",
    "            data = data.resample('M').mean() #일별 데이터를 월별 데이터로 만들어줌\n",
    "            data = data.pct_change() #월별 주가 데이터를 이용해 수익률 데이터로 변환\n",
    "            data.dropna(inplace=True) #결측치 제외(첫 row)\n",
    "\n",
    "            self.data = data\n",
    "            self.assets_w = assets_w\n",
    "            self.mu = data.mean() * 12\n",
    "            self.cov = data.cov() * 12\n",
    "\n",
    "    #GMV 최적화 : 제약 조건은 비중합=1, 공매도 불가능\n",
    "    def gmv_opt(self):\n",
    "        n_assets = len(self.data.columns)\n",
    "        w0 = np.ones(n_assets) / n_assets\n",
    "        fun = lambda w: np.dot(w.T, np.dot(self.cov, w))\n",
    "        constraints = ({'type':'eq', 'fun':lambda x: np.sum(x)-1})\n",
    "        bd = ((0,1),) * n_assets\n",
    "        #cov = data.cov() * 12\n",
    "        gmv = minimize(fun, w0, method = 'SLSQP', constraints=constraints, bounds=bd)\n",
    "        result = dict(zip(self.asset_name, np.round(gmv.x,3)))\n",
    "        return result\n",
    "    \n",
    "    #Max Sharp ratio : risk free rate은 0.8%로 지정했고, \n",
    "    def ms_opt(self):\n",
    "        n_assets = len(self.data.columns)\n",
    "        w0 = np.ones(n_assets) / n_assets\n",
    "        fun = lambda w: -(np.dot(w.T, self.mu) - 0.008) / np.sqrt(np.dot(w.T, np.dot(self.cov, w)))\n",
    "        bd = ((0,1),) * n_assets     \n",
    "        constraints = ({'type': 'eq', 'fun': lambda x:  np.sum(x) - 1})\n",
    "        maxsharp = minimize(fun, w0, method ='SLSQP', constraints=constraints, bounds=bd)\n",
    "        result = dict(zip(self.asset_name, np.round(maxsharp.x,3)))\n",
    "        return result\n",
    "    \n",
    "    def rp_opt(self):\n",
    "        def RC(cov, w):\n",
    "            pfo_std = np.sqrt(np.dot(w.T, np.dot(self.cov, w)))\n",
    "            mrc = 1/pfo_std * (np.dot(self.cov, w))\n",
    "            rc = mrc * w\n",
    "            rc = rc / rc.sum()\n",
    "            return rc\n",
    "        \n",
    "        \n",
    "        def RP_objective(x):\n",
    "            pfo_std = np.sqrt(np.dot(x.T, np.dot(self.cov, x)))\n",
    "            mrc = 1/pfo_std * (np.dot(self.cov, x))\n",
    "            rc = mrc * x\n",
    "            rc = rc / rc.sum()\n",
    "\n",
    "            a = np.reshape(rc, (len(rc),1))\n",
    "            differs = a - a.T\n",
    "            objective = np.sum(np.square(differs))\n",
    "\n",
    "            return objective    \n",
    "        \n",
    "        n_assets = len(self.data.columns)\n",
    "        w0 = np.ones(n_assets) / n_assets\n",
    "        constraints = [{'type':'eq', 'fun': lambda x: np.sum(x) -1}]\n",
    "        bd = ((0,1),) * n_assets\n",
    "\n",
    "        rp = minimize(RP_objective, w0,  constraints=constraints, bounds = bd, method='SLSQP')\n",
    "        result = dict(zip(self.asset_name, np.round(rp.x,3)))\n",
    "        return result     #, RC(self.cov, rp.x)\n",
    "\n",
    "    def plotting(self):\n",
    "        wt_gmv = np.asarray(list(self.gmv_opt().values()))\n",
    "        wt_ms = np.asarray(list(self.ms_opt().values()))\n",
    "        wt_rp = np.asarray(list(self.rp_opt().values()))\n",
    "        \n",
    "        ret_gmv = np.dot(wt_gmv, self.mu)\n",
    "        ret_ms = np.dot(wt_ms, self.mu)\n",
    "        ret_rp = np.dot(wt_rp, self.mu)\n",
    "        vol_gmv = np.sqrt(np.dot(wt_gmv.T, np.dot(self.cov, wt_gmv)))\n",
    "        vol_ms = np.sqrt(np.dot(wt_ms.T, np.dot(self.cov, wt_ms)))\n",
    "        vol_rp = np.sqrt(np.dot(wt_rp.T, np.dot(self.cov, wt_rp)))\n",
    "        \n",
    "        wt_gmv = wt_gmv.tolist()\n",
    "        wt_ms = wt_ms.tolist()\n",
    "        wt_rp = wt_rp.tolist()\n",
    "        \n",
    "        user_ret = np.dot(self.assets_w, self.mu)\n",
    "        user_risk = np.sqrt(np.dot(self.assets_w, np.dot(self.cov, self.assets_w)))\n",
    "\n",
    "        weights = {'gmv': wt_gmv, \"ms\" : wt_ms, \"rp\": wt_rp}\n",
    "        \n",
    "        #rec_rs = recommended_asset()\n",
    "\n",
    "        trets = np.linspace(ret_gmv, max(self.mu), 30) # 30개 짜르기 \n",
    "        tvols = []\n",
    "        \n",
    "        efpoints = dict()\n",
    "        for i, tret in enumerate(trets): #이 개별 return마다 최소 risk 찾기\n",
    "            n_assets = len(self.data.columns)\n",
    "            w0 = np.ones(n_assets) / n_assets\n",
    "            fun = lambda w: np.dot(w.T ,np.dot(self.cov, w))\n",
    "            constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1},\n",
    "                           {'type': 'ineq', 'fun': lambda x: np.dot(x, self.mu) - tret}]\n",
    "                           #{'type': 'ineq', 'fun': lambda x: x}]\n",
    "            bd = ((0,1),) * n_assets\n",
    "\n",
    "            minvol = minimize(fun, w0, method='SLSQP',bounds = bd, constraints=constraints)\n",
    "            tvols.append(np.sqrt(np.dot(minvol.x, np.dot(self.cov, minvol.x))))\n",
    "            \n",
    "            pnumber = '{}point'.format(i+1)\n",
    "            efpoints[pnumber] = minvol.x.tolist()\n",
    "        \n",
    "        if self.data.shape[0] <= 1:\n",
    "            error = '기간에러'\n",
    "            return error,1,1\n",
    "        else:\n",
    "            ret_vol = {\"GMV\": [vol_gmv, ret_gmv],\"MaxSharp\": [vol_ms, ret_ms],\"RiskParity\": [vol_rp, ret_rp], \"Trets\" : trets.tolist(), \"Tvols\": tvols, \"User\" : [user_risk,user_ret]} #, \"Recommended\" : rec_rs}        \n",
    "            return ret_vol, json.dumps(efpoints), json.dumps(weights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class back_test:\n",
    "    # 단순 일별수익률의 평균을 *365하여 연간수익률을 산출\n",
    "    def __init__(self):\n",
    "        self.test = 0\n",
    "        \n",
    "    def Arithmetic_Mean_Annual(self,ret):\n",
    "        month_return =  np.mean(ret)\n",
    "        return (month_return*252)\n",
    "\n",
    "    # 기간중 투자했을때 하락할 수 있는 비율\n",
    "    def dd(self,ret):\n",
    "        cum_ret = (1 + ret).cumprod()\n",
    "        max_drawdown = 0\n",
    "        max_ret = 1\n",
    "        dd_list = []\n",
    "        c = 0\n",
    "        for ix_ret in cum_ret.values:\n",
    "            if max_ret < ix_ret:\n",
    "                max_ret = ix_ret\n",
    "            dd_list.append((ix_ret - max_ret) / max_ret) \n",
    "            c= c+1\n",
    "        return dd_list\n",
    "    \n",
    "    # 기간중 투자했을때 최고로 많이 하락할 수 있는 비율\n",
    "    def mdd(self,ret):\n",
    "        \n",
    "        cum_ret = (1 + ret).cumprod()\n",
    "        max_drawdown = 0\n",
    "        max_ret = 1\n",
    "        for ix_ret in cum_ret.values:\n",
    "            if max_drawdown > (ix_ret - max_ret) / max_ret:\n",
    "                max_drawdown = (ix_ret - max_ret) / max_ret\n",
    "            if max_ret < ix_ret:\n",
    "                max_ret = ix_ret\n",
    "\n",
    "        return abs(max_drawdown)\n",
    "\n",
    "    # 포트폴리오 수익률에서 무위험 수익률을 제한 후 이를 포트폴리오의 표준편차로 나눠 산출한 값, 즉 위험대비 얼마나 수익이 좋은지의 척도\n",
    "    def sharpe_ratio(self,ret, rf=0.008, num_of_date=252):\n",
    "        \n",
    "        return ((np.mean(ret - (rf / num_of_date))) / (np.std(ret))) * np.sqrt(num_of_date)\n",
    "    \n",
    "    # 설정한 confidence level에 따른(95%) 확률로 발생할 수 있는 손실액의 최대 액수\n",
    "    def value_at_risk(self,ret, para_or_hist=\"para\", confidence_level=0.95):\n",
    "        \n",
    "        vol = np.std(ret)\n",
    "        if para_or_hist == \"para\":\n",
    "            VaR = np.mean(ret) - vol * norm.ppf(confidence_level)\n",
    "        else:\n",
    "            print('error')\n",
    "\n",
    "        return VaR\n",
    "    \n",
    "    # 전체 투자기간에서 상승한 ( ret > 0 ) 기간의 비율\n",
    "    def winning_rate(self,ret):\n",
    "        var_winning_rate = np.sum(ret > 0) / len(ret)\n",
    "        return var_winning_rate    \n",
    "    \n",
    "    # 상승한날의 평균상승값을 하락한날의 평균하락값으로 나눈 비율\n",
    "    def profit_loss_ratio(self,ret):\n",
    "\n",
    "        if np.sum(ret > 0) == 0:\n",
    "            var_profit_loss_ratio = 0\n",
    "        elif np.sum(ret < 0) == 0:\n",
    "            var_profit_loss_ratio = np.inf\n",
    "        else:\n",
    "            win_mean = np.mean(ret[ret > 0])\n",
    "            loss_mean = np.mean(ret[ret < 0])\n",
    "            var_profit_loss_ratio = win_mean / loss_mean\n",
    "        return abs(var_profit_loss_ratio)\n",
    "\n",
    "    # 데이터 취합하는 코드 \n",
    "    #임시로 5가지 데이터 예시를 활용해 코드작성\n",
    "    # 선택한 종목의 이름과 비중, 투자기간을 input 값으로 받음       \n",
    "    \n",
    "    def backtest_data(self, assets,weight,start_data_1, end_data_1,start_amount,rebalancing_month, interval, opt_option):\n",
    "        # input으로 받는 assetnames 입력\n",
    "        a = assets\n",
    "        stock_num = len(a)\n",
    "        # input으로 받는 assetweights 입력\n",
    "        rebal_month = int(rebalancing_month)\n",
    "        # input으로 받는 rebalancing_month를 입력\n",
    "        # 나타내는 데이터 간격을 표시\n",
    "\n",
    "        # weight 간격  \n",
    "        b = list(map(float, weight))\n",
    "        \n",
    "\n",
    "        # input으로 받는 from_period와 to_period 입력\n",
    "        stock_return = pd.date_range(start=start_data_1, end=end_data_1)\n",
    "        stock_return = pd.DataFrame(stock_return)\n",
    "        stock_return.columns = ['Date']\n",
    "\n",
    "        stocks = pd.read_csv('stockcodename.csv', index_col=0)\n",
    "        symbol = ''\n",
    "        asset_name = assets[:]\n",
    "        for k in range(len(assets)):\n",
    "            for i in enumerate(stocks.Name):\n",
    "                if i[1] == assets[k]:\n",
    "                    assets[k] = (stocks.iloc[i[0]].Symbol)\n",
    "                    break\n",
    "        \n",
    "        # input으로 받는 from_period와 to_period 입력\n",
    "        stock_return = pd.date_range(start=start_data_1, end=end_data_1)\n",
    "        stock_return = pd.DataFrame(stock_return)\n",
    "        stock_return.columns = ['Date']\n",
    "        \n",
    "\n",
    "        for asset in assets: #total_list:\n",
    "            tmp = fdr.DataReader(asset,start_data_1,end_data_1)\n",
    "            tmp.insert(1,\"Date\",tmp.index.copy(),True)\n",
    "            tmp = tmp[['Date','Change']]\n",
    "            tmp.columns = ['Date',asset]\n",
    "            tmp = tmp.reset_index(drop=True)\n",
    "            stock_return = pd.merge(stock_return,tmp,how='inner', on='Date')\n",
    "\n",
    "        stock_return = stock_return.dropna(axis=0)\n",
    "\n",
    "        #print(stock_return)\n",
    "        if opt_option == 'basic' :\n",
    "\n",
    "            # 투자비중으로 이루어진 dataframe 만들기\n",
    "\n",
    "            start_datetime = stock_return.iloc[0,0]\n",
    "            end_datetime = stock_return.iloc[-1,0]\n",
    "            diff_months_list = list(rrule.rrule(rrule.MONTHLY, dtstart=start_datetime, until=end_datetime))\n",
    "            month_gap = len(diff_months_list)\n",
    "            rebal_roof = month_gap//rebal_month\n",
    "            rebal_weight = pd.DataFrame()\n",
    "\n",
    "            for i in range(rebal_roof+1):\n",
    "                # 데이터로부터 리밸런싱기간만큼 가져오기\n",
    "                filtered_df =stock_return.loc[stock_return[\"Date\"].between(start_datetime, \n",
    "                                                                         start_datetime + relativedelta(months=rebal_month)+relativedelta(days = -1))]\n",
    "                # 리밸런싱 기간의 누적수익률 산출\n",
    "                for j in range(stock_num):\n",
    "                    filtered_df.iloc[:,j+1] = (1 + filtered_df.iloc[:,j+1]).cumprod()\n",
    "                # 해당 누적수익률에 initial 투자비중을 곱해준다 \n",
    "                for j in range(stock_num):\n",
    "                    filtered_df.iloc[:,j+1] = filtered_df.iloc[:,j+1]*float(b[j])\n",
    "                # 이후 각각의 종목의 비중을 계산해서 산출한다\n",
    "                filtered_df['total_value'] = filtered_df.sum(axis=1)\n",
    "                for j in range(stock_num):\n",
    "                    filtered_df.iloc[:,j+1] = filtered_df.iloc[:,j+1]/filtered_df['total_value']\n",
    "\n",
    "                rebal_weight = pd.concat([rebal_weight,filtered_df])\n",
    "                start_datetime = start_datetime + relativedelta(months=rebal_month)\n",
    "\n",
    "                #final_day = monthrange(start_datetime.year, start_datetime.month)\n",
    "\n",
    "            stock_weight = rebal_weight.iloc[:,:-1]\n",
    "            #print(stock_weight)\n",
    "            '''\n",
    "            stock_weight = stock_return.Date\n",
    "            stock_weight = pd.DataFrame(stock_weight)\n",
    "            c = 0\n",
    "            for stockweight in b:\n",
    "                stock_weight[a[c]] = float(stockweight)\n",
    "                c = c + 1\n",
    "            #print(stock_weight)\n",
    "            '''\n",
    "        else :\n",
    "            # 포트폴리오 최적화 코드를 통한 리벨런싱 이중 리스트 weight 산출\n",
    "            # 1. 입력 받은 start ~ end 날짜를 리밸런싱 기간으로 쪼개기   \n",
    "            opt_start_datetime = stock_return.iloc[0,0]\n",
    "            opt_end_datetime = stock_return.iloc[-1,0]\n",
    "            opt_diff_months_list = list(rrule.rrule(rrule.MONTHLY, dtstart=opt_start_datetime, until=opt_end_datetime))\n",
    "            opt_month_gap = len(opt_diff_months_list)\n",
    "            opt_rebal_roof = opt_month_gap//rebal_month\n",
    "            opt_rebal_weight = pd.DataFrame()\n",
    "            #opt_array = [[0]*stock_num]*(opt_rebal_roof+1)\n",
    "\n",
    "            for i in range(opt_rebal_roof+1):\n",
    "                opt_df = stock_return.loc[stock_return[\"Date\"].between(opt_start_datetime,opt_start_datetime + relativedelta(months=rebal_month)+relativedelta(days = -1))]\n",
    "                # 최적화 코드에서 기간마다의 가중치를 가져온다\n",
    "                c_m = c_Models(a,b,opt_df.iat[0,0]- relativedelta(months=3),opt_df.iat[-1,0])\n",
    "                ret_vol, efpoints, weights = c_m.plotting()\n",
    "                weights = literal_eval(weights)\n",
    "                weights = weights.get(opt_option)\n",
    "                ##print(weights)\n",
    "                # 리밸런싱 기간의 누적수익률 산출\n",
    "                for j in range(stock_num):\n",
    "                    opt_df.iloc[:,j+1] = (1 + opt_df.iloc[:,j+1]).cumprod()\n",
    "                # 해당 누적수익률에 initial 투자비중을 곱해준다 \n",
    "                for j in range(stock_num):\n",
    "                    opt_df.iloc[:,j+1] = opt_df.iloc[:,j+1]*float(weights[j])\n",
    "                # 이후 각각의 종목의 비중을 계산해서 산출한다\n",
    "                opt_df['total_value'] = opt_df.sum(axis=1)\n",
    "                for j in range(stock_num):\n",
    "                    opt_df.iloc[:,j+1] = opt_df.iloc[:,j+1]/opt_df['total_value']\n",
    "\n",
    "                # 이후 각각의 종목의 비중을 계산해서 산출한다\n",
    "                #print(opt_df)\n",
    "                opt_rebal_weight = pd.concat([opt_rebal_weight,opt_df])\n",
    "                opt_start_datetime = opt_start_datetime + relativedelta(months=rebal_month)\n",
    "                #리밸런싱으로 start 기간이 고객이 원하는 end 기간보다 커지게 되면 종료 \n",
    "                if opt_start_datetime > stock_return.iloc[-1,0]:    # i가 100일 때\n",
    "                    break    \n",
    "            stock_weight = opt_rebal_weight.iloc[:,:-1]\n",
    "            ##print(stock_weight)\n",
    "        # 수익률 데이터와 투자비중을 곱한 하나의 데이터 생성 \n",
    "        pfo_return = stock_weight.Date\n",
    "        pfo_return = pd.DataFrame(pfo_return)\n",
    "        # weight 와 return의 날짜 맞춰주기 \n",
    "        #pfo_return = pfo_return[0:len(stock_weight)]\n",
    "        pfo_return = pd.merge(pfo_return, stock_return, left_on='Date', right_on='Date', how='left')\n",
    "        pfo_return['mean_return'] = 0\n",
    "        ##print(pfo_return)\n",
    "        for i in range(0,len(pfo_return)):\n",
    "            return_result = list(pfo_return.iloc[i,1:1+stock_num])\n",
    "            return_weight = list(stock_weight.iloc[i,1:1+stock_num])\n",
    "            pfo_return.iloc[i,1+stock_num]  = np.dot(return_result,return_weight)\n",
    "            #rint(pfo_return)\n",
    "        pfo_return['acc_return'] = [x+1 for x in pfo_return['mean_return']]\n",
    "        pfo_return['acc_return'] = list(it.accumulate(pfo_return['acc_return'], operator.mul))\n",
    "        pfo_return['acc_return'] = [x-1 for x in pfo_return['acc_return']]\n",
    "        pfo_return['final_balance'] = float(start_amount) + float(start_amount)*pfo_return['acc_return']\n",
    "        pfo_return['Drawdown_list'] = back_test.dd(input,pfo_return['mean_return'])\n",
    "        pfo_return = pfo_return.set_index('Date') \n",
    "        #print(pfo_return)\n",
    "        \n",
    "        \n",
    "        ### 벤치마크 데이터 로드 및 전처리\n",
    "        \n",
    "        tiker_list = ['KS11','US500'] \n",
    "        bench_list = [fdr.DataReader(ticker, start_data_1,  end_data_1)['Change'] for ticker in tiker_list]\n",
    "        bench = pd.concat(bench_list, axis=1)\n",
    "        bench.columns = ['KOSPI', 'S&P500']\n",
    "        bench['KOSPI'] = bench['KOSPI'].fillna(0)\n",
    "        bench['S&P500'] = bench['S&P500'].fillna(0)\n",
    "        #bench = bench.dropna()\n",
    "        \n",
    "        # 벤치마크 누적수익률, DD 값 \n",
    "        \n",
    "        bench['KOSPI_acc'] = [x+1 for x in bench['KOSPI']]\n",
    "        bench['KOSPI_acc'] = list(it.accumulate(bench['KOSPI_acc'], operator.mul))\n",
    "        bench['KOSPI_acc'] = [x-1 for x in bench['KOSPI_acc']]\n",
    "        bench['KOSPI_balance'] = float(start_amount) + float(start_amount)*bench['KOSPI_acc']\n",
    "        bench['KOSPI_Drawdown'] = back_test.dd(input,bench['KOSPI'])\n",
    "        bench['S&P500_acc'] = [x+1 for x in bench['S&P500']]\n",
    "        bench['S&P500_acc'] = list(it.accumulate(bench['S&P500_acc'], operator.mul))\n",
    "        bench['S&P500_acc'] = [x-1 for x in bench['S&P500_acc']]\n",
    "        bench['S&P500_balance'] = float(start_amount) + float(start_amount)*bench['S&P500_acc']\n",
    "        bench['S&P500_Drawdown'] = back_test.dd(input,bench['S&P500'])\n",
    "        \n",
    "        if interval == 'monthly' or interval == 'weekly' :\n",
    "            if interval == 'monthly' :\n",
    "                inter = 'M'\n",
    "            if interval == 'weekly' :\n",
    "                inter = 'W'\n",
    "            pfo_return_interval = pfo_return.resample(inter).last()\n",
    "            pfo_return_first = pd.DataFrame(pfo_return.iloc[0]).transpose()\n",
    "            pfo_return_interval = pd.concat([pfo_return_first, pfo_return_interval])\n",
    "            pfo_return_interval['mean_return'] = pfo_return_interval['final_balance'].pct_change()\n",
    "            pfo_return_interval = pfo_return_interval.dropna()\n",
    "            \n",
    "            # 월별 간격으로 만들어주기, 여기서는 return과 value만 monthly로 산출함 나머지값은 daily\n",
    "            bench_interval = bench.resample(inter).last()\n",
    "            #bench_ex['KOSPI'] = bench_ex['final_balance'].pct_change()\n",
    "            bench_first = pd.DataFrame(bench.iloc[0]).transpose()\n",
    "            bench_interval = pd.concat([bench_first, bench_interval])\n",
    "            bench_interval['KOSPI'] = bench_interval['KOSPI_balance'].pct_change()\n",
    "            bench_interval['S&P500'] = bench_interval['S&P500_balance'].pct_change()\n",
    "            bench_interval = bench_interval.dropna()\n",
    "            \n",
    "            # 날짜타입 열로 만들기 및 str 타입으로 전처리 \n",
    "            pfo_return = pfo_return.rename_axis('Date').reset_index()\n",
    "            pfo_return['Date'] =  pd.to_datetime(pfo_return['Date'], format='%d/%m/%Y').dt.date\n",
    "            pfo_return['Date'] = list(map(str, pfo_return['Date']))\n",
    "            \n",
    "            pfo_return_interval = pfo_return_interval.rename_axis('Date').reset_index()\n",
    "            pfo_return_interval['Date'] =  pd.to_datetime(pfo_return_interval['Date'], format='%d/%m/%Y').dt.date\n",
    "            pfo_return_interval['Date'] = list(map(str, pfo_return_interval['Date']))\n",
    "            \n",
    "            bench = bench.rename_axis('Date').reset_index()\n",
    "            bench['Date'] =  pd.to_datetime(bench['Date'], format='%d/%m/%Y').dt.date\n",
    "            bench['Date'] = list(map(str, bench['Date']))        \n",
    "           \n",
    "            bench_interval = bench_interval.rename_axis('Date').reset_index()\n",
    "            bench_interval['Date'] =  pd.to_datetime(bench_interval['Date'], format='%d/%m/%Y').dt.date\n",
    "            bench_interval['Date'] = list(map(str, bench_interval['Date']))       \n",
    "            \n",
    "            backtest_return = {\n",
    "                 'pfo_return': [\n",
    "                         {\n",
    "                         'Date': list(pfo_return_interval['Date']),\n",
    "                         'mean_return': list(pfo_return_interval['mean_return']),                 \n",
    "                         'acc_return ratio': list(pfo_return_interval['acc_return']),\n",
    "                         'final_balance': list(pfo_return_interval['final_balance']),\n",
    "                         'Drawdown_list' : list(pfo_return_interval['Drawdown_list'])\n",
    "                          }\n",
    "                 ],         \n",
    "                 'bench': [\n",
    "                         {\n",
    "                         'Date': list(bench_interval['Date']),\n",
    "                         'KOSPI_return': list(bench_interval['KOSPI']),              \n",
    "                         'S&P500_return': list(bench_interval['S&P500']),\n",
    "                         'KOSPI_acc_return': list(bench_interval['KOSPI_acc']),\n",
    "                         'KOSPI_balance' : list(bench_interval['KOSPI_balance']),                 \n",
    "                         'KOSPI_Drawdown': list(bench_interval['KOSPI_Drawdown']),\n",
    "                         'S&P500_acc_return': list(bench_interval['S&P500_acc']),\n",
    "                         'S&P500_balance' : list(bench_interval['S&P500_balance']),                 \n",
    "                         'S&P500_Drawdown': list(bench_interval['S&P500_Drawdown'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,pfo_return['mean_return']),\n",
    "                         'Std': pfo_return['mean_return'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,pfo_return['mean_return']),\n",
    "                         'VaR': back_test.value_at_risk(input,pfo_return['mean_return']),\n",
    "                         'MDD': back_test.mdd(input,pfo_return['mean_return']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,pfo_return['mean_return']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,pfo_return['mean_return'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'KOSPI_indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,bench['KOSPI']),\n",
    "                         'Std': bench['KOSPI'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,bench['KOSPI']),\n",
    "                         'VaR': back_test.value_at_risk(input,bench['KOSPI']),\n",
    "                         'MDD': back_test.mdd(input,bench['KOSPI']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,bench['KOSPI']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,bench['KOSPI'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'S&P500_indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,bench['S&P500']),\n",
    "                         'Std': bench['S&P500'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,bench['S&P500']),\n",
    "                        'VaR': back_test.value_at_risk(input,bench['S&P500']),\n",
    "                         'MDD': back_test.mdd(input,bench['S&P500']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,bench['S&P500']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,bench['S&P500'])\n",
    "                          }\n",
    "                 ]\n",
    "             } \n",
    "            \n",
    "        else :\n",
    "            # 날짜타입 열로 만들기 및 str 타입으로 전처리 \n",
    "            pfo_return = pfo_return.rename_axis('Date').reset_index()\n",
    "            pfo_return['Date'] =  pd.to_datetime(pfo_return['Date'], format='%d/%m/%Y').dt.date\n",
    "            pfo_return['Date'] = list(map(str, pfo_return['Date']))\n",
    "            \n",
    "            bench = bench.rename_axis('Date').reset_index()\n",
    "            bench['Date'] =  pd.to_datetime(bench['Date'], format='%d/%m/%Y').dt.date\n",
    "            bench['Date'] = list(map(str, bench['Date']))\n",
    "            backtest_return = {\n",
    "                 'pfo_return': [\n",
    "                         {\n",
    "                         'Date': list(pfo_return['Date']),\n",
    "                         'mean_return': list(pfo_return['mean_return']),                 \n",
    "                         'acc_return ratio': list(pfo_return['acc_return']),\n",
    "                         'final_balance': list(pfo_return['final_balance']),\n",
    "                         'Drawdown_list' : list(pfo_return['Drawdown_list'])\n",
    "                          }\n",
    "                 ],         \n",
    "                 'bench': [\n",
    "                         {\n",
    "                         'Date': list(bench['Date']),\n",
    "                         'KOSPI_return': list(bench['KOSPI']),              \n",
    "                         'S&P500_return': list(bench['S&P500']),\n",
    "                         'KOSPI_acc_return': list(bench['KOSPI_acc']),\n",
    "                         'KOSPI_balance' : list(bench['KOSPI_balance']),                 \n",
    "                         'KOSPI_Drawdown': list(bench['KOSPI_Drawdown']),\n",
    "                         'S&P500_acc_return': list(bench['S&P500_acc']),\n",
    "                         'S&P500_balance' : list(bench['S&P500_balance']),                 \n",
    "                         'S&P500_Drawdown': list(bench['S&P500_Drawdown'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,pfo_return['mean_return']),\n",
    "                         'Std': pfo_return['mean_return'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,pfo_return['mean_return']),\n",
    "                         'VaR': back_test.value_at_risk(input,pfo_return['mean_return']),\n",
    "                         'MDD': back_test.mdd(input,pfo_return['mean_return']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,pfo_return['mean_return']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,pfo_return['mean_return'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'KOSPI_indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,bench['KOSPI']),\n",
    "                         'Std': bench['KOSPI'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,bench['KOSPI']),\n",
    "                         'VaR': back_test.value_at_risk(input,bench['KOSPI']),\n",
    "                         'MDD': back_test.mdd(input,bench['KOSPI']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,bench['KOSPI']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,bench['KOSPI'])\n",
    "                          }\n",
    "                 ],    \n",
    "                 'S&P500_indicator': [\n",
    "                         {\n",
    "                         'Mean': back_test.Arithmetic_Mean_Annual(input,bench['S&P500']),\n",
    "                         'Std': bench['S&P500'].std() * np.sqrt(365),                 \n",
    "                         'Sharpe ratio': back_test.sharpe_ratio(input,bench['S&P500']),\n",
    "                        'VaR': back_test.value_at_risk(input,bench['S&P500']),\n",
    "                         'MDD': back_test.mdd(input,bench['S&P500']),\n",
    "                         'Winning ratio': back_test.winning_rate(input,bench['S&P500']),\n",
    "                         'Gain/Loss Ratio': back_test.profit_loss_ratio(input,bench['S&P500'])\n",
    "                          }\n",
    "                 ]\n",
    "             }  \n",
    "\n",
    "        \n",
    "\n",
    "        return backtest_return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'GMV': [0.1858389981988727, 0.21203948231342723],\n",
       "  'MaxSharp': [0.18671958740979067, 0.2139596912413942],\n",
       "  'RiskParity': [0.20795176890404793, 0.21559809699947152],\n",
       "  'Trets': [0.21203948231342723,\n",
       "   0.21294773988703294,\n",
       "   0.21385599746063863,\n",
       "   0.21476425503424434,\n",
       "   0.21567251260785003,\n",
       "   0.21658077018145575,\n",
       "   0.21748902775506146,\n",
       "   0.21839728532866715,\n",
       "   0.21930554290227286,\n",
       "   0.22021380047587857,\n",
       "   0.22112205804948426,\n",
       "   0.22203031562308997,\n",
       "   0.22293857319669566,\n",
       "   0.22384683077030137,\n",
       "   0.2247550883439071,\n",
       "   0.22566334591751278,\n",
       "   0.2265716034911185,\n",
       "   0.2274798610647242,\n",
       "   0.2283881186383299,\n",
       "   0.2292963762119356,\n",
       "   0.2302046337855413,\n",
       "   0.231112891359147,\n",
       "   0.23202114893275272,\n",
       "   0.2329294065063584,\n",
       "   0.23383766407996412,\n",
       "   0.23474592165356983,\n",
       "   0.23565417922717552,\n",
       "   0.23656243680078123,\n",
       "   0.23747069437438692,\n",
       "   0.23837895194799263],\n",
       "  'Tvols': [0.1858389981987725,\n",
       "   0.18603980681220794,\n",
       "   0.1866279462874506,\n",
       "   0.18759977333781017,\n",
       "   0.1889493691852574,\n",
       "   0.19066871063768298,\n",
       "   0.19274790351948154,\n",
       "   0.1951754484924986,\n",
       "   0.19793852894483158,\n",
       "   0.2010233088543836,\n",
       "   0.20441522611870286,\n",
       "   0.2080992618687252,\n",
       "   0.21206019173944504,\n",
       "   0.2162828032765981,\n",
       "   0.2207520817102024,\n",
       "   0.22545335668848557,\n",
       "   0.230372426146853,\n",
       "   0.2354956425317311,\n",
       "   0.24080997621842265,\n",
       "   0.24630305688942764,\n",
       "   0.25196319408160095,\n",
       "   0.25777938370335385,\n",
       "   0.2637413018896242,\n",
       "   0.2698392894833826,\n",
       "   0.2760643295664975,\n",
       "   0.2824080201417004,\n",
       "   0.288862545420281,\n",
       "   0.29542064013059877,\n",
       "   0.3020755588277587,\n",
       "   0.3088210356801474],\n",
       "  'User': [0.25113519989524385, 0.2169925302290805]},\n",
       " '{\"1point\": [0.7270000003851871, 0.0, 0.272999999614813], \"2point\": [0.701931034333944, 0.0, 0.29806896566605606], \"3point\": [0.6768620689166184, 0.0, 0.32313793108338174], \"4point\": [0.6517931118624203, 0.0, 0.3482068881375798], \"5point\": [0.6267241338618083, 0.0, 0.37327586613819175], \"6point\": [0.6016551680700105, 0.0, 0.3983448319299896], \"7point\": [0.5765862068839319, 1.0625181290357943e-17, 0.42341379311606814], \"8point\": [0.5515172410659429, 3.469446951953614e-17, 0.4484827589340571], \"9point\": [0.5264482750472359, 0.0, 0.47355172495276426], \"10point\": [0.501379313669539, 0.0, 0.49862068633046097], \"11point\": [0.4763103453392776, 2.0816681711721685e-17, 0.5236896546607225], \"12point\": [0.45124137745684034, 0.0, 0.5487586225431597], \"13point\": [0.426172412012964, 0.0, 0.573827587987036], \"14point\": [0.40110344933541525, 6.938893903907228e-18, 0.5988965506645848], \"15point\": [0.376034481762012, 2.0816681711721685e-17, 0.623965518237988], \"16point\": [0.3509655176307255, 0.0, 0.6490344823692745], \"17point\": [0.3258965525334883, 0.0, 0.6741034474665117], \"18point\": [0.300827586518259, 4.163336342344337e-17, 0.699172413481741], \"19point\": [0.2757586213143949, 4.163336342344337e-17, 0.724241378685605], \"20point\": [0.2506896557025046, 2.7755575615628914e-17, 0.7493103442974953], \"21point\": [0.22562069008962146, 3.122502256758253e-17, 0.7743793099103785], \"22point\": [0.2005517244760024, 0.0, 0.7994482755239977], \"23point\": [0.17548275872525812, 1.3877787807814457e-17, 0.8245172412747419], \"24point\": [0.15041379287609932, 0.0, 0.8495862071239008], \"25point\": [0.12534482753941983, 1.6046192152785466e-17, 0.8746551724605802], \"26point\": [0.10027586412659925, 1.1102230246251565e-16, 0.8997241358734006], \"27point\": [0.07520689805671478, 0.0, 0.9247931019432855], \"28point\": [0.050137931954542976, 0.0, 0.9498620680454571], \"29point\": [0.025068965852762182, 0.0, 0.9749310341472383], \"30point\": [0.0, 3.533653586407226e-08, 0.9999999646634645]}',\n",
       " '{\"gmv\": [0.727, 0.0, 0.273], \"ms\": [0.674, 0.0, 0.326], \"rp\": [0.443, 0.238, 0.319]}')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#gmv 포트폴리오 -> 해당 종목을 각각 몇 퍼센트로 투자해야 위험이 제일 적은가\n",
    "c_Models(['삼성전자','LG전자','카카오'],[0.2,0.5,0.3],'2015-01-01','2021-04-01').plotting()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'삼성전자': 0.674, 'LG전자': 0.0, '카카오': 0.326}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#maxsharp ratio -> 위험대비 수익률이 제일 좋은 포트폴리오 비중 , 즉 가성비가 좋다\n",
    "c_Models(['삼성전자','LG전자','카카오'],[0,0,0],'2015-01-01','2021-04-01').ms_opt()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'삼성전자': 0.443, 'LG전자': 0.238, '카카오': 0.319}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#risk parity -> 포트폴리오에 대한 자산 위험 비중을 동일하게 조정, 즉 삼전,lg,카카오의 포트폴리오 위험 기여도를 0.33으로 하게 만드는 비중\n",
    "c_Models(['삼성전자','LG전자','카카오'],[0,0,0],'2015-01-01','2021-04-01').rp_opt()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#def backtest_data(self,assets,weight,start_data_1, end_data_1,start_amount,rebalancing_month, interval, opt_option):\n",
    "back_test().backtest_data(['삼성전자','LG전자'],[0.9,0.1],'2010-01-01', '2021-01-01',10000000,3, 'monthly', 'basic')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Open</th>\n",
       "      <th>High</th>\n",
       "      <th>Low</th>\n",
       "      <th>Close</th>\n",
       "      <th>Volume</th>\n",
       "      <th>Change</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>1997-06-02</td>\n",
       "      <td>1215</td>\n",
       "      <td>1222</td>\n",
       "      <td>1179</td>\n",
       "      <td>1190</td>\n",
       "      <td>74990</td>\n",
       "      <td>nan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1997-06-03</td>\n",
       "      <td>1190</td>\n",
       "      <td>1195</td>\n",
       "      <td>1174</td>\n",
       "      <td>1176</td>\n",
       "      <td>71360</td>\n",
       "      <td>-0.012</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1997-06-04</td>\n",
       "      <td>1161</td>\n",
       "      <td>1197</td>\n",
       "      <td>1161</td>\n",
       "      <td>1197</td>\n",
       "      <td>85220</td>\n",
       "      <td>0.018</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1997-06-05</td>\n",
       "      <td>1193</td>\n",
       "      <td>1206</td>\n",
       "      <td>1181</td>\n",
       "      <td>1188</td>\n",
       "      <td>81890</td>\n",
       "      <td>-0.008</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1997-06-07</td>\n",
       "      <td>1197</td>\n",
       "      <td>1215</td>\n",
       "      <td>1190</td>\n",
       "      <td>1197</td>\n",
       "      <td>32550</td>\n",
       "      <td>0.008</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2021-05-28</td>\n",
       "      <td>79800</td>\n",
       "      <td>80400</td>\n",
       "      <td>79400</td>\n",
       "      <td>80100</td>\n",
       "      <td>12360199</td>\n",
       "      <td>0.006</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2021-05-31</td>\n",
       "      <td>80300</td>\n",
       "      <td>80600</td>\n",
       "      <td>79600</td>\n",
       "      <td>80500</td>\n",
       "      <td>13321324</td>\n",
       "      <td>0.005</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2021-06-01</td>\n",
       "      <td>80500</td>\n",
       "      <td>81300</td>\n",
       "      <td>80100</td>\n",
       "      <td>80600</td>\n",
       "      <td>14058401</td>\n",
       "      <td>0.001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2021-06-02</td>\n",
       "      <td>80400</td>\n",
       "      <td>81400</td>\n",
       "      <td>80300</td>\n",
       "      <td>80800</td>\n",
       "      <td>16414644</td>\n",
       "      <td>0.002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2021-06-03</td>\n",
       "      <td>81300</td>\n",
       "      <td>83000</td>\n",
       "      <td>81100</td>\n",
       "      <td>82800</td>\n",
       "      <td>29341312</td>\n",
       "      <td>0.025</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>6000 rows × 6 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "             Open   High    Low  Close    Volume  Change\n",
       "Date                                                    \n",
       "1997-06-02   1215   1222   1179   1190     74990     nan\n",
       "1997-06-03   1190   1195   1174   1176     71360  -0.012\n",
       "1997-06-04   1161   1197   1161   1197     85220   0.018\n",
       "1997-06-05   1193   1206   1181   1188     81890  -0.008\n",
       "1997-06-07   1197   1215   1190   1197     32550   0.008\n",
       "...           ...    ...    ...    ...       ...     ...\n",
       "2021-05-28  79800  80400  79400  80100  12360199   0.006\n",
       "2021-05-31  80300  80600  79600  80500  13321324   0.005\n",
       "2021-06-01  80500  81300  80100  80600  14058401   0.001\n",
       "2021-06-02  80400  81400  80300  80800  16414644   0.002\n",
       "2021-06-03  81300  83000  81100  82800  29341312   0.025\n",
       "\n",
       "[6000 rows x 6 columns]"
      ]
     },
     "execution_count": 185,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = fdr.DataReader('005930')\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"gmv\": [0.727, 0.0, 0.273], \"ms\": [0.674, 0.0, 0.326], \"rp\": [0.443, 0.238, 0.319]}\n",
      "[0.674, 0.0, 0.326]\n"
     ]
    }
   ],
   "source": [
    "c_m = c_Models(['삼성전자','LG전자','카카오'],[0,0,0],'2015-01-01','2021-04-01')\n",
    "ret_vol, efpoints, weights = c_m.plotting()\n",
    "print(weights)\n",
    "weights = literal_eval(weights)\n",
    "weights = weights.get('ms')\n",
    "print(weights)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}