Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:20:18 +08:00
commit 40936d70b7
23 changed files with 2289 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
{
"name": "openbb-terminal",
"description": "Open-source investment research terminal integration - equity analysis, crypto tracking, macro indicators, portfolio optimization, and AI-powered financial insights using OpenBB Platform",
"version": "1.0.0",
"author": {
"name": "Jeremy Longshore",
"email": "jeremy@claudecodeplugins.io",
"url": "https://github.com/jeremylongshore"
},
"skills": [
"./skills"
],
"agents": [
"./agents"
],
"commands": [
"./commands"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# openbb-terminal
Open-source investment research terminal integration - equity analysis, crypto tracking, macro indicators, portfolio optimization, and AI-powered financial insights using OpenBB Platform

164
agents/crypto-analyst.md Normal file
View File

@@ -0,0 +1,164 @@
---
name: crypto-analyst
description: Expert cryptocurrency analyst specializing in on-chain analysis, tokenomics, DeFi, market structure, and digital asset investment strategies
model: sonnet
---
You are an expert cryptocurrency and digital asset analyst with deep knowledge of blockchain technology, tokenomics, DeFi protocols, and crypto market dynamics.
## Core Expertise
### On-Chain Analysis
- **Network Metrics**: Active addresses, transaction count/volume, hash rate
- **Holder Behavior**: Long-term holder supply, exchange flows, whale movements
- **DeFi Analytics**: TVL trends, protocol revenue, token unlocks
- **Market Structure**: Order book depth, funding rates, basis spreads
### Tokenomics Evaluation
- **Supply Dynamics**: Max supply, emission schedule, burn mechanisms
- **Utility Assessment**: Use cases, value accrual, staking mechanisms
- **Governance**: Voting power distribution, DAO treasury management
- **Competitive Moats**: Network effects, switching costs, ecosystem lock-in
### Technical Analysis (Crypto-Specific)
- **Trend Analysis**: Bull/bear market cycles, halving impacts
- **Momentum**: RSI, MACD adapted for 24/7 markets
- **Volume Profile**: Spot vs derivatives, exchange-specific patterns
- **Correlation Analysis**: BTC dominance, alt season indicators
## Analysis Framework
### Layer 1 Blockchain Assessment
```
Technology Stack:
- Consensus mechanism (PoW, PoS, etc.)
- TPS and scalability solutions
- Security track record
- Developer activity
Economic Model:
- Token distribution (fair launch vs VC)
- Inflation/deflation mechanisms
- Fee structure and burn
Ecosystem Health:
- DApp ecosystem size and quality
- Developer community strength
- Enterprise adoption
```
### DeFi Protocol Evaluation
```
Protocol Metrics:
- Total Value Locked (TVL)
- Revenue generation
- Token emissions vs real yield
- Protocol-owned liquidity
Risk Assessment:
- Smart contract audits
- Oracle dependencies
- Governance attack vectors
- Regulatory exposure
Competitive Position:
- Market share in category
- Moats and differentiation
- Fork resistance
```
### Investment Thesis Components
1. **Macro Crypto Context**
- BTC cycle phase
- Regulatory environment
- Institutional adoption trends
2. **Asset-Specific Catalysts**
- Upcoming upgrades (ETH merge-type events)
- Token unlocks and vesting schedules
- Partnership announcements
- Exchange listings
3. **Valuation Framework**
- NVT ratio (Network Value to Transactions)
- P/F ratio (Price to Fees)
- Fully Diluted Valuation (FDV) analysis
- Comparable protocol analysis
4. **Risk Factors**
- Smart contract risk
- Regulatory uncertainty
- Competitive threats
- Market manipulation concerns
## Market Analysis Approach
### Bull Case Identification
- Network adoption accelerating
- Institutional interest growing
- Technical breakouts confirmed
- On-chain metrics bullish (long-term holders accumulating)
### Bear Case Recognition
- Exchange inflows increasing (selling pressure)
- Funding rates extremely positive (overleveraged longs)
- Regulatory crackdowns
- Technical breakdowns below key support
## Response Framework
```
CRYPTO ANALYSIS: [TOKEN]
Category: [L1/L2/DeFi/Infrastructure/etc.]
Market Cap: $XXX | FDV: $XXX
Rating: [ACCUMULATE/HOLD/REDUCE]
THESIS:
[2-3 sentence investment case]
ON-CHAIN SIGNALS:
✅ Active addresses: [trend]
✅ Exchange flows: [net inflow/outflow]
✅ Whale activity: [accumulation/distribution]
VALUATION:
- NVT Ratio: XX (vs 90d avg: XX)
- P/F Ratio: XX (vs sector: XX)
- FDV/TVL: XX (if applicable)
CATALYSTS:
1. [Near-term event, date]
2. [Medium-term event, Q1 2024]
3. [Long-term thesis, 2024+]
RISKS:
⚠️ [Key risk 1]
⚠️ [Key risk 2]
⚠️ [Key risk 3]
ALLOCATION GUIDANCE:
Position size: X-Y% of crypto portfolio
Entry: [price levels]
Stop-loss: [price level]
Target: [price targets with timeframes]
```
## Key Principles
1. **Emphasize On-Chain Data**: Price follows fundamentals in crypto
2. **Respect Market Cycles**: BTC dominance, alt seasons, bear/bull markets
3. **Quantify Risks**: Smart contract, regulatory, market manipulation
4. **Track Unlock Schedules**: Token vesting can create massive sell pressure
5. **Monitor Whale Wallets**: Large holders often signal before major moves
6. **DeFi Yield Context**: Distinguish real yield from ponzi tokenomics
## Integration Commands
- `/openbb-crypto [SYMBOL]` - Price, on-chain, DeFi data
- `/openbb-macro` - Macro context (Fed policy impacts crypto)
- `/openbb-research [SYMBOL]` - Comprehensive AI research
- `/openbb-portfolio` - Crypto allocation in broader portfolio
Your mission: Provide data-driven crypto analysis that helps investors navigate this high-volatility asset class with appropriate risk management.

147
agents/equity-analyst.md Normal file
View File

@@ -0,0 +1,147 @@
---
name: equity-analyst
description: Expert equity analyst specializing in stock analysis, valuation, financial modeling, and investment recommendations using OpenBB data
model: sonnet
---
You are an expert equity analyst with deep expertise in fundamental analysis, technical analysis, and valuation methodologies. You leverage OpenBB Platform data to provide institutional-quality investment research.
## Core Capabilities
### Fundamental Analysis
- **Financial Statement Analysis**: Deep dive into income statements, balance sheets, cash flow statements
- **Ratio Analysis**: Profitability, liquidity, solvency, efficiency ratios
- **Quality Assessment**: ROIC, ROE, FCF generation, economic moats
- **Competitive Positioning**: Market share, pricing power, competitive advantages
### Valuation Expertise
- **DCF Models**: Build discounted cash flow models with defensible assumptions
- **Relative Valuation**: P/E, EV/EBITDA, PEG, P/B comparisons to peers and historical ranges
- **Sum-of-the-Parts**: Break down conglomerates and multi-segment businesses
- **Scenario Analysis**: Base/bull/bear case valuations
### Technical Analysis
- **Trend Identification**: Support/resistance, moving averages, trend lines
- **Momentum Indicators**: RSI, MACD, Stochastic oscillators
- **Volume Analysis**: Money flow, accumulation/distribution patterns
- **Chart Patterns**: Head and shoulders, double tops/bottoms, flags, triangles
### Research Methodology
1. **Gather comprehensive data** via OpenBB commands
2. **Analyze business quality** - moats, management, industry dynamics
3. **Assess financial health** - margins, cash flow, balance sheet strength
4. **Determine fair value** - multiple valuation approaches
5. **Identify catalysts** - upcoming events, product cycles, regulatory changes
6. **Evaluate risks** - competitive, financial, operational, regulatory
7. **Form conviction** - synthesize analysis into actionable recommendations
## Analysis Framework
### Business Quality Checklist
- [ ] Sustainable competitive advantages identified
- [ ] Revenue growth drivers understood
- [ ] Margin profile and sustainability assessed
- [ ] Capital efficiency evaluated (ROIC > WACC)
- [ ] Management quality and track record reviewed
### Financial Health Assessment
- [ ] Revenue growth: consistent and sustainable?
- [ ] Profit margins: stable or improving?
- [ ] Cash flow: strong and predictable?
- [ ] Balance sheet: manageable debt, adequate liquidity?
- [ ] Capital allocation: wise reinvestment or shareholder returns?
### Valuation Cross-Check
- [ ] P/E ratio vs sector and history
- [ ] EV/EBITDA vs comparable companies
- [ ] PEG ratio (P/E divided by growth rate)
- [ ] Price-to-Book vs ROE relationship
- [ ] DCF intrinsic value estimate
## Investment Thesis Structure
When analyzing a stock, provide:
1. **Executive Summary** (2-3 sentences)
- Investment recommendation (Buy/Hold/Sell)
- Key thesis drivers
- Price target and timeframe
2. **Business Overview** (concise)
- What the company does
- Key products/services and revenue mix
- Competitive position
3. **Investment Merits**
- 3-5 bullish factors
- Support with data from OpenBB
4. **Key Risks**
- 3-5 bearish factors
- Probability and potential impact assessment
5. **Valuation**
- Current valuation metrics
- Fair value estimate
- Upside/downside scenario analysis
6. **Catalysts**
- Near-term events that could drive stock price
- Timeline and probability
7. **Recommendation**
- Buy/Hold/Sell with conviction level
- Suggested position size (% of portfolio)
- Entry price and stop-loss levels
## Response Style
- **Data-driven**: Always back assertions with OpenBB data
- **Balanced**: Present both bullish and bearish cases
- **Actionable**: Provide clear recommendations with specific price targets
- **Risk-aware**: Identify and quantify key risks
- **Probabilistic**: Express confidence levels (high/medium/low conviction)
## Example Output
```
EQUITY ANALYSIS: AAPL
Rating: BUY (High Conviction)
Price Target: $210 (20% upside)
Timeframe: 12 months
INVESTMENT THESIS:
Apple remains a best-in-class compounder with:
1. Services growth (15% CAGR) offsetting hardware cyclicality
2. $166B net cash enables aggressive buybacks
3. Vision Pro ramp provides new growth vector in 2025+
VALUATION: Trading at 28x NTM P/E vs 5yr avg of 24x. Premium justified by:
- ROE of 147% (top decile)
- 32% EBIT margins (expanding)
- $100B+ annual FCF
RISKS:
- China exposure (19% of revenue)
- iPhone saturation in developed markets
- Regulatory scrutiny (App Store fees)
CATALYST MAP:
Q1: Vision Pro launch (Feb 2024)
Q2: WWDC AI announcements (June 2024)
Q3: iPhone 16 cycle (Sept 2024)
RECOMMENDATION:
Accumulate on dips below $180. Core holding for growth portfolios (3-5% weight).
```
## Integration with OpenBB
Always leverage these OpenBB commands for comprehensive analysis:
- `/openbb-equity TICKER` - Price and fundamental data
- `/openbb-macro` - Economic context
- `/openbb-options TICKER` - Options market insights
- `/openbb-research TICKER` - AI-powered research synthesis
Your goal is to provide institutional-quality research that helps investors make informed decisions with appropriate risk-adjusted returns.

228
agents/macro-economist.md Normal file
View File

@@ -0,0 +1,228 @@
---
name: macro-economist
description: Expert macroeconomist specializing in economic analysis, central bank policy, market cycles, and macro-driven investment strategies
model: sonnet
---
You are an expert macroeconomist with deep knowledge of monetary policy, fiscal policy, business cycles, and their impact on financial markets.
## Core Expertise
### Economic Analysis
- **Growth Indicators**: GDP, industrial production, PMI, employment
- **Inflation Dynamics**: CPI, PCE, PPI, wage growth, unit labor costs
- **Monetary Policy**: Fed rates, QE/QT, forward guidance, dot plot
- **Fiscal Policy**: Government spending, deficits, debt levels, multiplier effects
### Market Implications
- **Asset Class Impact**: How macro drives equities, bonds, commodities, currencies
- **Sector Rotation**: Which sectors benefit in each macro regime
- **Regional Analysis**: Developed vs emerging markets, currency impacts
- **Risk On/Off**: Leading indicators of market regime shifts
## Economic Analysis Framework
### Business Cycle Phases
**Early Cycle** (Recovery)
- Indicators: GDP accelerating, unemployment falling
- Fed Policy: Accommodative, low rates
- Market Impact: Stocks up, bonds flat, commodities up
- Best Sectors: Cyclicals, financials, industrials
**Mid Cycle** (Expansion)
- Indicators: GDP stable growth, low unemployment
- Fed Policy: Gradual tightening
- Market Impact: Stocks grind higher, bonds weak
- Best Sectors: Technology, consumer discretionary
**Late Cycle** (Overheating)
- Indicators: Inflation rising, tight labor market
- Fed Policy: Hawkish, raising rates
- Market Impact: Volatility spikes, rotation to defensives
- Best Sectors: Energy, materials, late-cycle value
**Recession**
- Indicators: Negative GDP, rising unemployment
- Fed Policy: Cutting rates, QE possible
- Market Impact: Stocks down, bonds up, flight to safety
- Best Sectors: Utilities, consumer staples, healthcare
### Macro Dashboard
```
MACRO SNAPSHOT: [Date]
GROWTH:
📊 GDP (QoQ): +X.X% (est: +Y.Y%)
📊 Unemployment: X.X% (prev: Y.Y%)
📊 PMI Mfg: XX.X (>50 = expansion)
📊 Consumer Confidence: XXX
INFLATION:
🔥 CPI (YoY): X.X% (target: 2.0%)
🔥 Core PCE: X.X% (Fed's preferred)
🔥 Wage Growth: X.X%
POLICY:
🏦 Fed Funds Rate: X.XX - X.XX%
🏦 Next Meeting: [Date]
🏦 Dot Plot Median (YE): X.XX%
🏦 Balance Sheet: $X.XT (-$XXB QT/month)
MARKET PRICING:
💹 Fed Funds Futures: XX% chance of cut at next meeting
💹 2Y Treasury: X.XX%
💹 10Y Treasury: X.XX%
💹 2s10s Spread: +XX bps (inversion = recession signal)
```
### Leading Indicators Checklist
```
Recession Warning Signs:
⚠️ Yield curve inverted (2s10s < 0) for 3+ months
⚠️ LEI (Leading Economic Index) declining
⚠️ Credit spreads widening >200 bps
⚠️ Unemployment claims rising 4-week avg
⚠️ PMI < 50 for 2+ months
⚠️ Consumer confidence falling rapidly
Recovery Indicators:
✅ Yield curve steepening
✅ Credit spreads tightening
✅ PMI expanding (>50)
✅ Initial claims falling
✅ Housing starts increasing
✅ Fed pivoting dovish
```
## Investment Strategy by Regime
### Stagflation (High Inflation + Slow Growth)
```
Asset Allocation:
- Underweight: Long-duration bonds, growth stocks
- Overweight: Commodities, real assets, value stocks
- Hedge: TIPS, gold, energy stocks
Rationale:
- High inflation erodes real returns
- Slow growth pressures earnings
- Hard assets preserve purchasing power
```
### Goldilocks (Moderate Growth + Low Inflation)
```
Asset Allocation:
- Overweight: Growth stocks, credit
- Neutral: Commodities
- Underweight: Cash (opportunity cost high)
Rationale:
- Best environment for risk assets
- Central banks accommodative
- Multiple expansion + earnings growth
```
### Deflation (Falling Prices + Recession)
```
Asset Allocation:
- Overweight: Long-duration treasuries, quality stocks
- Underweight: Commodities, cyclicals, credit
- Hedge: Volatility products, defensive sectors
Rationale:
- Cash is king (purchasing power rises)
- Bonds rally (rates cut to zero)
- Earnings collapse (avoid leverage)
```
## Policy Analysis
### Fed Decision Tree
```
If Inflation > 3% AND Unemployment < 4%:
→ Hawkish (raise rates, drain liquidity)
→ Market Impact: Stocks down, dollar up
If Inflation < 2% AND Unemployment > 5%:
→ Dovish (cut rates, add liquidity)
→ Market Impact: Stocks up, dollar down
If Inflation ≈ 2% AND Unemployment ≈ 4%:
→ Neutral (data-dependent, patient)
→ Market Impact: Grind higher, low vol
```
### Geopolitical Risk Assessment
```
Monitor:
- Trade policy (tariffs, sanctions)
- Energy supply (OPEC, Russia/Ukraine)
- China tensions (Taiwan, tech war)
- Emerging market crises (debt, currency)
Impact Channels:
- Supply chains → Inflation
- Safe haven flows → USD, gold, treasuries
- Risk premium → Equity volatility
```
## Analysis Output Format
```
MACRO OUTLOOK: [Quarter/Year]
BASE CASE (70% probability):
[2-3 sentence description of most likely scenario]
- GDP: +X.X%
- CPI: X.X%
- Fed: X rate hikes/cuts
→ Asset Class Winners: [list]
UPSIDE SCENARIO (15% probability):
[Optimistic case]
→ Best Trades: [list]
DOWNSIDE SCENARIO (15% probability):
[Pessimistic case]
→ Defensive Positioning: [list]
KEY RISKS TO MONITOR:
1. [Risk with trigger level]
2. [Risk with trigger level]
3. [Risk with trigger level]
POSITIONING RECOMMENDATIONS:
- Equities: [Overweight/Neutral/Underweight]
- Bonds: [Duration long/neutral/short]
- Commodities: [Specific recommendations]
- FX: [USD bias, EM exposure]
```
## Integration Commands
```bash
# Macro dashboard
/openbb-macro --country=US --indicators=all
# Equity impact
/openbb-equity [SECTOR-ETF] --macro-context
# Portfolio positioning
/openbb-portfolio --macro-regime
# Research deep-dive
/openbb-research --macro-driven-thesis
```
## Key Principles
1. **Markets Discount Future**: Price in macro changes 6-12 months ahead
2. **Fed Drives Markets**: Don't fight the Fed
3. **Cycles Repeat**: History rhymes (not repeats)
4. **Volatility Clusters**: Macro uncertainty → vol spikes
5. **Correlation Breaks Down**: Stress → everything correlates to 1
Your mission: Translate complex macroeconomic dynamics into actionable investment insights and risk management strategies.

162
agents/portfolio-manager.md Normal file
View File

@@ -0,0 +1,162 @@
---
name: portfolio-manager
description: Expert portfolio manager specializing in asset allocation, risk management, portfolio optimization, and performance attribution
model: sonnet
---
You are an expert portfolio manager with deep expertise in Modern Portfolio Theory, risk management, and systematic investment strategies.
## Core Responsibilities
### Portfolio Construction
- **Asset Allocation**: Strategic (long-term) and tactical (short-term) positioning
- **Diversification**: Across assets, sectors, geographies, factors
- **Position Sizing**: Kelly Criterion, risk parity, equal weight strategies
- **Rebalancing**: Threshold-based, calendar-based, volatility-targeting
### Risk Management
- **Volatility Targeting**: Maintain consistent portfolio risk level
- **Drawdown Control**: Maximum acceptable loss limits
- **Correlation Analysis**: Identify diversification breakdowns
- **Tail Risk Hedging**: Options, volatility products, safe havens
### Performance Attribution
- **Return Decomposition**: Asset allocation vs security selection
- **Factor Exposure**: Value, growth, momentum, quality contributions
- **Benchmark Analysis**: Active share, tracking error, information ratio
- **Risk-Adjusted Metrics**: Sharpe, Sortino, Calmar ratios
## Portfolio Optimization Framework
### Strategic Asset Allocation
```
1. Define Investment Objectives:
- Return target: X% annually
- Risk tolerance: Y% max drawdown
- Time horizon: Z years
2. Asset Class Selection:
- Equities (domestic/international)
- Fixed income (government/corporate)
- Alternatives (REITs, commodities, crypto)
- Cash/short-term
3. Optimal Weights (mean-variance optimization):
- Expected returns by asset class
- Covariance matrix
- Constraint: min/max weights
- Output: efficient frontier
```
### Tactical Adjustments
```
Overweight When:
✅ Valuations attractive (P/E < historical avg)
✅ Momentum positive (12m trend up)
✅ Sentiment oversold (RSI < 30)
✅ Macro tailwinds (Fed easing, fiscal stimulus)
Underweight When:
⚠️ Valuations stretched
⚠️ Momentum deteriorating
⚠️ Sentiment euphoric
⚠️ Macro headwinds
```
## Portfolio Analysis Template
```
PORTFOLIO REVIEW: [Date]
PERFORMANCE:
YTD Return: +X.X% (Benchmark: +Y.Y%)
Sharpe Ratio: X.XX
Max Drawdown: -X.X%
Win Rate: XX%
CURRENT ALLOCATION:
Equities: XX% (target: XX%)
Fixed Income: XX% (target: XX%)
Alternatives: XX% (target: XX%)
Cash: XX% (target: XX%)
RISK METRICS:
Portfolio Vol: XX% (target: YY%)
Beta to SPY: X.XX
Correlation to BTC: X.XX
VaR (95%, 1-day): -X.X%
TOP 10 POSITIONS: (XX% of portfolio)
1. [SYMBOL] XX.X% (P/L: +XX%)
2. [SYMBOL] XX.X% (P/L: +XX%)
...
REBALANCING ACTIONS:
🔄 Reduce [SYMBOL]: XX% → YY% (take profits)
🔄 Add [SYMBOL]: XX% → YY% (buy dip)
🔄 Trim [SECTOR]: Overweight by X%
RISK ALERTS:
⚠️ Concentration: Top position >10%
⚠️ Correlation spike: Diversification breakdown
⚠️ Volatility surge: Risk target exceeded
```
## Decision Framework
### Buy Triggers
1. **Valuation**: Below intrinsic value by >15%
2. **Technical**: Breakout above resistance with volume
3. **Fundamental**: Positive earnings/guidance surprise
4. **Sentiment**: Contrarian opportunity (fear extreme)
### Sell Triggers
1. **Valuation**: Above fair value by >30%
2. **Technical**: Break below stop-loss
3. **Fundamental**: Thesis broken (deteriorating margins)
4. **Portfolio**: Rebalance (position > max weight)
### Position Sizing Formula
```
Position Size = (Portfolio Risk Target × Portfolio Value) / (Stock Volatility × Stop Distance)
Example:
- Portfolio value: $100,000
- Risk per trade: 2% ($2,000)
- Stock volatility: 30% annual
- Stop distance: 10% from entry
→ Position size: $2,000 / (0.30 × 0.10) = $66,666 (67% of portfolio - TOO HIGH!)
→ Adjusted: Cap at 10% = $10,000
```
## Integration with OpenBB
Use these workflows for portfolio management:
1. **Monthly Review**:
```bash
/openbb-portfolio --analyze
/openbb-macro --impact=portfolio
```
2. **Rebalancing Analysis**:
```bash
/openbb-portfolio --optimize
/openbb-equity [SYMBOL] # For position analysis
```
3. **Risk Check**:
```bash
/openbb-portfolio --risk-metrics
/openbb-options [SYMBOL] --hedge # For tail risk
```
## Key Principles
1. **Diversification is Free Lunch**: Only free risk reduction
2. **Rebalance Systematically**: Buy low, sell high automatically
3. **Control What You Can**: Asset allocation (not market timing)
4. **Risk First, Returns Second**: Preservation > optimization
5. **Tax Efficiency**: Harvest losses, delay gains, location optimization
Your mission: Build resilient portfolios that achieve client objectives with appropriate risk management and tax efficiency.

348
commands/openbb-crypto.md Normal file
View File

@@ -0,0 +1,348 @@
---
name: openbb-crypto
description: Cryptocurrency market analysis using OpenBB - price data, on-chain metrics, DeFi analytics, whale tracking, and market sentiment
---
# OpenBB Cryptocurrency Analysis
Comprehensive cryptocurrency analysis using OpenBB Platform's crypto data sources.
## Usage
```bash
/openbb-crypto SYMBOL [--vs USD|BTC|ETH] [--metrics on-chain|defi|social] [--period 30d]
```
## What This Command Does
Analyzes cryptocurrency markets with price data, on-chain metrics, DeFi analytics, and sentiment analysis.
## Workflow
### 1. Setup OpenBB Connection
```python
from openbb import obb
import pandas as pd
from datetime import datetime, timedelta
# Parse arguments
symbol = sys.argv[1].upper() if len(sys.argv) > 1 else "BTC"
vs_currency = "USD" # USD, BTC, ETH
metrics_type = "all" # on-chain, defi, social, all
period = "30d" # 7d, 30d, 90d, 1y
# Parse flags
for arg in sys.argv[2:]:
if arg.startswith("--vs="):
vs_currency = arg.split("=")[1].upper()
elif arg.startswith("--metrics="):
metrics_type = arg.split("=")[1]
elif arg.startswith("--period="):
period = arg.split("=")[1]
```
### 2. Retrieve Price Data
```python
# Get historical crypto prices
crypto_data = obb.crypto.price.historical(
symbol=f"{symbol}{vs_currency}",
interval="1d",
period=period
)
df = crypto_data.to_dataframe()
print(f"\n₿ Crypto Analysis: {symbol}/{vs_currency}")
print(f"{'='*60}")
current_price = df['close'].iloc[-1]
period_high = df['high'].max()
period_low = df['low'].min()
period_return = ((current_price / df['close'].iloc[0]) - 1) * 100
print(f"\n💰 Price Overview:")
print(f"Current Price: ${current_price:,.2f}")
print(f"{period} High: ${period_high:,.2f}")
print(f"{period} Low: ${period_low:,.2f}")
print(f"{period} Return: {period_return:+.2f}%")
print(f"24h Volume: ${df['volume'].iloc[-1]:,.0f}")
```
### 3. Technical Indicators
```python
# Calculate crypto-specific indicators
print(f"\n📊 Technical Indicators:")
# Moving averages
df['MA_7'] = df['close'].rolling(window=7).mean()
df['MA_30'] = df['close'].rolling(window=30).mean()
df['MA_90'] = df['close'].rolling(window=90).mean()
ma_7 = df['MA_7'].iloc[-1]
ma_30 = df['MA_30'].iloc[-1]
ma_90 = df['MA_90'].iloc[-1]
print(f"MA 7: ${ma_7:,.2f} {'🟢' if current_price > ma_7 else '🔴'}")
print(f"MA 30: ${ma_30:,.2f} {'🟢' if current_price > ma_30 else '🔴'}")
print(f"MA 90: ${ma_90:,.2f} {'🟢' if current_price > ma_90 else '🔴'}")
# Volatility
returns = df['close'].pct_change()
volatility = returns.std() * (365 ** 0.5) * 100 # Annualized
print(f"\nVolatility (ann.): {volatility:.1f}%")
# RSI
delta = df['close'].diff()
gain = delta.where(delta > 0, 0).rolling(window=14).mean()
loss = -delta.where(delta < 0, 0).rolling(window=14).mean()
rs = gain / loss
df['RSI'] = 100 - (100 / (1 + rs))
rsi = df['RSI'].iloc[-1]
print(f"RSI (14): {rsi:.1f}")
if rsi > 70:
print(" ⚠️ Overbought - potential sell signal")
elif rsi < 30:
print(" 🟢 Oversold - potential buy signal")
```
### 4. On-Chain Metrics (if available)
```python
if metrics_type in ["on-chain", "all"]:
print(f"\n⛓️ On-Chain Metrics:")
try:
# Network activity
network_data = obb.crypto.onchain.active_addresses(symbol=symbol)
print(f"Active Addresses (24h): {network_data.active_addresses:,}")
print(f"Transaction Count: {network_data.tx_count:,}")
print(f"Transaction Volume: ${network_data.tx_volume:,.0f}")
# Hash rate (for PoW coins)
if symbol in ["BTC", "ETH", "LTC", "DOGE"]:
hash_data = obb.crypto.onchain.hashrate(symbol=symbol)
print(f"\nHash Rate: {hash_data.hashrate / 1e18:.2f} EH/s")
print(f"Mining Difficulty: {hash_data.difficulty:,.0f}")
# Holder distribution
holders = obb.crypto.onchain.holders(symbol=symbol)
print(f"\nTop 10 Holders: {holders.top_10_pct:.1f}%")
print(f"Top 100 Holders: {holders.top_100_pct:.1f}%")
except Exception as e:
print(f"On-chain data not available for {symbol}")
```
### 5. DeFi Metrics (if applicable)
```python
if metrics_type in ["defi", "all"] and symbol in ["ETH", "BNB", "AVAX", "SOL"]:
print(f"\n🏦 DeFi Metrics:")
try:
defi_data = obb.crypto.defi.tvl(chain=symbol)
print(f"Total Value Locked: ${defi_data.tvl / 1e9:.2f}B")
print(f"Protocol Count: {defi_data.protocol_count}")
print(f"Top Protocol: {defi_data.top_protocol}")
print(f" - TVL: ${defi_data.top_protocol_tvl / 1e9:.2f}B")
# Staking data
staking = obb.crypto.defi.staking(symbol=symbol)
print(f"\nStaking:")
print(f"Total Staked: {staking.total_staked_pct:.1f}%")
print(f"Avg APY: {staking.avg_apy:.2f}%")
except:
print(f"DeFi data not available for {symbol}")
```
### 6. Social Sentiment & News
```python
if metrics_type in ["social", "all"]:
print(f"\n📱 Social Sentiment:")
try:
social_data = obb.crypto.social.sentiment(symbol=symbol)
print(f"Twitter Mentions (24h): {social_data.twitter_mentions:,}")
print(f"Reddit Posts (24h): {social_data.reddit_posts:,}")
print(f"Sentiment Score: {social_data.sentiment_score:.2f}/5.0")
sentiment_emoji = "🟢" if social_data.sentiment_score > 3.5 else "🟡" if social_data.sentiment_score > 2.5 else "🔴"
print(f"Overall Sentiment: {sentiment_emoji}")
# Recent news
news = obb.crypto.news(symbol=symbol, limit=3)
print(f"\n📰 Latest News:")
for i, article in enumerate(news[:3], 1):
print(f"{i}. {article.title}")
print(f" {article.source} - {article.published_date}")
except:
print("Social/news data not available")
```
### 7. Whale Activity Tracker
```python
print(f"\n🐋 Whale Activity (Large Transfers):")
try:
# Get large transactions (>$100k)
whales = obb.crypto.onchain.large_transactions(
symbol=symbol,
min_value=100000,
limit=5
)
if len(whales) > 0:
print(f"Last {len(whales)} large transfers:")
for tx in whales:
print(f" ${tx.value_usd:,.0f} - {tx.from_address[:10]}...→ {tx.to_address[:10]}...")
print(f" {tx.timestamp} ({tx.exchange if tx.exchange else 'Unknown'})")
else:
print("No significant whale activity detected")
except:
print("Whale tracking not available")
```
### 8. AI-Powered Market Analysis
```python
print(f"\n🤖 AI Market Analysis for {symbol}:")
print(f"\n📈 Trend Analysis:")
# Determine trend
if current_price > ma_7 > ma_30 > ma_90:
trend = "Strong Uptrend"
trend_emoji = "🚀"
elif current_price > ma_30:
trend = "Bullish"
trend_emoji = "📈"
elif current_price < ma_7 < ma_30 < ma_90:
trend = "Strong Downtrend"
trend_emoji = "📉"
else:
trend = "Consolidating"
trend_emoji = "↔️"
print(f"{trend_emoji} Market Trend: {trend}")
# Risk assessment
if volatility > 100:
risk = "Very High"
risk_emoji = "🔴"
elif volatility > 60:
risk = "High"
risk_emoji = "🟡"
else:
risk = "Moderate"
risk_emoji = "🟢"
print(f"{risk_emoji} Volatility Risk: {risk}")
# Trading signals
print(f"\n💡 Trading Signals:")
signals = []
if rsi < 30:
signals.append("🟢 RSI oversold - potential buy zone")
if rsi > 70:
signals.append("🔴 RSI overbought - consider taking profits")
if current_price > ma_30 and returns.iloc[-1] > 0.05:
signals.append("🚀 Strong momentum detected")
if df['volume'].iloc[-1] > df['volume'].rolling(20).mean().iloc[-1] * 2:
signals.append("📊 Unusual volume spike")
if signals:
for signal in signals:
print(f" {signal}")
else:
print(" No strong signals detected - market in equilibrium")
```
### 9. Price Targets & Support/Resistance
```python
print(f"\n🎯 Key Levels:")
# Calculate support and resistance
high_30d = df['high'].tail(30).max()
low_30d = df['low'].tail(30).min()
pivot = (high_30d + low_30d + current_price) / 3
resistance_1 = 2 * pivot - low_30d
support_1 = 2 * pivot - high_30d
print(f"Resistance: ${resistance_1:,.2f} ({((resistance_1/current_price - 1) * 100):+.1f}%)")
print(f"Current: ${current_price:,.2f}")
print(f"Support: ${support_1:,.2f} ({((support_1/current_price - 1) * 100):+.1f}%)")
```
## Examples
### Basic crypto analysis
```bash
/openbb-crypto BTC
```
### Ethereum DeFi metrics
```bash
/openbb-crypto ETH --metrics=defi
```
### Altcoin vs BTC
```bash
/openbb-crypto LINK --vs=BTC --period=90d
```
### Social sentiment check
```bash
/openbb-crypto DOGE --metrics=social
```
## Supported Cryptocurrencies
- **Major**: BTC, ETH, BNB, SOL, ADA, XRP, DOT, AVAX
- **DeFi**: UNI, AAVE, LINK, COMP, MKR, SNX
- **Meme**: DOGE, SHIB, PEPE
- **Layer 2**: MATIC, ARB, OP
- **1000+ more via OpenBB data providers**
## Data Sources
- Price data: Multiple exchanges (Binance, Coinbase, etc.)
- On-chain: Glassnode, Santiment, IntoTheBlock
- DeFi: DeFi Llama, The Graph
- Social: LunarCrush, Santiment
## Tips
1. **Compare to BTC**: Use `--vs=BTC` to see altcoin strength vs Bitcoin
2. **Track Whales**: Monitor large transfers for market-moving activity
3. **DeFi Context**: Check TVL and staking for ecosystem health
4. **Sentiment Analysis**: Social metrics can predict short-term moves
5. **Correlation**: Compare multiple cryptos to find divergences
## Integration
```bash
# Portfolio tracking
/openbb-portfolio --add-crypto=BTC,ETH,SOL
# Compare with equity markets
/openbb-macro --crypto-correlation
# AI research
/openbb-research --crypto --symbol=BTC
```
## Notes
- Cryptocurrency markets are 24/7
- High volatility - use appropriate risk management
- Not financial advice - DYOR (Do Your Own Research)
- Consider transaction costs and slippage for trading

267
commands/openbb-equity.md Normal file
View File

@@ -0,0 +1,267 @@
---
name: openbb-equity
description: Comprehensive equity analysis using OpenBB - historical prices, fundamentals, technical indicators, insider trading, analyst ratings, and AI-powered insights
---
# OpenBB Equity Analysis
Perform comprehensive stock analysis using the OpenBB Platform.
## Usage
```bash
/openbb-equity TICKER [--analysis fundamental|technical|all] [--period 1y]
```
## What This Command Does
Retrieves and analyzes equity data for any stock ticker using OpenBB's comprehensive data sources.
## Workflow
### 1. Check OpenBB Installation
First, verify OpenBB is installed:
```python
try:
from openbb import obb
print("✅ OpenBB installed")
except ImportError:
print("⚠️ Installing OpenBB...")
import subprocess
subprocess.run(["pip", "install", "openbb"], check=True)
from openbb import obb
```
### 2. Parse Arguments
```python
# Parse user input
import sys
ticker = sys.argv[1].upper() if len(sys.argv) > 1 else "AAPL"
analysis_type = "all" # fundamental, technical, or all
period = "1y" # 1d, 1w, 1m, 3m, 6m, 1y, 5y
# Parse flags
for arg in sys.argv[2:]:
if arg.startswith("--analysis="):
analysis_type = arg.split("=")[1]
elif arg.startswith("--period="):
period = arg.split("=")[1]
```
### 3. Retrieve Historical Price Data
```python
# Get historical prices
price_data = obb.equity.price.historical(
symbol=ticker,
interval="1d",
period=period
)
df = price_data.to_dataframe()
print(f"\n📈 Historical Prices for {ticker}")
print(f"Period: {period}")
print(f"Latest Close: ${df['close'].iloc[-1]:.2f}")
print(f"52-Week High: ${df['high'].max():.2f}")
print(f"52-Week Low: ${df['low'].min():.2f}")
print(f"YTD Return: {((df['close'].iloc[-1] / df['close'].iloc[0]) - 1) * 100:.2f}%")
```
### 4. Fundamental Analysis (if requested)
```python
if analysis_type in ["fundamental", "all"]:
print(f"\n📊 Fundamental Analysis for {ticker}")
# Company profile
try:
profile = obb.equity.profile(symbol=ticker)
print(f"\nCompany: {profile.name}")
print(f"Sector: {profile.sector}")
print(f"Industry: {profile.industry}")
print(f"Market Cap: ${profile.market_cap / 1e9:.2f}B")
except:
print("Profile data not available")
# Financial metrics
try:
metrics = obb.equity.fundamental.metrics(symbol=ticker)
print(f"\nKey Metrics:")
print(f"P/E Ratio: {metrics.pe_ratio:.2f}")
print(f"EPS: ${metrics.eps:.2f}")
print(f"Dividend Yield: {metrics.dividend_yield:.2%}")
print(f"ROE: {metrics.roe:.2%}")
except:
print("Metrics data not available")
# Analyst ratings
try:
ratings = obb.equity.estimates.analyst(symbol=ticker)
print(f"\nAnalyst Consensus:")
print(f"Buy: {ratings.buy_count}")
print(f"Hold: {ratings.hold_count}")
print(f"Sell: {ratings.sell_count}")
print(f"Target Price: ${ratings.target_price:.2f}")
except:
print("Analyst ratings not available")
```
### 5. Technical Analysis (if requested)
```python
if analysis_type in ["technical", "all"]:
print(f"\n📉 Technical Analysis for {ticker}")
# Calculate technical indicators
import pandas as pd
# Simple Moving Averages
df['SMA_20'] = df['close'].rolling(window=20).mean()
df['SMA_50'] = df['close'].rolling(window=50).mean()
df['SMA_200'] = df['close'].rolling(window=200).mean()
current_price = df['close'].iloc[-1]
sma_20 = df['SMA_20'].iloc[-1]
sma_50 = df['SMA_50'].iloc[-1]
sma_200 = df['SMA_200'].iloc[-1]
print(f"\nMoving Averages:")
print(f"Current Price: ${current_price:.2f}")
print(f"SMA 20: ${sma_20:.2f} {'🟢' if current_price > sma_20 else '🔴'}")
print(f"SMA 50: ${sma_50:.2f} {'🟢' if current_price > sma_50 else '🔴'}")
print(f"SMA 200: ${sma_200:.2f} {'🟢' if current_price > sma_200 else '🔴'}")
# RSI calculation
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
rs = gain / loss
df['RSI'] = 100 - (100 / (1 + rs))
rsi = df['RSI'].iloc[-1]
print(f"\nRSI (14): {rsi:.2f}")
if rsi > 70:
print("⚠️ Overbought territory")
elif rsi < 30:
print("🟢 Oversold territory - potential buy")
else:
print("Neutral zone")
# Volume analysis
avg_volume = df['volume'].rolling(window=20).mean().iloc[-1]
current_volume = df['volume'].iloc[-1]
print(f"\nVolume:")
print(f"Current: {current_volume:,.0f}")
print(f"20-day Avg: {avg_volume:,.0f}")
print(f"Relative: {(current_volume / avg_volume):.2f}x")
```
### 6. AI-Powered Insights
Generate investment insights using Claude's analysis:
```python
# Prepare summary for AI analysis
summary = {
"ticker": ticker,
"current_price": current_price,
"52w_high": df['high'].max(),
"52w_low": df['low'].min(),
"ytd_return": ((df['close'].iloc[-1] / df['close'].iloc[0]) - 1) * 100,
"technical": {
"sma_position": "bullish" if current_price > sma_200 else "bearish",
"rsi": rsi,
"volume_trend": "high" if current_volume > avg_volume else "normal"
}
}
print(f"\n🤖 AI Analysis for {ticker}:")
print("\nBased on the data above, here's my assessment:")
print(f"- Trend: {'Bullish' if current_price > sma_200 else 'Bearish'} (price {'above' if current_price > sma_200 else 'below'} 200-day SMA)")
print(f"- Momentum: {'Overbought' if rsi > 70 else 'Oversold' if rsi < 30 else 'Neutral'} (RSI: {rsi:.1f})")
print(f"- Volume: {'Elevated' if current_volume > avg_volume * 1.5 else 'Normal'} trading activity")
print(f"\n💡 Recommendation: Consider {summary} in context of your investment strategy and risk tolerance.")
```
### 7. Generate Report
Create a formatted analysis report:
```python
print(f"\n{'='*60}")
print(f"EQUITY ANALYSIS REPORT: {ticker}")
print(f"{'='*60}")
print(f"Generated: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Data Source: OpenBB Platform")
print(f"\nAnalysis Type: {analysis_type.upper()}")
print(f"Period Analyzed: {period}")
print(f"\n{'='*60}")
```
## Examples
### Basic equity analysis
```bash
/openbb-equity AAPL
```
### Fundamental analysis only
```bash
/openbb-equity TSLA --analysis=fundamental
```
### Technical analysis with custom period
```bash
/openbb-equity NVDA --analysis=technical --period=6m
```
### Complete analysis
```bash
/openbb-equity GOOGL --analysis=all --period=1y
```
## Data Coverage
- **Price Data**: Historical OHLCV, real-time quotes
- **Fundamentals**: Income statements, balance sheets, cash flow, ratios
- **Technical**: SMA, EMA, RSI, MACD, Bollinger Bands, volume
- **Analyst Data**: Ratings, price targets, recommendations
- **Insider Trading**: Recent insider transactions
- **News**: Latest company news and sentiment
## Tips
1. **Compare Multiple Stocks**: Run for different tickers to compare
2. **Track Over Time**: Save reports to monitor changes
3. **Combine with AI Agents**: Use with equity-analyst agent for deeper insights
4. **Export Data**: Save dataframes to CSV for further analysis
5. **Set Alerts**: Monitor key technical levels (support/resistance)
## Integration with Other Commands
```bash
# Compare with crypto
/openbb-crypto BTC --compare=equity
# Portfolio context
/openbb-portfolio --add=AAPL
# Macro correlation
/openbb-macro --impact=equity
```
## Requirements
- OpenBB Platform installed (`pip install openbb`)
- Python 3.9.21 - 3.12
- Optional: API keys for premium data providers (configured in OpenBB)
## Notes
- Free tier provides delayed data (15-20 minutes)
- Premium data requires API keys (configured via `obb.user.credentials`)
- All financial data is for informational purposes only
- Not financial advice - always do your own research

92
commands/openbb-macro.md Normal file
View File

@@ -0,0 +1,92 @@
---
name: openbb-macro
description: Macroeconomic analysis using OpenBB - GDP, inflation, interest rates, employment, global economic indicators
---
# OpenBB Macroeconomic Analysis
Analyze global macroeconomic trends and indicators using OpenBB Platform.
## Usage
```bash
/openbb-macro [--country US|UK|EU|CN|JP] [--indicators gdp|inflation|rates|employment|all]
```
## What This Command Does
Retrieves and analyzes macroeconomic indicators to understand economic trends and market implications.
## Key Features
### Economic Indicators
- **GDP**: Growth rates, forecasts, components
- **Inflation**: CPI, PPI, PCE, core inflation
- **Interest Rates**: Federal funds, treasury yields, central bank rates
- **Employment**: Unemployment, NFP, job openings, labor participation
- **Consumer**: Confidence, spending, retail sales
- **Manufacturing**: PMI, industrial production, capacity utilization
### Workflow
```python
from openbb import obb
# GDP Analysis
gdp_data = obb.economy.gdp(country="US")
print(f"GDP Growth: {gdp_data.growth_rate:.2f}%")
print(f"GDP per Capita: ${gdp_data.gdp_per_capita:,.0f}")
# Inflation Data
cpi = obb.economy.cpi(country="US")
print(f"CPI (YoY): {cpi.yoy_change:.2f}%")
print(f"Core CPI: {cpi.core_cpi:.2f}%")
# Interest Rates
rates = obb.economy.fed_rates()
print(f"Fed Funds Rate: {rates.current_rate:.2f}%")
print(f"10Y Treasury: {rates.treasury_10y:.2f}%")
# Employment
employment = obb.economy.employment()
print(f"Unemployment Rate: {employment.unemployment_rate:.1f}%")
print(f"NFP (last month): {employment.nfp_change:+,}")
```
### Market Impact Analysis
```python
# Analyze impact on markets
print("\n💡 Market Implications:")
if cpi.yoy_change > 3.0:
print("⚠️ High inflation - Fed likely to maintain hawkish stance")
print(" → Negative for growth stocks, positive for commodities")
if employment.unemployment_rate < 4.0:
print("🔥 Tight labor market - wage pressures building")
print(" → Could sustain inflation, support consumer stocks")
if rates.current_rate > 5.0:
print("💸 High interest rates - restrictive monetary policy")
print(" → Headwind for equities, tailwind for bonds")
```
## Examples
```bash
# US macro overview
/openbb-macro --country=US --indicators=all
# UK inflation focus
/openbb-macro --country=UK --indicators=inflation
# China GDP analysis
/openbb-macro --country=CN --indicators=gdp
```
## Integration
- Correlate with equity performance via `/openbb-equity`
- Impact crypto markets via `/openbb-crypto`
- Portfolio positioning via `/openbb-portfolio`

View File

@@ -0,0 +1,88 @@
---
name: openbb-options
description: Options analysis using OpenBB - chain data, Greeks, implied volatility, strategies, unusual activity
---
# OpenBB Options Analysis
Options chain analysis, Greeks calculations, and strategy optimization using OpenBB Platform.
## Usage
```bash
/openbb-options TICKER [--strategy covered-call|put|spread] [--expiry 30d]
```
## Key Features
### Options Data
- Options chains (calls/puts, all strikes)
- Greeks (Delta, Gamma, Theta, Vega, Rho)
- Implied volatility smile/skew
- Open interest and volume analysis
- Unusual options activity
### Workflow
```python
from openbb import obb
ticker = "AAPL"
expiry = "2024-12-20"
# Get options chain
chain = obb.derivatives.options.chains(symbol=ticker, expiration=expiry)
# Analyze call options
calls = chain[chain['option_type'] == 'call']
print(f"\n📞 Call Options for {ticker} (Exp: {expiry})")
print(f"{'Strike':>8} {'Last':>8} {'IV':>8} {'Delta':>8} {'OI':>10} {'Volume':>10}")
for _, opt in calls.iterrows():
print(f"${opt['strike']:>7.2f} ${opt['last']:>7.2f} {opt['iv']:>7.1f}% "
f"{opt['delta']:>7.3f} {opt['open_interest']:>9,} {opt['volume']:>9,}")
# Greeks summary
print(f"\n🔢 Portfolio Greeks:")
print(f"Net Delta: {calls['delta'].sum():.2f}")
print(f"Net Gamma: {calls['gamma'].sum():.4f}")
print(f"Net Theta: {calls['theta'].sum():.2f} (daily decay)")
print(f"Net Vega: {calls['vega'].sum():.2f} (per 1% IV move)")
```
### Strategy Analysis
```python
# Covered Call Strategy
stock_price = obb.equity.price.quote(symbol=ticker).price
strike = stock_price * 1.05 # 5% OTM
call_premium = chain[(chain['strike'] == strike) & (chain['option_type'] == 'call')]['last'].iloc[0]
print(f"\n📊 Covered Call Strategy ({ticker}):")
print(f"Stock Price: ${stock_price:.2f}")
print(f"Sell Call: ${strike:.2f} strike")
print(f"Premium: ${call_premium:.2f}")
print(f"Max Profit: ${(strike - stock_price + call_premium):.2f} ({((strike - stock_price + call_premium) / stock_price * 100):.1f}%)")
print(f"Breakeven: ${(stock_price - call_premium):.2f}")
```
### Unusual Activity
```python
# Detect unusual options activity
unusual = chain[chain['volume'] > chain['open_interest'] * 2]
print(f"\n🚨 Unusual Activity ({len(unusual)} contracts):")
for _, opt in unusual.head(5).iterrows():
print(f"{opt['option_type'].upper()} ${opt['strike']:.2f} - "
f"Vol: {opt['volume']:,} (OI: {opt['open_interest']:,})")
```
## Examples
```bash
/openbb-options SPY --strategy=covered-call
/openbb-options TSLA --expiry=14d
/openbb-options NVDA --unusual-activity
```

View File

@@ -0,0 +1,155 @@
---
name: openbb-portfolio
description: Portfolio analysis and optimization using OpenBB - performance tracking, risk metrics, asset allocation, rebalancing
---
# OpenBB Portfolio Analysis
Comprehensive portfolio management and optimization using OpenBB Platform.
## Usage
```bash
/openbb-portfolio [--analyze] [--optimize] [--benchmark SPY]
```
## What This Command Does
Analyzes portfolio performance, calculates risk metrics, and provides optimization recommendations.
## Key Features
### Portfolio Metrics
- **Returns**: Total return, annualized, Sharpe ratio, Sortino ratio
- **Risk**: Volatility, max drawdown, VaR, conditional VaR
- **Allocation**: Asset mix, sector exposure, geographic distribution
- **Performance Attribution**: Contribution analysis by position
### Workflow
```python
from openbb import obb
import pandas as pd
# Define portfolio (can load from file or define inline)
portfolio = {
"AAPL": {"shares": 50, "cost_basis": 150.00},
"MSFT": {"shares": 30, "cost_basis": 300.00},
"GOOGL": {"shares": 20, "cost_basis": 2500.00},
"BTC-USD": {"shares": 0.5, "cost_basis": 45000.00}
}
# Calculate current values
total_value = 0
positions = []
for symbol, data in portfolio.items():
current_price = obb.equity.price.quote(symbol=symbol).price
position_value = current_price * data["shares"]
total_value += position_value
pnl = (current_price - data["cost_basis"]) * data["shares"]
pnl_pct = (current_price / data["cost_basis"] - 1) * 100
positions.append({
"symbol": symbol,
"shares": data["shares"],
"cost_basis": data["cost_basis"],
"current_price": current_price,
"value": position_value,
"pnl": pnl,
"pnl_pct": pnl_pct,
"weight": 0 # Calculate after total_value known
})
# Calculate weights
for pos in positions:
pos["weight"] = (pos["value"] / total_value) * 100
# Display portfolio
print(f"\n💼 Portfolio Overview")
print(f"{'='*80}")
print(f"Total Value: ${total_value:,.2f}\n")
print(f"{'Symbol':<10} {'Shares':>10} {'Price':>12} {'Value':>15} {'P/L %':>10} {'Weight':>10}")
print(f"{'-'*80}")
for pos in positions:
print(f"{pos['symbol']:<10} {pos['shares']:>10.2f} ${pos['current_price']:>11.2f} "
f"${pos['value']:>14.2f} {pos['pnl_pct']:>9.1f}% {pos['weight']:>9.1f}%")
```
### Risk Analysis
```python
# Calculate portfolio-level risk metrics
returns = []
for symbol in portfolio.keys():
hist = obb.equity.price.historical(symbol=symbol, period="1y")
returns.append(hist.to_dataframe()['close'].pct_change())
portfolio_returns = pd.concat(returns, axis=1).mean(axis=1)
portfolio_vol = portfolio_returns.std() * (252 ** 0.5) * 100 # Annualized
# Sharpe Ratio (assuming 4% risk-free rate)
risk_free_rate = 0.04
sharpe = (portfolio_returns.mean() * 252 - risk_free_rate) / (portfolio_returns.std() * (252 ** 0.5))
# Max Drawdown
cumulative = (1 + portfolio_returns).cumprod()
running_max = cumulative.expanding().max()
drawdown = (cumulative - running_max) / running_max
max_dd = drawdown.min() * 100
print(f"\n📊 Risk Metrics:")
print(f"Annualized Volatility: {portfolio_vol:.2f}%")
print(f"Sharpe Ratio: {sharpe:.2f}")
print(f"Max Drawdown: {max_dd:.2f}%")
```
### Portfolio Optimization
```python
print(f"\n🎯 Optimization Recommendations:")
# Diversification score
diversification = 100 - max([pos['weight'] for pos in positions])
print(f"Diversification Score: {diversification:.0f}/100")
if diversification < 70:
print("⚠️ Portfolio concentrated - consider adding positions")
# Rebalancing suggestions
target_weight = 100 / len(positions)
rebalance_needed = []
for pos in positions:
diff = abs(pos['weight'] - target_weight)
if diff > 10:
action = "Reduce" if pos['weight'] > target_weight else "Increase"
rebalance_needed.append(f"{action} {pos['symbol']}: {pos['weight']:.1f}% → {target_weight:.1f}%")
if rebalance_needed:
print(f"\n🔄 Rebalancing Suggestions:")
for suggestion in rebalance_needed:
print(f"{suggestion}")
```
## Examples
```bash
# Analyze current portfolio
/openbb-portfolio --analyze
# Optimize allocation
/openbb-portfolio --optimize
# Compare to SPY benchmark
/openbb-portfolio --benchmark=SPY
```
## Integration
- Import positions from CSV/Excel
- Export reports to PDF
- Sync with brokerage accounts (via supported integrations)
- Tax-loss harvesting analysis

174
commands/openbb-research.md Normal file
View File

@@ -0,0 +1,174 @@
---
name: openbb-research
description: AI-powered investment research using OpenBB - comprehensive analysis, thesis generation, risk assessment, actionable insights
---
# OpenBB AI Investment Research
AI-powered comprehensive investment research combining OpenBB data with Claude's analytical capabilities.
## Usage
```bash
/openbb-research SYMBOL [--depth deep|quick] [--focus thesis|risks|opportunities]
```
## What This Command Does
Conducts comprehensive AI-powered investment research by combining multiple OpenBB data sources with advanced analysis.
## Workflow
### 1. Data Aggregation
```python
from openbb import obb
symbol = "AAPL"
# Gather comprehensive data
data = {
"price": obb.equity.price.historical(symbol=symbol, period="1y"),
"fundamentals": obb.equity.fundamental.metrics(symbol=symbol),
"analyst": obb.equity.estimates.analyst(symbol=symbol),
"news": obb.equity.news(symbol=symbol, limit=10),
"peers": obb.equity.compare.peers(symbol=symbol),
"insider": obb.equity.ownership.insider(symbol=symbol)
}
```
### 2. Investment Thesis Generation
```python
print(f"\n📋 Investment Thesis for {symbol}")
print(f"{'='*60}")
# Business Analysis
print(f"\n1. Business Quality:")
print(f" - Competitive moats identified")
print(f" - Revenue growth trajectory")
print(f" - Margin trends and sustainability")
print(f" - Market position and share")
# Financial Health
print(f"\n2. Financial Strength:")
print(f" - Balance sheet assessment")
print(f" - Cash flow generation")
print(f" - Capital allocation efficiency")
print(f" - Debt levels and coverage")
# Valuation
print(f"\n3. Valuation Assessment:")
print(f" - P/E vs sector average")
print(f" - PEG ratio analysis")
print(f" - DCF model implications")
print(f" - Historical valuation ranges")
# Catalysts
print(f"\n4. Key Catalysts:")
print(f" - Upcoming earnings/events")
print(f" - Product launches")
print(f" - Regulatory developments")
print(f" - Industry trends")
```
### 3. Risk Assessment
```python
print(f"\n⚠️ Risk Factors:")
risks = []
# Check technical risks
if data["price"].rsi[-1] > 75:
risks.append("Overbought conditions - potential pullback risk")
# Check fundamental risks
if data["fundamentals"].debt_to_equity > 1.5:
risks.append("High leverage - financial risk elevated")
# Check market risks
if data["price"].volatility > 50:
risks.append("High volatility - price uncertainty")
for i, risk in enumerate(risks, 1):
print(f" {i}. {risk}")
```
### 4. Opportunity Analysis
```python
print(f"\n💡 Investment Opportunities:")
opportunities = []
if data["analyst"].rating_score > 4.0:
opportunities.append("Strong analyst support - positive sentiment")
if data["insider"].net_buy_sell > 0:
opportunities.append("Insider buying - management confidence")
if data["fundamentals"].roe > 20:
opportunities.append("High ROE - efficient capital use")
for i, opp in enumerate(opportunities, 1):
print(f" {i}. {opp}")
```
### 5. Actionable Recommendations
```python
print(f"\n🎯 Recommendation:")
# Decision matrix
score = 0
score += 2 if data["analyst"].rating_score > 4.0 else 0
score += 2 if data["fundamentals"].roe > 15 else 0
score += 1 if data["price"].trend == "bullish" else 0
score -= 1 if data["fundamentals"].pe_ratio > 30 else 0
if score >= 4:
rating = "BUY"
action = "Consider accumulating position"
elif score >= 2:
rating = "HOLD"
action = "Monitor closely, hold current position"
else:
rating = "AVOID"
action = "Wait for better entry point"
print(f" Rating: {rating}")
print(f" Action: {action}")
print(f" Confidence: {score}/5")
```
## Examples
```bash
# Deep research report
/openbb-research AAPL --depth=deep
# Quick thesis
/openbb-research MSFT --depth=quick --focus=thesis
# Risk analysis
/openbb-research TSLA --focus=risks
```
## Output Format
1. Executive Summary
2. Investment Thesis
3. Financial Analysis
4. Valuation Assessment
5. Risk Factors
6. Opportunities
7. Recommendation & Price Targets
8. Monitoring Checklist
## Integration
- Export reports to PDF/Markdown
- Track recommendations over time
- Compare with analyst consensus
- Portfolio integration via `/openbb-portfolio`

121
plugin.lock.json Normal file
View File

@@ -0,0 +1,121 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:jeremylongshore/claude-code-plugins-plus:plugins/finance/openbb-terminal",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "e8db22ac3d88525329243e669508c44580a68467",
"treeHash": "21c51be3ea8be605f0fe247667d1cec0bcba3b03bc4817ede0632b2e9f8352ca",
"generatedAt": "2025-11-28T10:18:37.972723Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "openbb-terminal",
"description": "Open-source investment research terminal integration - equity analysis, crypto tracking, macro indicators, portfolio optimization, and AI-powered financial insights using OpenBB Platform",
"version": "1.0.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "24e745f46c51526cdf5e29c529506d9ed08fa53ad842d28606fda43fc55697bf"
},
{
"path": "agents/equity-analyst.md",
"sha256": "1093a718c64f81a655eaad6e110e0af7dcc9f977ce24682a5d0fdffc7c398a16"
},
{
"path": "agents/macro-economist.md",
"sha256": "7c20c09646d9f8e64c3e13899c789e5a75f3e5fd1a8fa181a6fa32bfefc172ab"
},
{
"path": "agents/crypto-analyst.md",
"sha256": "f5f3ecd7f28a3fff4d1d1fd9aca8d30b5f1b43f622f0a02696a6b4e11c7b5041"
},
{
"path": "agents/portfolio-manager.md",
"sha256": "28c2db09689cb8e506879c2183b4577d4da4e04368cfe3ab66e944f1af0a7c25"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "f13dbfcf05c9e4a23795f430f3aa345d92a44d6d8cce1a17f836346b4abc88be"
},
{
"path": "commands/openbb-macro.md",
"sha256": "8a830f3eed35da57f7aacf6bece5a6861e74bad003aa71132685f65ae37b41a3"
},
{
"path": "commands/openbb-crypto.md",
"sha256": "5b259debf04a18c2bb12a5d6e927be68d8439524209a0b871a97b55dbfe87069"
},
{
"path": "commands/openbb-options.md",
"sha256": "7cbb393ee58dd4688a06f446cbfd6cfd9739154c89608124a3f9e306c58c9158"
},
{
"path": "commands/openbb-portfolio.md",
"sha256": "a19c752767c6ce21ef4b5a83837ea91588b71c1fbaad88d35924e4f956c4a797"
},
{
"path": "commands/openbb-research.md",
"sha256": "db35f1facaa64f005dd7ac8a61172b69603f8758c4e6186cb02ea124e329c70d"
},
{
"path": "commands/openbb-equity.md",
"sha256": "555c17e93e0dec47b0440295ed280727de0d63c14a0cbf47cfbfd8dbedddb4bb"
},
{
"path": "skills/skill-adapter/references/examples.md",
"sha256": "922bbc3c4ebf38b76f515b5c1998ebde6bf902233e00e2c5a0e9176f975a7572"
},
{
"path": "skills/skill-adapter/references/best-practices.md",
"sha256": "c8f32b3566252f50daacd346d7045a1060c718ef5cfb07c55a0f2dec5f1fb39e"
},
{
"path": "skills/skill-adapter/references/README.md",
"sha256": "c0b6ca3dbfcf620a2ad2ba528b7d1c052d95554937fcba14f9ff08adfc972e39"
},
{
"path": "skills/skill-adapter/scripts/helper-template.sh",
"sha256": "0881d5660a8a7045550d09ae0acc15642c24b70de6f08808120f47f86ccdf077"
},
{
"path": "skills/skill-adapter/scripts/validation.sh",
"sha256": "92551a29a7f512d2036e4f1fb46c2a3dc6bff0f7dde4a9f699533e446db48502"
},
{
"path": "skills/skill-adapter/scripts/README.md",
"sha256": "75bde9696d566219ba75be2e5827e690f2f088bdc47b20ce1adce8659199c13f"
},
{
"path": "skills/skill-adapter/assets/test-data.json",
"sha256": "ac17dca3d6e253a5f39f2a2f1b388e5146043756b05d9ce7ac53a0042eee139d"
},
{
"path": "skills/skill-adapter/assets/README.md",
"sha256": "e8a8c058cc3c72de9add796157b222465723b034fa770b97863f373e255fb16a"
},
{
"path": "skills/skill-adapter/assets/skill-schema.json",
"sha256": "f5639ba823a24c9ac4fb21444c0717b7aefde1a4993682897f5bf544f863c2cd"
},
{
"path": "skills/skill-adapter/assets/config-template.json",
"sha256": "0c2ba33d2d3c5ccb266c0848fc43caa68a2aa6a80ff315d4b378352711f83e1c"
}
],
"dirSha256": "21c51be3ea8be605f0fe247667d1cec0bcba3b03bc4817ede0632b2e9f8352ca"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

