Skip to content

Coding

Coding and Financial AnalysisΒΆ

In this example, we will set up a workflow for retrieving and plotting stock prices over a specified period. The workflow includes agents for data retrieval, data plotting, and message handling.

Example 5 overview Example 5 overview

OverviewΒΆ

The flow includes:

  • Code Executor Agent: Executes the code for retrieving and plotting stock prices.
  • Code Writer Agent: Writes the code for retrieving and plotting stock prices.
  • Get Stock Prices Skill: Fetches stock prices using yfinance.
  • Plot Stock Prices Skill: Plots the stock prices using matplotlib.

Agents and skillsΒΆ

SkillsΒΆ

  1. Get Stock Prices

    • Description: Get the stock prices for the given stock symbols between the start and end dates.
    • Inputs: stock_symbols (str or list), start_date (str in YYYY-MM-DD), end_date (str in YYYY-MM-DD).

    Content:

     # filename: {get_stock_prices}.py
     """Get stock prices.
    
     Get the stock prices for the given stock symbols between  
     the start and end dates.
     """
    
    
     def get_stock_prices(
         stock_symbols: str | list,
         start_date: str,
         end_date: str,
     ):
         """Get the stock prices for the given stock symbols between
         the start and end dates.
    
         Args:
             stock_symbols (str or list): The stock symbols to get the
             prices for.
             start_date (str): The start date in the format 
             'YYYY-MM-DD'.
             end_date (str): The end date in the format 'YYYY-MM-DD'.
    
         Returns:
             dict: (pandas.DataFrame.to_dict): The stock prices for the given stock
             symbols indexed by date, with one column per stock 
             symbol.
         """
         # pylint: disable=import-outside-toplevel
         import yfinance
    
         stock_data = yfinance.download(
             stock_symbols, start=start_date, end=end_date
         )
         return stock_data.get("Close")
         #
         # We might get:
         # Timestamp is not JSON serializable
         # we can return a dictionary instead:
         #
         # close = stock_data.get("Close")
         # close.index = close.index.date  # Convert the index to date only
         # close.index = close.index.astype(str)  # Convert the index to string
         # return close.to_dict()
    
    • Save the skill.
  2. Skill: Plot Stock Prices

    • Description: Plot the stock prices for the given stock symbols.

    Example Code:

    ```python # filename: {plot_stock_prices}.py """Plot the stock prices for the given stock symbols."""

    def plot_stock_prices( stock_prices: dict, filename: str, ): """Plot the stock prices for the given stock symbols.

      Args:
          stock_prices (dict) [dumped pandas.DataFrame]: The stock 
              prices for the given stock symbols.
          filename (str): The filename to save the plot to.
    
      Returns:
          str: "ok" if the plot was saved successfully.
      """
      # pylint: disable=import-outside-toplevel
      import matplotlib.pyplot as plt
      import pandas as pd
    
      if isinstance(stock_prices, dict):
          df = pd.DataFrame.from_dict(stock_prices)
      else:
          df = stock_prices
      plt.figure(figsize=(10, 5))
      for column in df.columns:
          plt.plot(df.index, df[column], label=column)
      plt.title("Stock Prices")
      plt.xlabel("Date")
      plt.ylabel("Price")
      plt.grid(True)
      # if the days are a lot in the plot, get the xticks every 5 days
      # plt.xticks(df.index[::5], rotation=45)
      # give a little space to the plot
      # or don't use xticks at all
      # plt.xticks([])
      plt.tight_layout()
      # save the plot
      plt.savefig(filename)
      return "ok"
    

    ```

    • Save the skill.

AgentsΒΆ

Code Writer AgentΒΆ

  1. Models Link a model of your choice to the Code Writer Agent. In our example, we use the gpt-4-turbo model.
  2. Skills In the skills tab, add the get_stock_prices and plot_stock_prices skills to the Code Writer Agent. As executor, select the Code Executor Agent. Agent skills registration Agent skills registration

Code Executor AgentΒΆ

In this step, we'll configure a Code Executor Agent to handle the execution of the functions required for retrieving and plotting stock data.

  1. Basic configuration

    • Max consecutive auto replies: Let's limit the number of auto-replies to 10 to avoid unnecessary repetition.
    • Agent Default auto-reply: We can set the default auto-reply to `Please continue. If everything is done, reply 'TERMINATE', to avoid repeating the same message when asked.
  2. Code Execution

    • At the Code Execution tab, check the box for Use Code Execution.
    • Set the Working Directory to coding (or your designated project folder).
    • Set the Timeout slider to 60 seconds to allow enough time for the code to fetch and plot data without interruption.
    • Under Functions, add the get_stock_prices and plot_stock_prices functions to allow the Code Executor Agent to access and execute these methods.

      Code Execution Code Execution

Flow chats and requirementsΒΆ

  1. Edit Flow: Set up the flow order to start with the "Code Executor Agent => Code Writer" connection.
  2. Additional requirements: Add the libraries we have used (yfinance, matplotlib, pandas) in our skills to the flow requirements. Additional requirements Additional requirements

Run the flowΒΆ

Press the Run button to execute the flow. When asked, you can press Enter to use the Agents auto-reply message. When you get a message about having the plot generated, you can enter TERMINATE (or exit) to end the flow.

Ending the flow Ending the flow

You can view the generated code and plot in the specified code execution folder.

Final PLot Final Plot


Files used in this example:

Note

The outputs may vary based on the model, skills and message you use. Feel free to customize the skills and messages to suit your requirements