Stock technical analysis questions can be as unique as the individual stock analysts themselves. Queries often include multiple technical indicators, such as the Simple Moving Average (SMA), Exponential Moving Average (EMA), and Relative Strength Index (RSI). To answer these different questions, you need to break down the query into parts and write complex business logic to retrieve the required data. Due to the number of indicators available, the possibility of using one or more of them in any combination, and the existence of each of these indicators over different time periods, it is very difficult to incorporate such business logic into the code. can get complicated.
As AI technology continues to evolve, the capabilities of generative AI agents continue to expand, creating even more opportunities to gain a competitive edge. At the forefront of this evolution is Amazon Bedrock. Amazon Bedrock is a fully managed service that makes high-performance foundation models (FM) from Amazon and other leading AI companies available through a single API. Amazon Bedrock lets you build and scale generative AI applications with security, privacy, and responsible AI. Amazon Bedrock Agents use enterprise systems and data sources to plan and execute multi-step tasks, from answering customer questions about product availability to accepting orders. With Amazon Bedrock, you can create an agent in just a few steps by first selecting an FM and providing access to actions to securely run enterprise systems, knowledge bases, and APIs. These actions can be implemented in the cloud using AWS Lambda, or you can use local business logic to return control. The agent analyzes the user’s request and automatically calls the necessary APIs and data sources to fulfill the request. Amazon Bedrock Agents offer enhanced security and privacy. There’s no need to create prompts, manage session context, or manually coordinate tasks.
In this post, we will use Amazon Bedrock Agents to create a virtual analyst that can answer natural language queries for stocks that match specific technical indicator criteria. Configure an action group consisting of Lambda functions as part of your agent. This allows the agent to perform various actions. The Amazon Bedrock agent translates the user’s natural language queries into relevant Lambda calls, passing the technical metrics and their required time periods. Lambda accesses open source stock data prefetched into an Amazon Simple Storage Service (Amazon S3) bucket, calculates technical indicators in real time, and returns them to the agent. The agent performs further actions such as filtering and ordering based on other Lambda invocations and tasks.
Solution overview
Using Amazon Bedrock Agents, the Technical Analysis Assistant solution can be as simple as “Give me a list of stocks in the NASDAQ 100 index” or “Which stocks in the NASDAQ 100 index have both been ranked 10 in the past 6 months?” % and finished above the 20-day SMA?” The agent adjusts and analyzes the task, using FM’s reasoning power to break it down into the correct logical sequence. The agent automatically calls the necessary Lambda functions to retrieve the relevant stock technical analysis data and determines whether you can continue along the way or if you need to gather more information.
The following diagram shows the solution architecture.
The workflow consists of the following steps:
- This solution starts a Python-based Lambda function and
yfinance
package. The Lambda function is triggered to run daily using Amazon EventBridge. This function puts stock data from the past year into an S3 bucket. - Users can ask natural language queries such as “What is the list of stocks in the NASDAQ 100 index?” or “Which stocks in the FTSE 100 index closed above both the 20 SMA and 50 EMA?” I ask.
- This query is passed to the Amazon Bedrock agent powered by Anthropic’s Claude 3 Sonnet. The agent decomposes the user’s query, creates an action plan, and executes it step by step to obtain the various data needed to answer the question. To retrieve the required data, the agent has three action groups, each leveraging Lambda functions, that use the raw data stored in the S3 bucket to retrieve technical indicators and other stock-related information. can be calculated. Based on the response from the action group and the agent’s action plan, the agent continues making calls and performing other actions, such as filtering and summarizing, until it reaches the answer to the question. The action groups are:
- Get index – Get the stock symbols of the constituents of the specified index. This example currently has components configured for the Nasdaq 100, FTSE 100, and Nifty 50 indexes.
- Get inventory changes – Calculate the percentage change for a specific stock or list of stocks over a specific time period based on raw data previously retrieved in Amazon S3. This solution is currently configured to retain data for the past year.
- Obtain technical analysis – Calculate a specific technical indicator for a specific stock or list of stocks over a specific period of time. It also retrieves the last closing price of the stock based on the raw data previously retrieved in Amazon S3. The solution is currently configured to process SMA, EMA, and RSI technical indicators for up to one year.
Prerequisites
Setting up this solution requires basic knowledge of AWS and related AWS services. Additionally, request model access to Anthropic’s Claude 3 Sonnet on Amazon Bedrock.
Deploy the solution
To deploy your solution using AWS CloudFormation, follow these steps.
- Start the CloudFormation stack.
us-east-1
AWS Region:
- for stack nameenter the stack name of your choice.
- Leave the rest at default.
- choose Next.
- choose Next
- Check the confirmation checkbox and submit.
- Wait until the stack creation is complete.
- Verify that all resources are created on the stack details page.
The CloudFormation stack creates the solution and the following key resources described in the solution overview.
- Stock data S3 bucket – An S3 bucket to store one year of inventory data.
- YfinDailyLambda – Python Lambda functions are
yfinance
package:
- YfinDailyLambdaScheduleRule – EventBridge rule to trigger
YfinDailyLambda
Works daily to get the latest inventory data. - InvokeYfinDailyLambda and InvokeLambdaFunction – A custom CloudFormation resource and its Lambda function.
YfinDailyLambda
Serves as part of stack creation to fetch initial data. - GetIndexLambda – This function takes an index name as input and returns a list of stocks in the specified index.
- GetStockChangeLambda – This function takes a list of inventory and number of days as input, retrieves inventory data from an S3 bucket, calculates the percentage change in inventory over time, and returns the data.
- GetStockTechAnalysisLambda – This function takes as input a list of stocks, number of days, and technical indicators and returns the last closing price and technical indicators over the number of days for the specified list of stocks. for example:
- stock bot agent – The Amazon Bedrock agent is built with Anthropic’s Claude 3 Sonnet model and has three action groups, each mapped to a Lambda function. Give instructions to the agent in natural language. In our solution, the agent knows that it can retrieve the stocks in the index because part of the instructions include “You can retrieve the list of stocks in the specified index.” You configure action groups as part of your agent to describe your Lambda functions using the OpenAPI 3 schema standard, so the agent knows when and how to invoke your Lambda functions. Below is a snippet of the get-index action group OpenAPI schema that describes its functionality, input and output parameters, and format.
Test the solution
To test your solution, follow these steps:
- In the Amazon Bedrock console, agent in the navigation pane.
- Select the agent created by your CloudFormation stack.
- under testselect Name Alias version 1 and, test
You can now type your questions and interact with the agent.
- Let’s start with the query, “Please give me a list of stocks on Nasdaq.”
You can see the answer in the following screenshot. Expand. trace step Click the section in the right pane to see the agent rationale and Lambda function invocation.
- Now let’s ask a question that is likely to use all three action groups and their Lambda functions. “Please give me a list of stocks that have grown at least 10% over the past 6 months and closed above their 20-day SMA. Please use stocks from the Nasdaq index.”
You will get the response shown in the following screenshot. In the trace step, you can see that different Lambda functions are called at different steps as the agent infers the steps to get the answer to the question.
You can test further using additional prompts such as:
- Can you tell me the top 3 companies that have increased in percentage terms in the past 6 months in the Nifty 50 index?
- Which stocks closed above both the 20 SMA and 50 EMA of the FTSE 100 Index?
- Can you give me a list of stocks that have grown at least 10% over the past 6 months and closed above their 20-day SMA and 50-day EMA? Uses stocks from the FTSE 100 index. Follow-up question: Have any of these stocks grown more than 25% over the past few months? If so, can you tell me about them and their 6-month growth rate?
Call the agent programmatically
Once you are satisfied with the agent’s performance, you can use the InvokeAgent API to build an application that invokes the agent programmatically. The agent ID and agent alias ID required to programmatically call an agent alias are: output CloudFormation stack tabs (with titles) AgentId
and AgentAliasId
respectively. For more information about programmatic invocation, see the following Python and JavaScript examples.
cleaning
To avoid charges in your AWS account, clean up your solution’s provisioned resources.
- In the Amazon S3 console, empty the S3 bucket that was created as part of the CloudFormation stack. The bucket name must start with the stack name you entered when creating the CloudFormation stack. You can also check the name of the bucket in your CloudFormation stack. resource
- In the AWS CloudFormation console, select the stack you created for this solution and choose erase.
conclusion
In this post, you learned how to use Amazon Bedrock Agents to perform complex tasks that require orchestration of multiple steps using only natural language instructions. Agents allow you to automate tasks for your customers and answer their questions. We recommend that you refer to the Amazon Bedrock Agents User Guide to further understand its features and use it for your use case.
About the author
Bharath Shridharan is a Senior Technical Account Manager at AWS and works with AWS strategic customers to proactively optimize their workloads on AWS. Bharath also specializes in AWS machine learning services with a focus on Generative AI.