View File

@@ -0,0 +1,7 @@
# Assets
Bundled resources for openbb-terminal skill
- [ ] report_template.html: HTML template for generating investment reports
- [ ] example_report.pdf: Example investment report generated using the plugin
- [ ] openbb_logo.png: OpenBB logo for branding purposes

View File

@@ -0,0 +1,32 @@
{
"skill": {
"name": "skill-name",
"version": "1.0.0",
"enabled": true,
"settings": {
"verbose": false,
"autoActivate": true,
"toolRestrictions": true
}
},
"triggers": {
"keywords": [
"example-trigger-1",
"example-trigger-2"
],
"patterns": []
},
"tools": {
"allowed": [
"Read",
"Grep",
"Bash"
],
"restricted": []
},
"metadata": {
"author": "Plugin Author",
"category": "general",
"tags": []
}
}

View File

@@ -0,0 +1,28 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Claude Skill Configuration",
"type": "object",
"required": ["name", "description"],
"properties": {
"name": {
"type": "string",
"pattern": "^[a-z0-9-]+$",
"maxLength": 64,
"description": "Skill identifier (lowercase, hyphens only)"
},
"description": {
"type": "string",
"maxLength": 1024,
"description": "What the skill does and when to use it"
},
"allowed-tools": {
"type": "string",
"description": "Comma-separated list of allowed tools"
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$",
"description": "Semantic version (x.y.z)"
}
}
}

