{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Proxy (To connect OpenAI in China)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import socket\n",
    "import socks\n",
    "socks.set_default_proxy(socks.SOCKS5, \"127.0.0.1\", 7890)\n",
    "socks.set_default_proxy(socks.HTTP, \"127.0.0.1\", 7890)\n",
    "socket.socket = socks.socksocket"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Configs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "env_args = {\n",
    "    \"stock_name\" : \"AAPL\",       \n",
    "    \"start_date\":\"2014-01-01\",\n",
    "    \"end_date\":\"2015-12-30\",\n",
    "    \"init_cash\": 100,\n",
    "    \"init_hold\": 0,\n",
    "    \"trade_volumn\": 100,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai_token.token_ import OPEN_AI_TOKEN      # You may just paste you own openai token\n",
    "agent_args = {\n",
    "    \"model_name\": \"text-davinci-003\", # \"text-curie-001\",\"text-davinci-003\"\n",
    "    \"source\": \"local\",                # \"local\",\"openai\"\n",
    "    \"api_key\": OPEN_AI_TOKEN,         # not necessary when the \"source\" is \"local\"\n",
    "    \"buy_threshold\": 0.3,             # the max positive sentiment is 1, so this should range from 0 to 1 \n",
    "    \"sell_threshold\": -0.3            # the min negative sentiment is -1, so this should range from -1 to 0\n",
    "}"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Env"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gym\n",
    "import json\n",
    "import pandas as pd\n",
    "from easydict import EasyDict as edict\n",
    "from tqdm.notebook import tqdm\n",
    "\n",
    "\n",
    "class Tweets_trading_env(gym.Env):\n",
    "    def __init__(self,args):\n",
    "        args = edict(args)\n",
    "        self.stock_name = args.stock_name\n",
    "        self.start_date = args.start_date\n",
    "        self.end_date = args.end_date\n",
    "        self.init_cash = args.init_cash if \"init_cash\" in args.keys() else 100\n",
    "        self.init_hold = args.init_hold if \"init_hold\" in args.keys() else 0\n",
    "        self.cal_on = args.cal_on if \"cal_on\" in args.keys() else \"Close\"\n",
    "        self.trade_volumn = args.trade_volumn if \"trade_volumn\" in args.keys() else 100\n",
    "        \n",
    "        self.read_file(args.stock_name)\n",
    "\n",
    "    def read_file(self,stock_name):\n",
    "        # sentences\n",
    "        sentence_path = f\"../../stocknet-dataset/tweet/preprocessed/{stock_name}/\"\n",
    "        self.tweets_df = pd.DataFrame()\n",
    "        print(\"missing (empty means not missing):\", end = \" \")\n",
    "        for date in pd.date_range(self.start_date,self.end_date):\n",
    "            date = date.date().strftime(\"%Y-%m-%d\")\n",
    "            file_path = f\"{sentence_path}/{date}\"\n",
    "            try:\n",
    "                with open(file_path, \"r\") as f:\n",
    "                    sentences = f.readlines()\n",
    "                sentences_dict = [json.loads(i) for i in sentences]\n",
    "                sentences = [\" \".join(i[\"text\"]) for i in sentences_dict]\n",
    "                date = [date for i in sentences_dict]\n",
    "                time_ = [pd.to_datetime(i[\"created_at\"]).time() for i in sentences_dict]\n",
    "                user_id_str = [i[\"user_id_str\"] for i in sentences_dict]\n",
    "                temp_df = pd.DataFrame([sentences,date,time_,user_id_str]).T\n",
    "                # print(temp_df)\n",
    "                self.tweets_df = pd.concat([self.tweets_df,temp_df])\n",
    "            except:\n",
    "                print(date,end = \" \")\n",
    "        self.tweets_df.columns = [\"text\",\"date\",\"time\",\"user_id\"]\n",
    "        self.tweets_df = self.tweets_df.reset_index(drop= True)\n",
    "        self.date_list = self.tweets_df.sort_values(\"date\")[\"date\"].unique().tolist()\n",
    "\n",
    "        # Prices\n",
    "        price_path = f\"../../stocknet-dataset/price/raw/{stock_name}.csv\"\n",
    "        self.price_df = pd.read_csv(price_path)\n",
    "        self.price_df = self.price_df[self.price_df.Date.isin(self.date_list)]\n",
    "        self.price_df[self.cal_on] /= self.price_df.iloc[0][self.cal_on]\n",
    "        self.date_list = self.price_df.sort_values(\"Date\")[\"Date\"].unique().tolist()\n",
    "\n",
    "    def reset(self):\n",
    "        self.day_index = 0\n",
    "        self.today = self.date_list[self.day_index]\n",
    "        self.today_sentences = self.tweets_df[self.tweets_df.date == self.today]\n",
    "        self.today_price = self.price_df[self.price_df[\"Date\"] == self.today]\n",
    "        self.today_cash = self.init_cash\n",
    "        self.today_hold = self.init_hold\n",
    "        self.terminal = False\n",
    "        self.asset_memory = [self.init_hold * self.today_price[self.cal_on].item() + self.today_cash]\n",
    "        self.hold_memory = [self.init_hold]\n",
    "        self.cash_memory = [self.init_cash]\n",
    "        self.reward_momory = [0]\n",
    "        self.action_memory = [0]\n",
    "\n",
    "        return self.today_sentences.text.tolist()\n",
    "    \n",
    "    def update(self):\n",
    "        if self.day_index >= len(self.date_list)-1:\n",
    "            self.terminal = True\n",
    "        else:\n",
    "            self.day_index += 1\n",
    "            self.today = self.date_list[self.day_index]\n",
    "            self.today_sentences = self.tweets_df[self.tweets_df.date == self.today]\n",
    "            self.today_price = self.price_df[self.price_df[\"Date\"] == self.today]\n",
    "\n",
    "    def step(self,action):\n",
    "        last_price = self.today_price[self.cal_on].item()\n",
    "        last_hold = self.today_hold\n",
    "        last_cash = self.today_cash\n",
    "        last_asset = last_price * last_hold + last_cash\n",
    "        self.update()\n",
    "        if self.terminal:\n",
    "            print(\"\\n\\nall_done\")\n",
    "        else:\n",
    "            next_price = self.today_price[self.cal_on].item()\n",
    "            if action >0:\n",
    "                buy_cost = self.trade_volumn * next_price\n",
    "                today_cash = self.today_cash - buy_cost\n",
    "                if today_cash >= 0 :\n",
    "                    self.today_hold += self.trade_volumn \n",
    "                    self.today_cash = today_cash\n",
    "                else:\n",
    "                    avaliable_volumn = self.today_cash / next_price\n",
    "                    self.today_hold += avaliable_volumn\n",
    "                    self.today_cash = 0\n",
    "\n",
    "            \n",
    "            elif action <0:\n",
    "                today_hold = self.today_hold - self.trade_volumn \n",
    "                if today_hold >= 0:\n",
    "                    sell_earn = self.trade_volumn * next_price\n",
    "                    self.today_cash += sell_earn\n",
    "                    self.today_hold = today_hold\n",
    "                else:\n",
    "                    self.today_cash += next_price * self.today_hold\n",
    "                    self.today_hold = 0\n",
    "            \n",
    "            else:\n",
    "                pass\n",
    "                \n",
    "            next_asset = self.today_hold * next_price +  self.today_cash   \n",
    "            self.reward = next_asset - last_asset\n",
    "            self.asset_memory.append(next_asset)\n",
    "            self.hold_memory.append(self.today_hold)\n",
    "            self.reward_momory.append(self.reward)\n",
    "            self.action_memory.append(action)\n",
    "            self.cash_memory.append(self.today_cash)\n",
    "        \n",
    "        return self.today_sentences.text.tolist(), self.reward ,self.terminal ,{}\n",
    "    "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### GPT Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import numpy as np\n",
    "import pickle\n",
    "import time\n",
    "\n",
    "class GPT_agent:\n",
    "    def __init__(self, args):\n",
    "        args = edict(args)\n",
    "        self.model_name = args.model_name\n",
    "        self.source = args.source\n",
    "        self.buy_threshold = args.get(\"buy_threshold\", 0.3)\n",
    "        self.sell_threshold = args.get(\"sell_threshold\", -0.3)\n",
    "\n",
    "        # Init\n",
    "        if self.source == \"openai\":\n",
    "            openai.api_key = args.api_key\n",
    "        elif self.source == \"local\":\n",
    "            with open(f\"./data/{self.model_name}.pkl\", \"rb\") as f:\n",
    "                self.sentiment_dict = pickle.load(f)\n",
    "\n",
    "    def __call__(self, obs):\n",
    "        self.score_list = [self.get_sentiment(o) for o in obs]\n",
    "        self.score_list_mean = np.mean(self.score_list)\n",
    "        return 1 if self.score_list_mean > self.buy_threshold else -1 if self.score_list_mean < self.sell_threshold else 0\n",
    "\n",
    "    def get_sentiment(self, sentence):\n",
    "        if self.source == \"openai\":\n",
    "            time.sleep(1)\n",
    "            response = openai.Completion.create(\n",
    "                model=self.model_name,\n",
    "                prompt=f\"Decide whether a sentence's sentiment is positive, neutral, or negative.\\n\\nSentence: \\\"{sentence}\\\"\\nSentiment: \",\n",
    "                temperature=0,\n",
    "                max_tokens=60,\n",
    "                top_p=1,\n",
    "                frequency_penalty=0.5,\n",
    "                presence_penalty=0\n",
    "            )\n",
    "            response = response[\"choices\"][0][\"text\"]\n",
    "        elif self.source == \"local\":\n",
    "            response = self.sentiment_dict.get(sentence, \"\")\n",
    "\n",
    "        if \"negative\" in response.lower():\n",
    "            return -1\n",
    "        elif \"positive\" in response.lower():\n",
    "            return 1\n",
    "        else:\n",
    "            return 0\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Trade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "missing (empty means not missing): 2014-01-17 2014-01-18 2014-06-17 2014-08-05 2014-08-06 2014-09-24 2014-09-25 2014-09-26 2014-09-27 2014-09-28 2014-11-10 2014-11-11 2014-11-12 2014-11-13 2014-11-15 2014-11-16 2014-11-17 2014-11-18 2014-11-19 2014-11-20 2014-11-21 2014-11-22 2014-11-23 2014-12-20 2015-03-08 2015-06-05 2015-06-23 2015-07-08 2015-08-15 2015-09-17 2015-09-18 2015-11-27 2015-12-16 2015-12-18 \n",
      "\n",
      "all_done\n"
     ]
    }
   ],
   "source": [
    "env = Tweets_trading_env(env_args)\n",
    "agent = GPT_agent(agent_args)\n",
    "obs = env.reset()\n",
    "terminal = False\n",
    "while not terminal:\n",
    "    action = agent(obs)\n",
    "    obs,reward,terminal,info = env.step(action)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 168544 characters]",
      "text/plain": [
       "<Figure size 1152x1152 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime\n",
    "plt.figure(figsize=(16,4*4),facecolor='white')\n",
    "\n",
    "\n",
    "# assets\n",
    "plt.subplot(4,1,1)\n",
    "assets = env.asset_memory\n",
    "assets = [i/assets[0] for i in assets]\n",
    "xs = [datetime.strptime(d, '%Y-%m-%d').date() for d in env.date_list]\n",
    "plt.title(\"AAPL Chatgpt trading results\")\n",
    "plt.plot(xs,env.price_df.reset_index(drop = True).Close.tolist(),label = \"buy-and-hold\")\n",
    "plt.plot(xs,assets,label = \"gpt-trading\")\n",
    "plt.ylabel(\"return rate\")\n",
    "plt.legend()\n",
    "\n",
    "# singals\n",
    "plt.subplot(4,1,2)\n",
    "actions = env.action_memory\n",
    "plt.plot(xs,actions,label = \"signals\")\n",
    "plt.ylabel(\"signals\")\n",
    "\n",
    "# stock/cash holdings\n",
    "plt.subplot(4,1,3)\n",
    "holds = env.hold_memory\n",
    "cash = env.cash_memory\n",
    "plt.plot(xs,holds,label = \"stock_holdings\")\n",
    "plt.plot(xs,cash,label = \"cash_holdings\")\n",
    "plt.ylabel(\"stock/cash holdings\")\n",
    "plt.legend()\n",
    "\n",
    "# earnings\n",
    "plt.subplot(4,1,4)\n",
    "rewards = env.reward_momory\n",
    "plt.plot(xs,rewards,label = \"rewards\")\n",
    "plt.ylabel(\"rewards\")\n",
    "plt.savefig(\"output.png\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Backtest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6611161275697802"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# return rate\n",
    "(env.asset_memory[-1]-env.asset_memory[0])/env.asset_memory[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "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>time</th>\n",
       "      <th>account_value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2014-01-02</td>\n",
       "      <td>100.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2014-01-03</td>\n",
       "      <td>100.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         time account_value\n",
       "0  2014-01-02         100.0\n",
       "1  2014-01-03         100.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "account_value = env.asset_memory\n",
    "baseline_value = env.price_df.Close.tolist()\n",
    "date_list = env.date_list\n",
    "\n",
    "df_account_value = pd.DataFrame([date_list,account_value],index= [\"time\",\"account_value\"]).T\n",
    "df_baseline = pd.DataFrame([date_list,baseline_value],index= [\"time\",\"account_value\"]).T\n",
    "\n",
    "df_account_value.head(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_return(df, value_col_name=\"account_value\"):\n",
    "    df[\"daily_return\"] = df[value_col_name].pct_change(1)\n",
    "    df[\"time\"] = pd.to_datetime(df[\"time\"], format=\"%Y-%m-%d\")\n",
    "    df.set_index(\"time\", inplace=True, drop=True)\n",
    "    df.index = df.index.tz_localize(\"UTC\")\n",
    "    return pd.Series(df[\"daily_return\"], index=df.index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==============DRL Strategy Stats===========\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Annual return          0.306025\n",
       "Cumulative returns     0.661116\n",
       "Annual volatility      0.134534\n",
       "Sharpe ratio           2.055749\n",
       "Calmar ratio           4.514700\n",
       "Stability              0.868554\n",
       "Max drawdown          -0.067784\n",
       "Omega ratio            1.997149\n",
       "Sortino ratio          4.298199\n",
       "Skew                        NaN\n",
       "Kurtosis                    NaN\n",
       "Tail ratio             1.838620\n",
       "Daily value at risk   -0.015852\n",
       "Alpha                  0.241364\n",
       "Beta                   0.313467\n",
       "dtype: float64"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pyfolio\n",
    "from pyfolio import timeseries\n",
    "daily_return = get_return(df_account_value)\n",
    "daily_return_base = get_return(df_baseline)\n",
    "\n",
    "perf_func = timeseries.perf_stats\n",
    "perf_stats_all = perf_func(returns=daily_return, \n",
    "                              factor_returns=daily_return_base, \n",
    "                                positions=None, transactions=None, turnover_denom=\"AGB\")\n",
    "print(\"==============DRL Strategy Stats===========\")\n",
    "perf_stats_all"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\"><th>Start date</th><td colspan=2>2014-01-02</td></tr>\n",
       "    <tr style=\"text-align: right;\"><th>End date</th><td colspan=2>2015-12-30</td></tr>\n",
       "    <tr style=\"text-align: right;\"><th>Total months</th><td colspan=2>22</td></tr>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Backtest</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Annual return</th>\n",
       "      <td>30.603%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Cumulative returns</th>\n",
       "      <td>66.112%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Annual volatility</th>\n",
       "      <td>13.453%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Sharpe ratio</th>\n",
       "      <td>2.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Calmar ratio</th>\n",
       "      <td>4.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Stability</th>\n",
       "      <td>0.87</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Max drawdown</th>\n",
       "      <td>-6.778%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Omega ratio</th>\n",
       "      <td>2.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Sortino ratio</th>\n",
       "      <td>4.30</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Skew</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Kurtosis</th>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Tail ratio</th>\n",
       "      <td>1.84</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Daily value at risk</th>\n",
       "      <td>-1.585%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Alpha</th>\n",
       "      <td>0.24</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Beta</th>\n",
       "      <td>0.31</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Worst drawdown periods</th>\n",
       "      <th>Net drawdown in %</th>\n",
       "      <th>Peak date</th>\n",
       "      <th>Valley date</th>\n",
       "      <th>Recovery date</th>\n",
       "      <th>Duration</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6.78</td>\n",
       "      <td>2014-12-29</td>\n",
       "      <td>2015-01-16</td>\n",
       "      <td>2015-01-28</td>\n",
       "      <td>23</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6.25</td>\n",
       "      <td>2014-09-02</td>\n",
       "      <td>2014-10-16</td>\n",
       "      <td>2014-10-22</td>\n",
       "      <td>37</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.21</td>\n",
       "      <td>2014-06-10</td>\n",
       "      <td>2014-06-24</td>\n",
       "      <td>2014-07-07</td>\n",
       "      <td>20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3.90</td>\n",
       "      <td>2015-02-23</td>\n",
       "      <td>2015-08-24</td>\n",
       "      <td>NaT</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2.57</td>\n",
       "      <td>2014-05-05</td>\n",
       "      <td>2014-05-09</td>\n",
       "      <td>2014-05-19</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>Stress Events</th>\n",
       "      <th>mean</th>\n",
       "      <th>min</th>\n",
       "      <th>max</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Apr14</th>\n",
       "      <td>0.54%</td>\n",
       "      <td>-1.24%</td>\n",
       "      <td>7.76%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Oct14</th>\n",
       "      <td>0.31%</td>\n",
       "      <td>-1.56%</td>\n",
       "      <td>2.72%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Fall2015</th>\n",
       "      <td>-0.00%</td>\n",
       "      <td>-0.14%</td>\n",
       "      <td>0.12%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>New Normal</th>\n",
       "      <td>0.11%</td>\n",
       "      <td>-3.50%</td>\n",
       "      <td>7.76%</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 381596 characters]",
      "text/plain": [
       "<Figure size 1008x5184 with 13 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 106808 characters]",
      "text/plain": [
       "<Figure size 1008x864 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "with pyfolio.plotting.plotting_context(font_scale=1.1):\n",
    "        pyfolio.create_full_tear_sheet(returns = daily_return,\n",
    "                                       benchmark_rets = daily_return_base, set_context=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "finrl",
   "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.12"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "afd6dc03c9be451573fc2885de79a969af6a24a159f11a3ead741ab7a9ff405f"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
