Blog / Finance / Using Claude Code for Stock Analysis and Portfolio Management
Finance

Using Claude Code for Stock Analysis and Portfolio Management

Published: March 17, 2026
Read time: 11 min read
By: Claude Skills 360

Financial analysis used to be a specialized skill requiring expensive Bloomberg terminals and years of training. Today, Claude Code can handle the analysis faster and often more objectively than human analysts.

The opportunity: build a personal financial analyst agent that monitors markets, analyzes trends, calculates risk metrics, and recommends portfolio adjustments — all without the $24,000/year Bloomberg subscription.

What a Financial Analysis Agent Can Do

Real-Time Analysis

  • Stock fundamental analysis (earnings, growth, valuation)
  • Technical indicator calculation (RSI, MACD, moving averages)
  • Sector and industry comparison
  • Competitor benchmarking
  • Earnings call sentiment analysis

Portfolio Management

  • Portfolio composition analysis
  • Asset allocation optimization
  • Correlation analysis (stocks that move together)
  • Risk metrics (Sharpe ratio, Sortino ratio, Value at Risk)
  • Dividend tracking and tax implications

Opportunity Identification

  • Stocks breaking above support/resistance
  • Earnings surprises (positive or negative)
  • Insider trading analysis
  • M&A rumors and implications
  • Sector rotation signals

Risk Management

  • Downside protection analysis
  • Portfolio stress testing (what if markets drop 20%?)
  • Concentration risk (overexposure to single stocks)
  • Correlation breakdown (when hedges fail)
  • Black swan preparation

Setting Up Your Financial Analyst Agent

Step 1: Connect to Financial Data Sources

Claude Code integrates with multiple financial data providers:

{
  "mcpServers": {
    "yahoo-finance": {
      "command": "uvx",
      "args": ["stockquotes-mcp"]
    },
    "alphaVantage": {
      "command": "uvx",
      "args": ["av-mcp"],
      "env": {
        "ALPHA_VANTAGE_API_KEY": "your_key"
      }
    },
    "eodhd": {
      "command": "uvx",
      "args": ["eodhd-mcp"],
      "env": {
        "EODHD_API_KEY": "your_key"
      }
    }
  }
}

Data available:

  • Real-time quotes: Stock prices, volume, bid/ask spreads
  • Historical data: Daily prices for technical analysis
  • Fundamentals: P/E, dividend yield, earnings growth, ROE
  • Technical indicators: 80+ indicators (RSI, MACD, Bollinger Bands, etc.)
  • News: Sentiment and major announcements

Step 2: Create Your Analysis Profile

# Financial Analysis Profile

## Portfolio
- Account value: $100,000
- Investment horizon: 10 years
- Risk tolerance: Moderate (willing to lose 25% in bad year)
- Goals:
  - Primary: Retirement in 30 years
  - Secondary: Generate income
  - Tertiary: Beat S&P 500 by 3% annually

## Current Holdings
- 50% SPY (S&P 500 ETF)
- 25% QQQ (Nasdaq ETF)
- 15% BND (Bond ETF)
- 10% Individual stocks (AAPL, MSFT, GOOGL)

## Constraints
- No day trading (long-term only)
- Maximum 20% in any single stock
- Minimum 30-day hold period
- No margin or leverage
- No cryptocurrencies

## Analysis Focus
- Focus on value stocks (P/E < 20, strong fundamentals)
- Sector allocation insights
- Quarterly rebalancing
- Dividend income optimization
- Tax-loss harvesting opportunities

## Alerts
Notify if:
- Any position drops 20% from entry
- Market volatility spikes (VIX > 30)
- Earnings surprise (>20% move)
- Insider buying in holdings

Step 3: Invoke the Financial Analyst Agent

/financial-analyst-agent

Daily market analysis:
1. Get current market sentiment (VIX, Put/Call ratio)
2. Analyze my portfolio (current allocation vs target)
3. Check for alerts (earnings surprises, insider trading)
4. Identify top 3 opportunities today
5. Calculate current risk metrics
6. Suggest actions (if any)

Use my financial profile for context.
Report format: [Executive summary] → [Analysis] → [Recommendations]

Claude’s financial analyst agent now runs daily, monitoring your portfolio and markets.

Real-World Examples

Example 1: Quarterly Rebalancing Analysis

Analyze my portfolio for Q1 rebalancing:

Current allocation:
- 50% SPY (S&P 500)
- 25% QQQ (Nasdaq)
- 15% BND (Bonds)
- 10% Individual stocks

Target allocation:
- 50% Large-cap US
- 25% Tech/Growth
- 15% Fixed Income
- 10% Individual

Provide:
1. Drift from target (how much has allocation changed?)
2. Realized gains (if I rebalance now, what are taxes?)
3. Optimal rebalancing trades (minimize tax impact)
4. Market implications (why is allocation drifting?)