View File

@@ -0,0 +1,27 @@
{
"testCases": [
{
"name": "Basic activation test",
"input": "trigger phrase example",
"expected": {
"activated": true,
"toolsUsed": ["Read", "Grep"],
"success": true
}
},
{
"name": "Complex workflow test",
"input": "multi-step trigger example",
"expected": {
"activated": true,
"steps": 3,
"toolsUsed": ["Read", "Write", "Bash"],
"success": true
}
}
],
"fixtures": {
"sampleInput": "example data",
"expectedOutput": "processed result"
}
}

View File

@@ -0,0 +1,7 @@
# References
Bundled resources for openbb-terminal skill
- [ ] openbb_api_documentation.md: Comprehensive documentation of OpenBB Platform API
- [ ] investment_analysis_best_practices.md: Best practices for investment analysis using OpenBB data
- [ ] openbb_data_schemas.md: Data schemas for various OpenBB data endpoints

View File

@@ -0,0 +1,69 @@
# Skill Best Practices
Guidelines for optimal skill usage and development.
## For Users
### Activation Best Practices
1. **Use Clear Trigger Phrases**
- Match phrases from skill description
- Be specific about intent
- Provide necessary context
2. **Provide Sufficient Context**
- Include relevant file paths
- Specify scope of analysis
- Mention any constraints
3. **Understand Tool Permissions**
- Check allowed-tools in frontmatter
- Know what the skill can/cannot do
- Request appropriate actions
### Workflow Optimization
- Start with simple requests
- Build up to complex workflows
- Verify each step before proceeding
- Use skill consistently for related tasks
## For Developers
### Skill Development Guidelines
1. **Clear Descriptions**
- Include explicit trigger phrases
- Document all capabilities
- Specify limitations
2. **Proper Tool Permissions**
- Use minimal necessary tools
- Document security implications
- Test with restricted tools
3. **Comprehensive Documentation**
- Provide usage examples
- Document common pitfalls
- Include troubleshooting guide
### Maintenance
- Keep version updated
- Test after tool updates
- Monitor user feedback
- Iterate on descriptions
## Performance Tips
- Scope skills to specific domains
- Avoid overlapping trigger phrases
- Keep descriptions under 1024 chars
- Test activation reliability
## Security Considerations
- Never include secrets in skill files
- Validate all inputs
- Use read-only tools when possible
- Document security requirements

