{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Custom Code Executor\n",
    "\n",
    "In this guide we will show you how to create a custom code executor that runs\n",
    "code inside the same Jupyter notebook as this one.\n",
    "\n",
    "First, let's install the required dependencies:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip -qqq install autogen-agentchat~=0.2 matplotlib yfinance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from typing import List\n",
    "\n",
    "from IPython import get_ipython\n",
    "\n",
    "from autogen import ConversableAgent\n",
    "from autogen.coding import CodeBlock, CodeExecutor, CodeExtractor, CodeResult, MarkdownCodeExtractor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can create the custom code executor class by subclassing the\n",
    "`CodeExecutor` protocol and implementing the `execute_code_blocks` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "class NotebookExecutor(CodeExecutor):\n",
    "\n",
    "    @property\n",
    "    def code_extractor(self) -> CodeExtractor:\n",
    "        # Extact code from markdown blocks.\n",
    "        return MarkdownCodeExtractor()\n",
    "\n",
    "    def __init__(self) -> None:\n",
    "        # Get the current IPython instance running in this notebook.\n",
    "        self._ipython = get_ipython()\n",
    "\n",
    "    def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CodeResult:\n",
    "        log = \"\"\n",
    "        for code_block in code_blocks:\n",
    "            result = self._ipython.run_cell(\"%%capture --no-display cap\\n\" + code_block.code)\n",
    "            log += self._ipython.ev(\"cap.stdout\")\n",
    "            log += self._ipython.ev(\"cap.stderr\")\n",
    "            if result.result is not None:\n",
    "                log += str(result.result)\n",
    "            exitcode = 0 if result.success else 1\n",
    "            if result.error_before_exec is not None:\n",
    "                log += f\"\\n{result.error_before_exec}\"\n",
    "                exitcode = 1\n",
    "            if result.error_in_exec is not None:\n",
    "                log += f\"\\n{result.error_in_exec}\"\n",
    "                exitcode = 1\n",
    "            if exitcode != 0:\n",
    "                break\n",
    "        return CodeResult(exit_code=exitcode, output=log)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can use the new custom code executor in our agents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "code_writer_agent = ConversableAgent(\n",
    "    name=\"CodeWriter\",\n",
    "    system_message=\"You are a helpful AI assistant.\\n\"\n",
    "    \"You use your coding skill to solve problems.\\n\"\n",
    "    \"You have access to a IPython kernel to execute Python code.\\n\"\n",
    "    \"You can suggest Python code in Markdown blocks, each block is a cell.\\n\"\n",
    "    \"The code blocks will be executed in the IPython kernel in the order you suggest them.\\n\"\n",
    "    \"All necessary libraries have already been installed.\\n\"\n",
    "    \"Once the task is done, returns 'TERMINATE'.\",\n",
    "    llm_config={\"config_list\": [{\"model\": \"gpt-4\", \"api_key\": os.getenv(\"OPENAI_API_KEY\")}]},\n",
    ")\n",
    "\n",
    "code_executor_agent = ConversableAgent(\n",
    "    name=\"CodeExecutor\",\n",
    "    llm_config=False,\n",
    "    code_execution_config={\"executor\": NotebookExecutor()},\n",
    "    is_termination_msg=lambda msg: \"TERMINATE\" in msg.get(\"content\", \"\").strip().upper(),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's use the agents to complete a simple task of drawing a plot showing\n",
    "the market caps of the top 7 publicly listed companies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "Create a plot showing the market caps of the top 7 publicly listed companies using data from Yahoo Finance.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "To accomplish this task, we would use the `yfinance` library to fetch data from Yahoo Finance, `pandas` library for data manipulation, and `matplotlib` for data visualization.\n",
      "\n",
      "Steps:\n",
      "1. Identify the tickers for the top 7 largest publicly listed companies. Currently, these companies are: Apple (AAPL), Microsoft (MSFT), Google (GOOGL), Amazon (AMZN), Facebook (FB), Tesla (TSLA), and Berkshire Hathaway (BRK-A).\n",
      "2. Fetch market cap information for these companies using yfinance.\n",
      "3. Clean and process the fetched data into a usable format (a pandas DataFrame).\n",
      "4. Plot the market caps for these companies.\n",
      "\n",
      "Let's start by fetching data for these companies.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "Great! Before I continue, I need to know if the necessary libraries are installed.\n",
      "\n",
      "The libraries needed for this task are:\n",
      "1. `yfinance`\n",
      "2. `pandas`\n",
      "3. `matplotlib`\n",
      "\n",
      "If these libraries are not installed, you can install them using pip:\n",
      "\n",
      "```python\n",
      "!pip install yfinance pandas matplotlib\n",
      "```\n",
      "\n",
      "Assuming these libraries are installed, we would import them and proceed with fetching the market cap data:\n",
      "\n",
      "```python\n",
      "import yfinance as yf\n",
      "import pandas as pd\n",
      "import matplotlib.pyplot as plt\n",
      "\n",
      "# Define tickers \n",
      "tickers = [\"AAPL\", \"MSFT\", \"GOOGL\", \"AMZN\", \"FB\", \"TSLA\", \"BRK-A\"]\n",
      "\n",
      "# Fetch data\n",
      "data = yf.download(tickers, start=\"2022-02-01\", end=\"2022-02-28\")\n",
      "\n",
      "# Extract only 'Close' values for each ticker\n",
      "data = data['Close']\n",
      "\n",
      "# Create empty dictionary to hold market cap data\n",
      "market_caps = {}\n",
      "\n",
      "# Calculate market caps\n",
      "for ticker in tickers:\n",
      "    info = yf.Ticker(ticker).info\n",
      "    market_caps[ticker] = info[\"marketCap\"]\n",
      "\n",
      "# Convert market_caps dictionary to pandas DataFrame\n",
      "df = pd.DataFrame(list(market_caps.items()), columns=['Company', 'Market_Cap'])\n",
      "\n",
      "# Sort DataFrame by Market_Cap in descending order\n",
      "df = df.sort_values('Market_Cap', ascending=False)\n",
      "\n",
      "# Plot data\n",
      "plt.figure(figsize=(10,6))\n",
      "plt.barh(df['Company'], df['Market_Cap'], color='skyblue')\n",
      "plt.xlabel('Market Cap (in trillions)')\n",
      "plt.title('Market Caps of Top 7 Publicly Listed Companies')\n",
      "plt.gca().invert_yaxis()\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "Please note that the start and end dates used while fetching data specifies the time period we are interested in. Feel free to modify these as needed. The 'marketCap' obtained from the 'info' property of the Ticker object represents the market cap as of the end date.\n",
      "\n",
      "Also note that the final plot shows the companies in descending order of market cap, with the company with the highest market cap at the top of the chart.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING 2 CODE BLOCKS (inferred languages are [python, python])...\u001b[0m\n"
     ]
    },
    {
     "ename": "KeyError",
     "evalue": "'marketCap'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[24], line 20\u001b[0m\n\u001b[1;32m     18\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m ticker \u001b[38;5;129;01min\u001b[39;00m tickers:\n\u001b[1;32m     19\u001b[0m     info \u001b[38;5;241m=\u001b[39m yf\u001b[38;5;241m.\u001b[39mTicker(ticker)\u001b[38;5;241m.\u001b[39minfo\n\u001b[0;32m---> 20\u001b[0m     market_caps[ticker] \u001b[38;5;241m=\u001b[39m \u001b[43minfo\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mmarketCap\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\n\u001b[1;32m     22\u001b[0m \u001b[38;5;66;03m# Convert market_caps dictionary to pandas DataFrame\u001b[39;00m\n\u001b[1;32m     23\u001b[0m df \u001b[38;5;241m=\u001b[39m pd\u001b[38;5;241m.\u001b[39mDataFrame(\u001b[38;5;28mlist\u001b[39m(market_caps\u001b[38;5;241m.\u001b[39mitems()), columns\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCompany\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mMarket_Cap\u001b[39m\u001b[38;5;124m'\u001b[39m])\n",
      "\u001b[0;31mKeyError\u001b[0m: 'marketCap'"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: Requirement already satisfied: yfinance in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (0.2.36)\n",
      "Requirement already satisfied: pandas in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (2.2.1)\n",
      "Requirement already satisfied: matplotlib in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (3.8.3)\n",
      "Requirement already satisfied: numpy>=1.16.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.26.4)\n",
      "Requirement already satisfied: requests>=2.31 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2.31.0)\n",
      "Requirement already satisfied: multitasking>=0.0.7 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (0.0.11)\n",
      "Requirement already satisfied: lxml>=4.9.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (5.0.1)\n",
      "Requirement already satisfied: appdirs>=1.4.4 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.4.4)\n",
      "Requirement already satisfied: pytz>=2022.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2023.3.post1)\n",
      "Requirement already satisfied: frozendict>=2.3.4 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2.4.0)\n",
      "Requirement already satisfied: peewee>=3.16.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (3.17.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.11.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (4.12.2)\n",
      "Requirement already satisfied: html5lib>=1.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.1)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from pandas) (2.8.2)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from pandas) (2023.4)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (1.2.0)\n",
      "Requirement already satisfied: cycler>=0.10 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (0.12.1)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (4.47.2)\n",
      "Requirement already satisfied: kiwisolver>=1.3.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (1.4.5)\n",
      "Requirement already satisfied: packaging>=20.0 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (23.2)\n",
      "Requirement already satisfied: pillow>=8 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (10.2.0)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (3.1.1)\n",
      "Requirement already satisfied: soupsieve>1.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",
      "Requirement already satisfied: six>=1.9 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",
      "Requirement already satisfied: webencodings in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (1.26.18)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (2024.2.2)\n",
      "/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[**************        29%%                      ]  2 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[********************* 43%%                      ]  3 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[**********************57%%*                     ]  4 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[**********************71%%********              ]  5 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[*********************100%%**********************]  7 of 7 completed\n",
      "\n",
      "1 Failed download:\n",
      "['FB']: Exception('%ticker%: No timezone found, symbol may be delisted')\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "From the error message, it seems that the 'FB' ticker (Facebook) failed to download because it might have been delisted. This is likely due to Facebook's corporate rebranding to Meta Platforms Inc. in late 2021, which resulted in a ticker change from 'FB' to 'META'.\n",
      "\n",
      "To resolve this, we'll replace 'FB' in our tickers list with 'META' and then retrieve the data again. Here is the modified code:\n",
      "\n",
      "```python\n",
      "# Define tickers \n",
      "tickers = [\"AAPL\", \"MSFT\", \"GOOGL\", \"AMZN\", \"META\", \"TSLA\", \"BRK-A\"]\n",
      "\n",
      "# Fetch data\n",
      "data = yf.download(tickers, start=\"2022-02-01\", end=\"2022-02-28\")\n",
      "\n",
      "# Extract only 'Close' values for each ticker\n",
      "data = data['Close']\n",
      "\n",
      "# Create empty dictionary to hold market cap data\n",
      "market_caps = {}\n",
      "\n",
      "# Calculate market caps\n",
      "for ticker in tickers:\n",
      "    info = yf.Ticker(ticker).info\n",
      "    market_caps[ticker] = info[\"marketCap\"]\n",
      "\n",
      "# Convert market_caps dictionary to pandas DataFrame\n",
      "df = pd.DataFrame(list(market_caps.items()), columns=['Company', 'Market_Cap'])\n",
      "\n",
      "# Sort DataFrame by Market_Cap in descending order\n",
      "df = df.sort_values('Market_Cap', ascending=False)\n",
      "\n",
      "# Plot data\n",
      "plt.figure(figsize=(10,6))\n",
      "plt.barh(df['Company'], df['Market_Cap'], color='skyblue')\n",
      "plt.xlabel('Market Cap (in trillions)')\n",
      "plt.title('Market Caps of Top 7 Publicly Listed Companies')\n",
      "plt.gca().invert_yaxis()\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 29648 characters]",
      "text/plain": [
       "<Figure size 1000x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[                       0%%                      ]/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[********************* 43%%                      ]  3 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[**********************57%%*                     ]  4 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[**********************71%%********              ]  5 of 7 completed/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
      "  df.index += _pd.TimedeltaIndex(dst_error_hours, 'h')\n",
      "[*********************100%%**********************]  7 of 7 completed\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "I see that the fetched data was successfully retrieved and processed. However, it looks like the result of the plot isn't visible, so we don't know whether the plot was generated successfully. Please run the code again and provide the output of the plot.\n",
      "\n",
      "If there are any issues or any other points you would like me to help with, let me know!\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "I'm glad we were able to retrieve and process the data successfully. Please try running the last part of the code again to generate and display the plot:\n",
      "\n",
      "```python\n",
      "# Plot data\n",
      "plt.figure(figsize=(10,6))\n",
      "plt.barh(df['Company'], df['Market_Cap'], color='skyblue')\n",
      "plt.xlabel('Market Cap (in trillions)')\n",
      "plt.title('Market Caps of Top 7 Publicly Listed Companies')\n",
      "plt.gca().invert_yaxis()\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "This section of the code creates a horizontal bar plot of the market capitalizations of the companies. The `plt.gca().invert_yaxis()` line is included to invert the y-axis, so the company with the highest market cap is at the top of the chart.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 29648 characters]",
      "text/plain": [
       "<Figure size 1000x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "I see that the code has executed successfully, but unfortunately, the generated plot is not visible here. However, given that there are no errors, it's likely that the plot has been created as expected when you executed the code on your end.\n",
      "\n",
      "If you have any other questions related to this code or need further assistance with Python coding or data visualization, please let me know! I'm here to help.\n",
      "\n",
      "Otherwise, if this completes your initial request, I will end this task. Just let me know your decision.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeExecutor\u001b[0m (to CodeWriter):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mCodeWriter\u001b[0m (to CodeExecutor):\n",
      "\n",
      "Alright. If you have any more questions regarding this task, or if you need help with other tasks in the future, don't hesitate to ask. Have a great day!\n",
      "\n",
      "'---TERMINATE---'\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=\"Create a plot showing the market caps of the top 7 publicly listed companies using data from Yahoo Finance.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see the plots are now displayed in the current notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "autogen",
   "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.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
