Building a stock-trading agent with ADK
Copy as MarkdownThe Agent Development Kit (ADK) is Google’s open-source Python framework for building AI agents. You write the agent’s logic and the tools it can call, and ADK handles orchestrating everything — with evaluation and deployment built in too.
I wanted a slightly more interesting app than Hello World to exercise more parts of the platform, so I figured I’d write a little stock trading agent that applies a sentiment momentum trading strategy. We’ll use ADK and the Gemini API to execute trades on Alpaca, chosen for its REST API and free paper-trading account.
Tip: Prefer a fully-built solution? See the completed example.
First, let’s set up our project directory and create a subfolder for our agent:
mkdir trading-agent-project
cd trading-agent-project
mkdir trading_agent
Get an API key from Alpaca’s “API Keys” box on the account overview page.
The Alpaca API key box
And a Google API key from AI Studio.
Create a .env file at trading_agent/.env and populate it with your 3 keys:
# Google AI Studio / Vertex AI Key for the ADK Agent
GOOGLE_API_KEY=your-key
# Alpaca Paper Trading Keys
APCA_API_KEY_ID=your-key-id
APCA_API_SECRET_KEY=your-key
Note: I use this trading agent with paper trades only. It’s likely a terrible trading strategy, and also poorly executed, so I do not endorse it. If you build your own agent based on this prompt, I strongly advise you not to switch the API keys from paper trades to money trades. It makes for a fun demo though.
Next, create a file at trading_agent/requirements.txt to manage our dependencies, and add the following:
google-adk
alpaca-py
google-cloud-aiplatform[agent_engines,adk]
python-dotenv
We’ll need a Python environment with the dependencies installed, which we can use venv to manage. Install venv if not already installed (apt update && apt install python3-venv, or sudo apt update && sudo apt install python3-venv depending on your permissions).
Create the venv environment:
python3 -m venv trading-env
source trading-env/bin/activate
pip install -r trading_agent/requirements.txt
Now, we can use the Gemini CLI (or your preferred coding agent) to generate the ADK agent. Here’s my prompt:
You are operating from within a venv project folder. Create an AI agent using ADK in python in the sub-folder "trading_agent". It already contains a .env with the required keys. The agent will be executed with `adk run trading_agent`.
The agent is a stock trading bot that will use Alpaca with paper trades (not real money). Each execution, it performs the following actions:
1/ News lookup. Discover the latest financial news affecting companies, primarily the S&P 500
2/ Analyze the news for positive or negative sentiments using Gemini 2.5 Pro and assign a sentiment rating between -1 and 1. Ignore Stock Analyst Rating changes; market news only. Format as Primary ticker affected, news summary, score.
3/ Query current position portfolio from Alpaca markets
4/ For any stock currently held, if the sentiment is negative, sell the stock. If no negative sentiment, do not sell. For all trades, introduce a 1s delay to rate-limit API calls.
5/ Rank the news in order of positivity, and create market BUY trades for $1000 worth of EACH of up to 5 stock with high confidence positive sentiments NOT currently held (fractional shares are OK). If no positive sentiments, do not buy.
6/ Produce a summary of all orders placed with a summary of the news that led to the order, along with a sentiment score. Additionally, provide a market sentiment overview of the top 10 positive, and top 10 negative news stories (include the ticker, summary, and score).
Note: If you run out of Gemini CLI quota, you can use the same API key in the .env file above to authenticate the Gemini CLI (run /auth in Gemini, and enter the key).
It’s best to let Gemini run the agent the first time to iron out any bugs. Just be aware that however it runs, the trades are executing.
Here’s the Python agent code that I got from the Gemini CLI:
To run the agent locally, from the project folder (with the venv environment active, if you need: source trading-env/bin/activate):
adk run trading_agent
You’ll need to prompt it like “go” to kick off the analysis. ADK agents can be quiet while they “think”. To get some feedback, tail the logs and watch the tool-calling in real time:
tail -F /tmp/agents_log/agent.latest.log
As requested, it made 5 paper trades on my account that will execute on open.
And here’s the summary (from 2026-04-21):
[TradingAgent]: ## FINAL REPORT
### SUMMARY OF ORDERS
| Ticker | Action | Sentiment Score | News Summary |
|---|---|---|---|
| ADBE | BUY | 0.9 | Adobe announced a large $25 billion stock buyback plan. |
| UNH | BUY | 0.9 | UnitedHealth reported a strong Q1 beat and raised its profit outlook, causing the stock to jump. |
| GTLB | BUY | 0.8 | GitLab shares are rising after announcing a collaboration with Amazon Web Services. |
| ISRG | BUY | 0.8 | Intuitive Surgical reported a strong Q1 with a double beat on earnings and revenue. |
| IBM | BUY | 0.7 | Positive preview for IBM's Q1 earnings, with expectations of a sixth consecutive double beat, driven by AI momentum. |
### MARKET SENTIMENT OVERVIEW
#### Top 10 Positive Stories
| Ticker | Summary | Score |
|---|---|---|
| ADBE | Adobe Announces $25B Buyback Plan Through April 2030 | 0.9 |
| UNH | UnitedHealth Stock Jumps After Q1 Beat — Here's What Execs Say Drove It | 0.9 |
| GTLB | GitLab Stock Jumps After The Close: Here's Why | 0.8 |
| ISRG | Intuitive Surgical Delivers Q1 Double Beat: ISRG Earnings Highlights | 0.8 |
| IBM | IBM Q1 Preview: Dow Giant Goes For Six Straight Double Beats As AI Momentum Builds | 0.7 |
| CB | Chubb Q1 Adj. EPS $6.82 Beats $6.60 Estimate, Sales $11.716B Beat $11.687B Estimate | 0.7 |
| TMUS | UPDATE: 'Deutsche Telekom Weighs Full Combination With T-Mobile' - Bloomberg | 0.7 |
| BA | 'Boeing 737 Max 7, 10 Models on Track for 2026 Certification, FAA Says'- Bloomberg | 0.6 |
| COIN | Kalshi, Polymarket Announce Plans To Launch Crypto Perpetual Futures: Report | 0.6 |
| META | Meta Platforms Breaking Ground On $1B First Data Center In Oklahoma | 0.6 |
#### Top 10 Negative Stories
| Ticker | Summary | Score |
|---|---|---|
| COIN | New York Attorney General Sues Coinbase Over Prediction Markets: COIN Slides 6% | -0.9 |
| UAL | United Airlines Holdings Lowers FY2026 Adj EPS Guidance from $12.00-$14.00 to $7.00-$11.00 vs $9.96 Est | -0.9 |
| COF | Capital One Misses Q1 Estimates — Stock Drops | -0.8 |
| PRU | 'Prudential's Japan operations suspected of fraud at Gibraltar Life unit'- Nikkei Asia | -0.8 |
| GM | 'GM suspends next-gen electric trucks amid pivot back to gas engines, hybrids'- Crain's Detroit Business | -0.7 |
| TSLA | Tesla California Sales Fall 24% In Q1 Despite Model Y Leading EV Sales | -0.7 |
| UAL | United Airlines Stock Slips As Softer 2026 Outlook Overshadows Q1 Earnings Beat | -0.7 |
| BX | Blackstone's Private Credit Fund Slashes Value Of ACI Group Holdings | -0.6 |
| COF | Capital One Financial Reveals March Domestic Credit Card Net Charge-Off Rate 5.09% | -0.5 |
| DHI | America's Largest Homebuilder D.R. Horton Says Affordability Is Hitting Housing Demand | -0.5 |
I built this after-hours, and the trades executed at open. Here’s where I stand at 1pm:

Alpaca allows for 3 paper trading accounts, so to “reset” you simply create a new account with the desired paper balance, get the new API keys and update your .env (after which you can delete the old paper account).
Next up, we can deploy this agent to the cloud on Agent Platform.
The completed example
Here’s the fully built example of the trading agent, ready to clone & run:
1. Clone the repo:
git clone https://github.com/WilliamDenniss/agent-examples.git
cd agent-examples/01_TradingAgent
2. Sign up for a free Alpaca paper trading account and grab a Google AI Studio key, then put both in a trading_agent/.env file:
# Google AI Studio / Vertex AI Key for the ADK Agent
GOOGLE_API_KEY=your-key
# Alpaca Paper Trading Keys
APCA_API_KEY_ID=your-key-id
APCA_API_SECRET_KEY=your-key
Caution: Paper trades only—don’t point it at a real-money account!
3. Set up a venv and install the deps:
python3 -m venv trading-env
source trading-env/bin/activate
pip install -r trading_agent/requirements.txt
4. Run the agent:
adk run trading_agent
5. Enter “go” or “trade” to kick it off.
6. To deploy to Agent Platform runtime, run:
python deploy.py
View in the UI playground to kick off a remote trading session, or set the RESOURCE_NAME
environment variable, and trade via the CLI:
export RESOURCE_NAME=projects/.../locations/us-west1/reasoningEngines/...
./trade.sh
See interacting with agent for how to trade with the deployed agent.