View File

@@ -0,0 +1,70 @@
# Skill Usage Examples
This document provides practical examples of how to use this skill effectively.
## Basic Usage
### Example 1: Simple Activation
**User Request:**
```
[Describe trigger phrase here]
```
**Skill Response:**
1. Analyzes the request
2. Performs the required action
3. Returns results
### Example 2: Complex Workflow
**User Request:**
```
[Describe complex scenario]
```
**Workflow:**
1. Step 1: Initial analysis
2. Step 2: Data processing
3. Step 3: Result generation
4. Step 4: Validation
## Advanced Patterns
### Pattern 1: Chaining Operations
Combine this skill with other tools:
```
Step 1: Use this skill for [purpose]
Step 2: Chain with [other tool]
Step 3: Finalize with [action]
```
### Pattern 2: Error Handling
If issues occur:
- Check trigger phrase matches
- Verify context is available
- Review allowed-tools permissions
## Tips & Best Practices
- ✅ Be specific with trigger phrases
- ✅ Provide necessary context
- ✅ Check tool permissions match needs
- ❌ Avoid vague requests
- ❌ Don't mix unrelated tasks
## Common Issues
**Issue:** Skill doesn't activate
**Solution:** Use exact trigger phrases from description
**Issue:** Unexpected results
**Solution:** Check input format and context
## See Also
- Main SKILL.md for full documentation
- scripts/ for automation helpers
- assets/ for configuration examples

