Files
patchy631--ai-engineering-hub/autogen-stock-analyst/coding_and_financial_analyst.ipynb
T
2026-07-13 12:37:47 +08:00

402 lines
28 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"ename": "",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[1;31mRunning cells with 'env_qualcomm (Python 3.11.10)' requires the ipykernel package.\n",
"\u001b[1;31mRun the following command to install 'ipykernel' into the Python environment. \n",
"\u001b[1;31mCommand: 'conda install -n env_qualcomm ipykernel --update-deps --force-reinstall'"
]
}
],
"source": [
"import os\n",
"import autogen\n",
"import json\n",
"from dotenv import load_dotenv\n",
"load_dotenv()\n",
"\n",
"\n",
"import datetime\n",
"import os\n",
"\n",
"# custom_autogen_model package\n",
"from custom_autogen_model import CustomModelClient\n",
"\n",
"\n",
"# pyautogen package\n",
"from autogen import ConversableAgent, UserProxyAgent, AssistantAgent\n",
"from autogen.coding import LocalCommandLineCodeExecutor\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def config_list(config, client_name=\"CustomModelClient\"):\n",
" dict_list = [config]\n",
"\n",
" # set the config into an environment variable\n",
" os.environ[\"IMAGINE_AUTOGEN_CONFIG\"] = json.dumps(dict_list)\n",
"\n",
" config_list_custom = autogen.config_list_from_json(\n",
" \"IMAGINE_AUTOGEN_CONFIG\",\n",
" filter_dict={\"model_client_cls\": [client_name]},\n",
" )\n",
" return config_list_custom"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"api_key = os.environ[\"IMAGINE_API_KEY\"]\n",
"\n",
"config = {\n",
" \"model\": \"imaginechat\",\n",
" \"model_client_cls\": \"CustomModelClient\",\n",
" \"n\": 1,\n",
" \"params\": {\"max_length\": 1500, \"api_key\": api_key, \"temperature\": 0.0},\n",
"}\n",
"\n",
"config_list_custom = config_list(config)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"executor = LocalCommandLineCodeExecutor(\n",
" timeout=60,\n",
" work_dir=\"coding\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"code_executor_agent = ConversableAgent(\n",
" name=\"code_executor_agent\",\n",
" code_execution_config={\"executor\": executor},\n",
" default_auto_reply=\"Please continue. If everything is done, reply 'TERMINATE'.\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[autogen.oai.client: 11-18 19:23:37] {565} INFO - Detected custom model client in config: CustomModelClient, model client can not be used until register_model_client is called.\n"
]
}
],
"source": [
"code_writer_agent = UserProxyAgent(\n",
" name=\"code_writer_agent\",\n",
" llm_config={\"config_list\": config_list_custom},\n",
" code_execution_config=False,\n",
")\n",
"\n",
"# code_writer_agent = AssistantAgent(\n",
"# name=\"code_writer_agent\",\n",
"# llm_config={\"config_list\": config_list_custom},\n",
"# code_execution_config=False,\n",
"# human_input_mode=\"NEVER\",\n",
"# )"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CustomModelClient config: {'model': 'imaginechat', 'model_client_cls': 'CustomModelClient', 'n': 1, 'params': {'max_length': 1500, 'api_key': '38e48000-4d41-4a15-9cfb-e97056b06eb8', 'temperature': 0.0}}\n",
"Loaded model imaginechat\n"
]
}
],
"source": [
"# register the custom client class to the agents\n",
"code_writer_agent.register_model_client(model_client_cls=CustomModelClient)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"source": [
"code_writer_agent_system_message = code_writer_agent.system_message\n",
"print(code_writer_agent_system_message)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"# Ask the two agents to collaborate on a stock analysis task.\n",
"today = datetime.datetime.now().date()\n",
"message = (\n",
" f\"Today is {today}. \"\n",
" \"Create a plot showing stock gain YTD over the whole year for (Qualcomm) QCOM and (Tesla) TSLA. \"\n",
" \"Make sure the code is in python code block and save the figure\"\n",
" \" to a file ytd_stock_gains.png.\"\n",
" \"use the yfinance lib\"\n",
" \"\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
"\n",
"Today is 2024-11-18. Create a plot showing stock gain YTD over the whole year for (Qualcomm) QCOM and (Tesla) TSLA. Make sure the code is in python code block and save the figure to a file ytd_stock_gains.png.use the yfinance lib\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
"\u001b[31m\n",
">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
"response: namespace(choices=[namespace(message=namespace(content=AIMessage(content=\"Here is a Python code block that uses the yfinance library to retrieve the stock data for Qualcomm (QCOM) and Tesla (TSLA) and plots the year-to-date (YTD) stock gains:\\n```python\\nimport yfinance as yf\\nimport matplotlib.pyplot as plt\\n\\n# Define the stock tickers\\ntickers = ['QCOM', 'TSLA']\\n\\n# Get the historical data for each stock\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n\\n # Calculate the YTD gain\\n ytd_gain = (stock_data['Close'][-1] - stock_data['Close'][0]) / stock_data['Close'][0] * 100\\n\\n # Print the YTD gain\\n print(f'{ticker}: {ytd_gain:.2f}%')\\n\\n# Create a figure and axis\\nfig, ax = plt.subplots()\\n\\n# Plot the YTD gains\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'][0]) / stock_data['Close'][0] * 100, label=ticker)\\n\\n# Set the title and labels\\nax.set_title('Year-to-Date Stock Gains')\\nax.set_xlabel('Date')\\nax.set_ylabel('Gain (%)')\\nax.legend()\\n\\n# Save the figure to a file\\nplt.savefig('ytd_stock_gains.png')\\n\\n# Show the plot\\nplt.show()\\n```\\nThis code will create a line plot showing the YTD gains for both QCOM and TSLA, with the x-axis representing the date and the y-axis representing the gain percentage. The plot will be saved to a file named `ytd_stock_gains.png`.\\n\\nNote: Make sure you have the yfinance and matplotlib libraries installed by running `pip install yfinance matplotlib` in your terminal before running this code.\", additional_kwargs={}, response_metadata={'token_usage': {'prompt_tokens': 75, 'total_tokens': 501, 'completion_tokens': 426}, 'model': 'Llama-3.1-8B', 'finish_reason': 'FinishReason.stop'}, id='run-4af98e33-49b2-4bce-8eb3-62c6b05dd825-0', usage_metadata={'input_tokens': 75, 'output_tokens': 426, 'total_tokens': 501}), tool_calls=None))], model='imaginechat', cost=0, message_retrieval_function=<bound method CustomModelClient.message_retrieval of <custom_autogen_model.CustomModelClient object at 0x12a50ff10>>, config_id=0, pass_filter=True)\n",
"\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
"\n",
"Here is a Python code block that uses the yfinance library to retrieve the stock data for Qualcomm (QCOM) and Tesla (TSLA) and plots the year-to-date (YTD) stock gains:\n",
"```python\n",
"import yfinance as yf\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Define the stock tickers\n",
"tickers = ['QCOM', 'TSLA']\n",
"\n",
"# Get the historical data for each stock\n",
"for ticker in tickers:\n",
" stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\n",
"\n",
" # Calculate the YTD gain\n",
" ytd_gain = (stock_data['Close'][-1] - stock_data['Close'][0]) / stock_data['Close'][0] * 100\n",
"\n",
" # Print the YTD gain\n",
" print(f'{ticker}: {ytd_gain:.2f}%')\n",
"\n",
"# Create a figure and axis\n",
"fig, ax = plt.subplots()\n",
"\n",
"# Plot the YTD gains\n",
"for ticker in tickers:\n",
" stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\n",
" ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'][0]) / stock_data['Close'][0] * 100, label=ticker)\n",
"\n",
"# Set the title and labels\n",
"ax.set_title('Year-to-Date Stock Gains')\n",
"ax.set_xlabel('Date')\n",
"ax.set_ylabel('Gain (%)')\n",
"ax.legend()\n",
"\n",
"# Save the figure to a file\n",
"plt.savefig('ytd_stock_gains.png')\n",
"\n",
"# Show the plot\n",
"plt.show()\n",
"```\n",
"This code will create a line plot showing the YTD gains for both QCOM and TSLA, with the x-axis representing the date and the y-axis representing the gain percentage. The plot will be saved to a file named `ytd_stock_gains.png`.\n",
"\n",
"Note: Make sure you have the yfinance and matplotlib libraries installed by running `pip install yfinance matplotlib` in your terminal before running this code.\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",
"\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
"\n",
"exitcode: 1 (execution failed)\n",
"Code output: \n",
"[*********************100%***********************] 1 of 1 completed\n",
"Traceback (most recent call last):\n",
" File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3805, in get_loc\n",
" return self._engine.get_loc(casted_key)\n",
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
" File \"index.pyx\", line 167, in pandas._libs.index.IndexEngine.get_loc\n",
" File \"index.pyx\", line 196, in pandas._libs.index.IndexEngine.get_loc\n",
" File \"pandas/_libs/hashtable_class_helper.pxi\", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item\n",
" File \"pandas/_libs/hashtable_class_helper.pxi\", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item\n",
"KeyError: -1\n",
"\n",
"The above exception was the direct cause of the following exception:\n",
"\n",
"Traceback (most recent call last):\n",
" File \"/Users/akshaypachaar/Eigen/crewai-qualcomm/coding/tmp_code_f894a8bbf923d30a7d0fbc4d8b2f6b62.py\", line 12, in <module>\n",
" ytd_gain = (stock_data['Close'][-1] - stock_data['Close'][0]) / stock_data['Close'][0] * 100\n",
" ~~~~~~~~~~~~~~~~~~~^^^^\n",
" File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/frame.py\", line 4102, in __getitem__\n",
" indexer = self.columns.get_loc(key)\n",
" ^^^^^^^^^^^^^^^^^^^^^^^^^\n",
" File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3812, in get_loc\n",
" raise KeyError(key) from err\n",
"KeyError: -1\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
"\u001b[31m\n",
">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
"params : {'messages': [{'content': '', 'role': 'system'}, {'content': 'Today is 2024-11-18. Create a plot showing stock gain YTD over the whole year for (Qualcomm) QCOM and (Tesla) TSLA. Make sure the code is in python code block and save the figure to a file ytd_stock_gains.png.use the yfinance lib', 'role': 'user', 'name': 'code_executor_agent'}, {'content': \"Here is a Python code block that uses the yfinance library to retrieve the stock data for Qualcomm (QCOM) and Tesla (TSLA) and plots the year-to-date (YTD) stock gains:\\n```python\\nimport yfinance as yf\\nimport matplotlib.pyplot as plt\\n\\n# Define the stock tickers\\ntickers = ['QCOM', 'TSLA']\\n\\n# Get the historical data for each stock\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n\\n # Calculate the YTD gain\\n ytd_gain = (stock_data['Close'][-1] - stock_data['Close'][0]) / stock_data['Close'][0] * 100\\n\\n # Print the YTD gain\\n print(f'{ticker}: {ytd_gain:.2f}%')\\n\\n# Create a figure and axis\\nfig, ax = plt.subplots()\\n\\n# Plot the YTD gains\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'][0]) / stock_data['Close'][0] * 100, label=ticker)\\n\\n# Set the title and labels\\nax.set_title('Year-to-Date Stock Gains')\\nax.set_xlabel('Date')\\nax.set_ylabel('Gain (%)')\\nax.legend()\\n\\n# Save the figure to a file\\nplt.savefig('ytd_stock_gains.png')\\n\\n# Show the plot\\nplt.show()\\n```\\nThis code will create a line plot showing the YTD gains for both QCOM and TSLA, with the x-axis representing the date and the y-axis representing the gain percentage. The plot will be saved to a file named `ytd_stock_gains.png`.\\n\\nNote: Make sure you have the yfinance and matplotlib libraries installed by running `pip install yfinance matplotlib` in your terminal before running this code.\", 'tool_calls': [], 'role': 'assistant', 'name': 'code_writer_agent'}, {'content': 'exitcode: 1 (execution failed)\\nCode output: \\n[*********************100%***********************] 1 of 1 completed\\nTraceback (most recent call last):\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3805, in get_loc\\n return self._engine.get_loc(casted_key)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n File \"index.pyx\", line 167, in pandas._libs.index.IndexEngine.get_loc\\n File \"index.pyx\", line 196, in pandas._libs.index.IndexEngine.get_loc\\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item\\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item\\nKeyError: -1\\n\\nThe above exception was the direct cause of the following exception:\\n\\nTraceback (most recent call last):\\n File \"/Users/akshaypachaar/Eigen/crewai-qualcomm/coding/tmp_code_f894a8bbf923d30a7d0fbc4d8b2f6b62.py\", line 12, in <module>\\n ytd_gain = (stock_data[\\'Close\\'][-1] - stock_data[\\'Close\\'][0]) / stock_data[\\'Close\\'][0] * 100\\n ~~~~~~~~~~~~~~~~~~~^^^^\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/frame.py\", line 4102, in __getitem__\\n indexer = self.columns.get_loc(key)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3812, in get_loc\\n raise KeyError(key) from err\\nKeyError: -1\\n', 'role': 'user', 'name': 'code_executor_agent'}], 'model': 'imaginechat', 'model_client_cls': 'CustomModelClient', 'n': 1, 'params': {'max_length': 1500, 'api_key': '38e48000-4d41-4a15-9cfb-e97056b06eb8', 'temperature': 0.0}}\n",
"response: namespace(choices=[namespace(message=namespace(content=AIMessage(content=\"The error occurs because the `stock_data` DataFrame does not have a column named `-1`. The `-1` is an index, not a column name.\\n\\nTo fix this issue, you can calculate the YTD gain using the `iloc` method to access the last and first rows of the DataFrame. Here's the corrected code:\\n\\n```python\\nimport yfinance as yf\\nimport matplotlib.pyplot as plt\\n\\n# Define the stock tickers\\ntickers = ['QCOM', 'TSLA']\\n\\n# Get the historical data for each stock\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n\\n # Calculate the YTD gain\\n ytd_gain = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100\\n\\n # Print the YTD gain\\n print(f'{ticker}: {ytd_gain:.2f}%')\\n\\n# Create a figure and axis\\nfig, ax = plt.subplots()\\n\\n# Plot the YTD gains\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100, label=ticker)\\n\\n# Set the title and labels\\nax.set_title('Year-to-Date Stock Gains')\\nax.set_xlabel('Date')\\nax.set_ylabel('Gain (%)')\\nax.legend()\\n\\n# Save the figure to a file\\nplt.savefig('ytd_stock_gains.png')\\n\\n# Show the plot\\nplt.show()\\n```\\n\\nThis code will correctly calculate the YTD gain and plot the gains for both QCOM and TSLA.\", additional_kwargs={}, response_metadata={'token_usage': {'prompt_tokens': 955, 'total_tokens': 1352, 'completion_tokens': 397}, 'model': 'Llama-3.1-8B', 'finish_reason': 'FinishReason.stop'}, id='run-4c67c89c-1b00-4eff-a36d-1c1e12968c07-0', usage_metadata={'input_tokens': 955, 'output_tokens': 397, 'total_tokens': 1352}), tool_calls=None))], model='imaginechat', cost=0, message_retrieval_function=<bound method CustomModelClient.message_retrieval of <custom_autogen_model.CustomModelClient object at 0x12a50ff10>>, config_id=0, pass_filter=True)\n",
"\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
"\n",
"The error occurs because the `stock_data` DataFrame does not have a column named `-1`. The `-1` is an index, not a column name.\n",
"\n",
"To fix this issue, you can calculate the YTD gain using the `iloc` method to access the last and first rows of the DataFrame. Here's the corrected code:\n",
"\n",
"```python\n",
"import yfinance as yf\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Define the stock tickers\n",
"tickers = ['QCOM', 'TSLA']\n",
"\n",
"# Get the historical data for each stock\n",
"for ticker in tickers:\n",
" stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\n",
"\n",
" # Calculate the YTD gain\n",
" ytd_gain = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100\n",
"\n",
" # Print the YTD gain\n",
" print(f'{ticker}: {ytd_gain:.2f}%')\n",
"\n",
"# Create a figure and axis\n",
"fig, ax = plt.subplots()\n",
"\n",
"# Plot the YTD gains\n",
"for ticker in tickers:\n",
" stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\n",
" ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100, label=ticker)\n",
"\n",
"# Set the title and labels\n",
"ax.set_title('Year-to-Date Stock Gains')\n",
"ax.set_xlabel('Date')\n",
"ax.set_ylabel('Gain (%)')\n",
"ax.legend()\n",
"\n",
"# Save the figure to a file\n",
"plt.savefig('ytd_stock_gains.png')\n",
"\n",
"# Show the plot\n",
"plt.show()\n",
"```\n",
"\n",
"This code will correctly calculate the YTD gain and plot the gains for both QCOM and TSLA.\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",
"\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
"\n",
"exitcode: 1 (execution failed)\n",
"Code output: \n",
"[*********************100%***********************] 1 of 1 completed\n",
"Traceback (most recent call last):\n",
" File \"/Users/akshaypachaar/Eigen/crewai-qualcomm/coding/tmp_code_88a84a5084d5f7f0180305b840655af2.py\", line 15, in <module>\n",
" print(f'{ticker}: {ytd_gain:.2f}%')\n",
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
"TypeError: unsupported format string passed to Series.__format__\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
"\u001b[31m\n",
">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
"params : {'messages': [{'content': '', 'role': 'system'}, {'content': 'Today is 2024-11-18. Create a plot showing stock gain YTD over the whole year for (Qualcomm) QCOM and (Tesla) TSLA. Make sure the code is in python code block and save the figure to a file ytd_stock_gains.png.use the yfinance lib', 'role': 'user', 'name': 'code_executor_agent'}, {'content': \"Here is a Python code block that uses the yfinance library to retrieve the stock data for Qualcomm (QCOM) and Tesla (TSLA) and plots the year-to-date (YTD) stock gains:\\n```python\\nimport yfinance as yf\\nimport matplotlib.pyplot as plt\\n\\n# Define the stock tickers\\ntickers = ['QCOM', 'TSLA']\\n\\n# Get the historical data for each stock\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n\\n # Calculate the YTD gain\\n ytd_gain = (stock_data['Close'][-1] - stock_data['Close'][0]) / stock_data['Close'][0] * 100\\n\\n # Print the YTD gain\\n print(f'{ticker}: {ytd_gain:.2f}%')\\n\\n# Create a figure and axis\\nfig, ax = plt.subplots()\\n\\n# Plot the YTD gains\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'][0]) / stock_data['Close'][0] * 100, label=ticker)\\n\\n# Set the title and labels\\nax.set_title('Year-to-Date Stock Gains')\\nax.set_xlabel('Date')\\nax.set_ylabel('Gain (%)')\\nax.legend()\\n\\n# Save the figure to a file\\nplt.savefig('ytd_stock_gains.png')\\n\\n# Show the plot\\nplt.show()\\n```\\nThis code will create a line plot showing the YTD gains for both QCOM and TSLA, with the x-axis representing the date and the y-axis representing the gain percentage. The plot will be saved to a file named `ytd_stock_gains.png`.\\n\\nNote: Make sure you have the yfinance and matplotlib libraries installed by running `pip install yfinance matplotlib` in your terminal before running this code.\", 'tool_calls': [], 'role': 'assistant', 'name': 'code_writer_agent'}, {'content': 'exitcode: 1 (execution failed)\\nCode output: \\n[*********************100%***********************] 1 of 1 completed\\nTraceback (most recent call last):\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3805, in get_loc\\n return self._engine.get_loc(casted_key)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n File \"index.pyx\", line 167, in pandas._libs.index.IndexEngine.get_loc\\n File \"index.pyx\", line 196, in pandas._libs.index.IndexEngine.get_loc\\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item\\n File \"pandas/_libs/hashtable_class_helper.pxi\", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item\\nKeyError: -1\\n\\nThe above exception was the direct cause of the following exception:\\n\\nTraceback (most recent call last):\\n File \"/Users/akshaypachaar/Eigen/crewai-qualcomm/coding/tmp_code_f894a8bbf923d30a7d0fbc4d8b2f6b62.py\", line 12, in <module>\\n ytd_gain = (stock_data[\\'Close\\'][-1] - stock_data[\\'Close\\'][0]) / stock_data[\\'Close\\'][0] * 100\\n ~~~~~~~~~~~~~~~~~~~^^^^\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/frame.py\", line 4102, in __getitem__\\n indexer = self.columns.get_loc(key)\\n ^^^^^^^^^^^^^^^^^^^^^^^^^\\n File \"/Users/akshaypachaar/miniconda3/envs/env_crewai/lib/python3.11/site-packages/pandas/core/indexes/base.py\", line 3812, in get_loc\\n raise KeyError(key) from err\\nKeyError: -1\\n', 'role': 'user', 'name': 'code_executor_agent'}, {'content': \"The error occurs because the `stock_data` DataFrame does not have a column named `-1`. The `-1` is an index, not a column name.\\n\\nTo fix this issue, you can calculate the YTD gain using the `iloc` method to access the last and first rows of the DataFrame. Here's the corrected code:\\n\\n```python\\nimport yfinance as yf\\nimport matplotlib.pyplot as plt\\n\\n# Define the stock tickers\\ntickers = ['QCOM', 'TSLA']\\n\\n# Get the historical data for each stock\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n\\n # Calculate the YTD gain\\n ytd_gain = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100\\n\\n # Print the YTD gain\\n print(f'{ticker}: {ytd_gain:.2f}%')\\n\\n# Create a figure and axis\\nfig, ax = plt.subplots()\\n\\n# Plot the YTD gains\\nfor ticker in tickers:\\n stock_data = yf.download(ticker, start='2022-01-01', end='2024-11-18')\\n ax.plot(stock_data.index, (stock_data['Close'] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100, label=ticker)\\n\\n# Set the title and labels\\nax.set_title('Year-to-Date Stock Gains')\\nax.set_xlabel('Date')\\nax.set_ylabel('Gain (%)')\\nax.legend()\\n\\n# Save the figure to a file\\nplt.savefig('ytd_stock_gains.png')\\n\\n# Show the plot\\nplt.show()\\n```\\n\\nThis code will correctly calculate the YTD gain and plot the gains for both QCOM and TSLA.\", 'tool_calls': [], 'role': 'assistant', 'name': 'code_writer_agent'}, {'content': 'exitcode: 1 (execution failed)\\nCode output: \\n[*********************100%***********************] 1 of 1 completed\\nTraceback (most recent call last):\\n File \"/Users/akshaypachaar/Eigen/crewai-qualcomm/coding/tmp_code_88a84a5084d5f7f0180305b840655af2.py\", line 15, in <module>\\n print(f\\'{ticker}: {ytd_gain:.2f}%\\')\\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\nTypeError: unsupported format string passed to Series.__format__\\n', 'role': 'user', 'name': 'code_executor_agent'}], 'model': 'imaginechat', 'model_client_cls': 'CustomModelClient', 'n': 1, 'params': {'max_length': 1500, 'api_key': '38e48000-4d41-4a15-9cfb-e97056b06eb8', 'temperature': 0.0}}\n"
]
}
],
"source": [
"chat_result = code_executor_agent.initiate_chat(\n",
" code_writer_agent,\n",
" message=message,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "env_crewai",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 2
}