Claude calculates the rebalancing trades and tax implications.

Output:

Current allocation drift from target:
- SPY: 48% (target 50%) = 2% underweight
- QQQ: 27% (target 25%) = 2% overweight
- BND: 15% (target 15%) = On target
- Individual: 10% (target 10%) = On target

Recommended trades:
1. Sell 0.5 shares QQQ (~$200) → Realized gain: $45 (tax = $7)
2. Buy 0.3 shares SPY (~$200)

Result: Allocation rebalanced, tax impact: $7
Wait 40 days before selling other QQQ to harvest losses if QQQ drops

Example 2: Technical Analysis for Entry/Exit

I'm considering buying MSFT.

Analyze:
1. Current valuation (P/E, PEG ratio)
2. Technical setup (moving averages, support/resistance)
3. Sentiment (insider buying/selling, analyst ratings)
4. Risk/reward (downside if thesis breaks, upside if it works)
5. Entry point recommendation
6. Stop-loss level
7. Profit target

Current price: $420
Entry target: $400-410
Stop loss: $380 (5% risk)
Profit target: $450-480 (5-14% upside)
Risk/reward: 1:1 to 1:2.8 (favorable)

Claude provides a complete trade setup including entry, stop-loss, and profit targets.

Example 3: Portfolio Risk Analysis

Stress-test my portfolio:

Scenarios:
1. Market drops 20% (like 2022)
2. Tech sector drops 30% (concentration risk)
3. Bonds drop 10% (rising interest rates)
4. Recession (earnings down 40%)

For each scenario, calculate:
- Portfolio impact ($)
- Portfolio impact (%)
- Which holdings hurt most
- What would protect me
- Recommended hedge

Current portfolio value: $100,000
Scenario 1 impact: -$12,000 (12% loss)
  → Downside mostly from QQQ (27% holdings)
  → Bond position (15%) partially hedges
Scenario 2 impact: -$18,000 (18% loss)
  → Tech-heavy portfolio (77% in SPY+QQQ+MSFT+AAPL)
  → Need more diversification

Recommendation: Increase bond allocation to 20% or add defensive stocks

Claude identifies concentration risk and recommends hedges.

Example 4: Earnings Analysis

AAPL earnings in 3 days.

Analyze:
1. Current expectations (consensus estimate)
2. Historical surprises (does AAPL beat or miss?)
3. Implied move (how much will stock move?)
4. Options setup (which scenarios are profitable?)
5. My position (100 shares)

Consensus EPS: $1.99
Historical beat rate: 85% (usually beats)
Options implied move: +/- 4%

Scenarios:
- Beat by 5%: Stock could jump 6-8% → +$840-1120 gain
- Miss by 5%: Stock could drop 6-8% → -$840-1120 loss
- In line: Stock moves 1-2% → -$140-280 or +$140-280

Trade recommendation:
- If bullish on earnings: Hold (upside likely)
- If cautious: Sell covered call (capture upside, get paid)
- If concerned: Buy put option ($5 cost, protects downside)

My recommendation: Your historical beats suggest holding.

Building Your Own Analysis System

Phase 1: Daily Monitoring

# Create a daily analyst script
# daily-portfolio-check.mjs

import { Anthropic } from "@anthropic-ai/sdk";

const client = new Anthropic();

async function dailyAnalysis() {
  const message = await client.messages.create({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 2048,
    messages: [
      {
        role: "user",
        content: `Daily portfolio analysis:
1. Get stock prices for: AAPL, MSFT, GOOGL, AMZN, NVDA
2. Compare vs yesterday (up/down)
3. Check if any hit stop-loss or take-profit
4. Analyze market sentiment (VIX, put/call ratio)
5. List top 3 opportunities today
6. Alert on any major news/earnings

Format as: Summary → Analysis → Action items`,
      },
    ],
  });

  // Email the report
  console.log(message.content[0].text);
}

dailyAnalysis();

Run daily via cron:

0 16 * * * node daily-portfolio-check.mjs | mail -s "Daily Analysis" you@email.com

Phase 2: Quarterly Reviews

// quarterly-review.mjs
const quarterlyAnalysis = {
  "Q1": {
    startDate: "2026-01-01",
    endDate: "2026-03-31",
    analysis: [
      "Portfolio returns vs S&P 500",
      "Best/worst performers",
      "Realized gains and losses",
      "Rebalancing needed?",
      "Tax-loss harvesting opportunities",
      "Allocation vs target",
      "Risk metrics (Sharpe, Sortino)",
      "What worked / what didn't"
    ]
  }
};

Phase 3: Annual Planning

# Annual Financial Review

## 2025 Performance
- Portfolio return: 18%
- S&P 500 return: 24%
- Underperformance: -6%