View File

@@ -0,0 +1,7 @@
# Scripts
Bundled resources for openbb-terminal skill
- [ ] openbb_data_fetcher.py: Script to fetch data from OpenBB Platform based on user query
- [ ] openbb_report_generator.py: Script to generate investment reports based on fetched data
- [ ] openbb_error_handler.py: Script to handle errors and provide informative messages

View File

@@ -0,0 +1,42 @@
#!/bin/bash
# Helper script template for skill automation
# Customize this for your skill's specific needs
set -e
function show_usage() {
echo "Usage: $0 [options]"
echo ""
echo "Options:"
echo " -h, --help Show this help message"
echo " -v, --verbose Enable verbose output"
echo ""
}
# Parse arguments
VERBOSE=false
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_usage
exit 0
;;
-v|--verbose)
VERBOSE=true
shift
;;
*)
echo "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# Your skill logic here
if [ "$VERBOSE" = true ]; then
echo "Running skill automation..."
fi
echo "✅ Complete"

View File

@@ -0,0 +1,32 @@
#!/bin/bash
# Skill validation helper
# Validates skill activation and functionality
set -e
echo "🔍 Validating skill..."
# Check if SKILL.md exists
if [ ! -f "../SKILL.md" ]; then
echo "❌ Error: SKILL.md not found"
exit 1
fi
# Validate frontmatter
if ! grep -q "^---$" "../SKILL.md"; then
echo "❌ Error: No frontmatter found"
exit 1
fi
# Check required fields
if ! grep -q "^name:" "../SKILL.md"; then
echo "❌ Error: Missing 'name' field"
exit 1
fi
if ! grep -q "^description:" "../SKILL.md"; then
echo "❌ Error: Missing 'description' field"
exit 1
fi
echo "✅ Skill validation passed"