## Analysis
- Tech overweight (QQQ down 12%) caused underperformance
- Individual stocks beat (MSFT +35%, NVDA +28%)
- Bonds were a drag in rising-rate environment

## 2026 Adjustments
1. Reduce tech concentration (QQQ 25% → 20%)
2. Increase value/dividend stocks
3. Add emerging markets exposure (5%)
4. Bonds: Shift to shorter duration

## 2026 Goals
- Beat S&P 500 by 3%
- Reduce portfolio volatility 10%
- $150K net worth by year-end
- Dividend income: $3,000/year

Technical Indicators to Track

Claude can calculate any indicator, but here are the most useful:

Trend Following

  • Moving Averages (SMA/EMA): Follow long-term trend
  • MACD: Momentum and trend changes
  • ADX: Trend strength (is it real?)

Mean Reversion

  • RSI: Overbought (>70) / Oversold (<30)
  • Bollinger Bands: Extremes tend to reverse
  • Stochastic: Momentum oscillator

Volatility

  • ATR: Average True Range (how volatile?)
  • Bollinger Bandwidth: Volatility compression
  • VIX: Market-wide fear index

Volume

  • Volume trend: Increasing/decreasing
  • OBV: On-Balance Volume
  • VWAP: Volume-Weighted Average Price

Example Claude prompt:

Calculate these indicators for SPY:
- 50-day and 200-day moving average
- RSI (14-day)
- MACD (12, 26, 9)
- Bollinger Bands (20-day)
- ATR (14-day)

Compare current values to historical ranges. Is SPY overbought/oversold?
What does this suggest about near-term direction?

Risk Metrics to Monitor

Sharpe Ratio

(Return - Risk-free Rate) / Standard Deviation Higher is better (indicates return per unit of risk)

Sortino Ratio

(Return - Risk-free Rate) / Downside Deviation Like Sharpe, but only counts downside risk (bad volatility)

Maximum Drawdown

Largest peak-to-trough decline Important: Shows worst-case scenario

Beta

How much does your portfolio move with the market?

  • Beta 1.0 = moves with market
  • Beta 1.5 = 50% more volatile than market
  • Beta 0.5 = 50% less volatile than market

Correlation

How much do your holdings move together?

  • Correlation 1.0 = perfectly together (no diversification)
  • Correlation 0.0 = independent (good diversification)

Example:

Calculate risk metrics for my portfolio:
- Sharpe ratio (vs S&P 500)
- Maximum drawdown
- Beta to S&P 500
- Correlation between holdings
- Value at Risk (VaR) at 95% confidence

Interpretation: What do these metrics tell me?
Compare to target profile: "Moderate risk, long-term"

Backtesting Your Strategy

Before deploying real money to a strategy, test it on historical data:

I'm considering a momentum strategy:
- Buy when RSI > 60 and price > 200-day MA
- Sell when RSI < 40 or price < 200-day MA

Backtest this on SPY from 2015-2024:
1. Calculate entries and exits
2. Calculate returns
3. Calculate max drawdown
4. Calculate Sharpe ratio
5. Compare to buy-and-hold

Result: Did the strategy beat the market?
When did it fail? (2020? 2022?)
What would make it better?

Claude can backtest trading strategies on historical data.

Avoiding Emotional Mistakes

One benefit of an AI analyst: it’s unemotional. It follows rules. The agent will:

  • Rebalance on schedule (not when “feeling lucky”)
  • Take profits at predetermined levels (not holding for more)
  • Cut losses at stop-loss (not hoping for reversal)
  • Diversify (not going all-in on one idea)
  • Stay disciplined (not FOMO-ing into hot stocks)

Set your rules. Let the agent follow them. Emotions are your biggest enemy in investing.

Regulatory Note

This guide is for educational purposes. Not financial advice. Always:

  • Do your own research
  • Understand what you’re buying
  • Only invest money you can afford to lose
  • Consult a financial advisor for large decisions
  • Keep detailed records for taxes

Conclusion

Claude Code transforms financial analysis from a specialized skill to something any investor can do. You now have a 24/7 analyst that monitors markets, identifies opportunities, and manages risk.

Start simple:

  1. Week 1: Set up daily price monitoring
  2. Week 2: Add technical indicators
  3. Week 3: Add fundamental analysis
  4. Week 4: Automate quarterly rebalancing
  5. Month 2+: Add more complex strategies

Your edge isn’t beating professional traders (you probably won’t). Your edge is:

  • Discipline (following your rules)
  • Speed (reacting to opportunities fast)
  • Data (having all information instantly)
  • Emotion control (letting AI decide, not gut feelings)

Build your analyst. Let it work. Review and adjust quarterly. Over 10+ years, the compound effect is massive.

Ready to build with Claude Code?

Explore Claude Skills 360. 2,350+ professional skills, 45+ autonomous agents, and 12 business swarms. Start building today.

Back to Blog