Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 34 additions & 11 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# ─────────────────────────────────────────────
# OpenSwarm — environment configuration
# Trading Portfolio Swarm — environment configuration
# Copy this file to .env and fill in your keys.
# Run `python run.py` to launch the onboarding
# wizard, which fills this file automatically.
Expand Down Expand Up @@ -29,8 +29,7 @@ DEFAULT_MODEL=

# ── Optional: Composio ───────────────────────

# Composio unlocks 10,000+ external integrations (Gmail, Slack, Google Calendar,
# HubSpot, GitHub, and more) for the General Agent.
# Composio unlocks external integrations when you add custom tools that need them.
# Get your key and user ID at https://composio.dev
COMPOSIO_API_KEY=
COMPOSIO_USER_ID=
Expand All @@ -44,27 +43,51 @@ COMPOSIO_USER_ID=
SEARCH_API_KEY=


# ── Trading / IBKR ───────────────────────────

# Interactive Brokers TWS or IB Gateway API settings.
# TWS paper trading usually uses port 7497; live TWS usually uses 7496.
# IB Gateway paper trading usually uses 4002; live gateway usually uses 4001.
IBKR_HOST=127.0.0.1
IBKR_PORT=7497
IBKR_CLIENT_ID=19
IBKR_ACCOUNT=
IBKR_READONLY=true

# Live trading is disabled unless this is explicitly set to true.
# IBKR_TRADE_CONFIRMATION_TOKEN must match the token provided to the order tool.
IBKR_ENABLE_LIVE_TRADING=false
IBKR_TRADE_CONFIRMATION_TOKEN=


# ── Optional: Paid market data / research APIs ─────────

POLYGON_API_KEY=
ALPHAVANTAGE_API_KEY=
FINNHUB_API_KEY=
FMP_API_KEY=
TIINGO_API_KEY=
NEWSAPI_API_KEY=


# ── Optional: Images / Video ─────────────────────────

# Google AI / Gemini — used for image generation, editing, and composition
# (Gemini 2.5 Flash Image, Gemini 3 Pro Image) across Image Agent, Slides Agent,
# and Video Agent; also required for Veo video generation (Video Agent).
# Google AI / Gemini — reserved for custom extensions that need Gemini models.
# Get your key at https://aistudio.google.com/app/apikey
GOOGLE_API_KEY=

# Pexels — stock photo search used by Slides Agent (ImageSearch tool).
# Pexels — reserved for custom extensions that need stock image search.
# Get your key at https://www.pexels.com/api
PEXELS_API_KEY=

# Pixabay — stock photo search used by Slides Agent (ImageSearch tool).
# Pixabay — reserved for custom extensions that need stock image search.
# Get your key at https://pixabay.com/api/docs
PIXABAY_API_KEY=

# Unsplash — stock photo search used by Slides Agent (ImageSearch tool).
# Unsplash — reserved for custom extensions that need stock image search.
# Get your key at https://unsplash.com/developers
UNSPLASH_ACCESS_KEY=

# fal.ai — used for Seedance 1.5 Pro video generation, video editing (Video Agent),
# and background removal (Image Agent).
# fal.ai — reserved for custom extensions that need media generation.
# Get your key at https://fal.ai/dashboard/keys
FAL_KEY=
194 changes: 57 additions & 137 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,162 +1,82 @@
<div align="center">
# Trading Portfolio Swarm

# 🚀 OpenSwarm
This fork of OpenSwarm is configured as a multi-agent trading and portfolio-management team.

![OpenSwarm](assets/new-framework.jpg)
It coordinates specialists for:

</div>
- IBKR API capability detection, account snapshots, market-data entitlement probes, order previews, and gated live order routing.
- Portfolio construction, rebalancing, and ROI-oriented allocation across daily, short, medium, and long horizons.
- Quantitative research, factor analysis, backtesting, and algorithm diagnostics.
- Market, sentiment, politics, macro, regulatory, and paid-research synthesis.
- Risk review, drawdown controls, liquidity checks, leverage limits, and pre-trade verdicts.

**The fully open-source multi-agent system that does everything Claude Code can't.**
Built on [Agency Swarm](https://github.com/VRSEN/agency-swarm).

Create polished slide decks, research reports, data visualizations, documents, images, and videos — all from a single prompt in your terminal. No platform, no UI, no setup hassles.
## Agent Roster

✨ **One prompt → Complete deliverables**
🎯 **8 specialized agents working together**
⚡ **Install in 30 seconds, running in 60**
🔧 **100% customizable and forkable**
| Agent | Owns |
|---|---|
| **Orchestrator** | Routes work to the right trading specialists. |
| **Trade Execution Agent** | IBKR connection checks, account snapshots, market-data probes, order previews, and safety-gated live orders. |
| **Portfolio Manager** | Allocation, position sizing, rebalancing, and multi-horizon portfolio plans. |
| **Quantitative Analyst** | Backtests, signals, factor analysis, and algorithm research. |
| **Market Research Analyst** | Fundamentals, news, sentiment, politics, macro, regulation, and research-source synthesis. |
| **Risk Manager** | Exposure, drawdown, liquidity, leverage, stops, margin, and pre-trade risk controls. |
| **Data Analyst** | General CSV/Excel analysis, dashboards, charts, KPIs, and broader statistics. |
| **Docs Agent** | Investment memos, research reports, trading journals, policies, SOPs, and formatted exports. |

Built on [Agency Swarm](https://github.com/VRSEN/agency-swarm) — the framework powering real AI agencies.

---

> 💼 **Investor or looking to integrate AI agents into your SaaS?**
> We're the team behind OpenSwarm and Agency Swarm, building the future of multi-agent systems.
> **[Partner with us →](https://vrsen-ai.notion.site/fee2d391a8d74b24baa04a0b648af83c?pvs=105)**

---

## 💡 What Makes This Different?

Instead of one agent trying to do everything poorly, you get **specialists coordinated by an orchestrator**.

### 🎯 Real Examples

Paste these into your terminal and watch magic happen:

- **"Create a complete investor pitch for OpenSwarm"** → Full deck + executive summary + market research
- **"Research my top 5 competitors and write 3 SEO-optimized blog posts"** → Competitive analysis + keyword research + publish-ready content
- **"Analyze this data and create a quarterly report with charts"** → Data insights + visualizations + formatted document
- **"Generate a product launch video with animations"** → Professional video with graphics and transitions
- **"Build me a marketing campaign for Q2"** → Strategy doc + creative assets + implementation timeline

Connect to 10,000+ external services (Gmail, Slack, GitHub, HubSpot) via Composio for even more power.

---

## 🤖 Meet Your AI Team

| Agent | What it does |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Orchestrator** | Routes every user request to the right specialist(s). Never answers directly — pure coordination. |
| **Virtual Assistant** | Handles everyday tasks: writing, scheduling, messaging, task management. Gains 10,000+ external integrations via [Composio](https://composio.dev) (Gmail, Slack, GitHub, HubSpot, and more). |
| **Deep Research** | Conducts comprehensive, evidence-based web research with citations and balanced analysis. |
| **Data Analyst** | Analyses structured data, builds charts, runs statistical models — all inside an isolated IPython kernel. |
| **Slides Agent** | Generates complete, visually polished HTML slide decks, then exports them to PPTX. |
| **Docs Agent** | Creates formatted Word documents and PDFs from outlines or raw content. |
| **Image Generation Agent** | Generates and edits images using Gemini 2.5 Flash Image / Gemini 3 Pro Image and fal.ai. |
| **Video Generation Agent** | Produces videos via Sora (OpenAI), Veo (Google), and Seedance (fal.ai); also edits and combines clips. |

---

## 📦 Get Started in 30 Seconds

**For most users (recommended):**
## Setup

```bash
npm install -g @vrsen/openswarm
openswarm
cp .env.example .env
python3 -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
python3 run.py
```

That's it! The setup wizard handles everything: authentication, dependencies, and configuration.

**Requirements:** Node.js 20+ (Python 3.10+ auto-installed)

## 🔧 Build Your Own Swarm
At minimum, configure one model provider key in `.env`, such as `OPENAI_API_KEY`.

Fork this repo and create your own specialized AI team in minutes:
For IBKR workflows, start TWS or IB Gateway, enable API access, and configure:

```bash
git clone https://github.com/VRSEN/openswarm.git
cd openswarm
```env
IBKR_HOST=127.0.0.1
IBKR_PORT=7497
IBKR_CLIENT_ID=19
IBKR_ACCOUNT=
IBKR_READONLY=true
```

Then tell **Claude Code**, **Cursor**, or **Codex**:

> _"Turn this into an SEO optimization swarm"_

They'll automatically customize all agents for your use case.

**Popular custom swarms:**

- **SEO Swarm:** Keyword research + competitor analysis + blog writing
- **Sales Swarm:** Lead research + outreach + proposal generation
- **Marketing Swarm:** Campaign planning + creative assets + analytics
- **Product Swarm:** Market research + feature specs + launch materials
Live order submission is blocked unless both are configured:

## ⚙️ API Keys & Setup

The setup wizard walks you through everything, but you'll need at least one of these:

**Required (choose one):**

- `OPENAI_API_KEY` - For GPT 5.5 and Sora video generation
- `ANTHROPIC_API_KEY` - For Claude models

**Optional superpowers:**

- `COMPOSIO_API_KEY` - Unlock 10,000+ integrations (Gmail, Slack, GitHub, etc.)
- `GOOGLE_API_KEY` - Gemini image generation + Veo video
- `FAL_KEY` - Advanced video editing and effects
- `SEARCH_API_KEY` - Web search for research agent

Tools gracefully degrade when keys are missing — you'll get clear instructions on what to add.

---

## 🚀 Coming Soon

- **Agent Builder Agent** - Create custom swarms from a single prompt
- **OpenClaw + Claude Code integration** - All agents in one place

⭐ **Star us on GitHub** to stay updated and help us prioritize features!

## 🏗️ For Developers

**Local development:**

```bash
git clone https://github.com/VRSEN/openswarm.git
cd openswarm
python swarm.py
```env
IBKR_ENABLE_LIVE_TRADING=true
IBKR_TRADE_CONFIRMATION_TOKEN=<your-private-token>
```

**Docker deployment:**

```bash
git clone https://github.com/VRSEN/openswarm.git
cd openswarm
cp .env.example .env # Add your API keys
docker-compose up --build
```
## Optional Data Sources

**API server:**
The swarm detects available providers at runtime without exposing secret values:

```bash
python server.py # Runs on localhost:8080
```env
POLYGON_API_KEY=
ALPHAVANTAGE_API_KEY=
FINNHUB_API_KEY=
FMP_API_KEY=
TIINGO_API_KEY=
NEWSAPI_API_KEY=
SEARCH_API_KEY=
```

---

## 📺 Learn More

- **Watch the full demo:** [YouTube video →](https://youtu.be/c5DdXzqaeVU?si=rM2CNaZ8qVwMvqmz)
- **Multi-agent framework:** [Agency Swarm](https://github.com/VRSEN/agency-swarm)
- **External integrations:** [Composio](https://composio.dev)

---
## Typical Prompts

## 📄 License
- "Check which IBKR and market-data capabilities are currently available."
- "Review my IBKR portfolio and propose risk-adjusted rebalancing actions."
- "Research AAPL using fundamentals, sentiment, politics/regulation, and market context."
- "Backtest a daily momentum strategy on SPY and compare it to buy-and-hold."
- "Risk-check this proposed QQQ trade and preview the IBKR order."
- "Analyze this trading log CSV and turn the findings into an investment memo."

MIT — see [LICENSE](LICENSE).
## Risk Notice

**Built with ❤️ by the team behind [Agency Swarm](https://github.com/VRSEN/agency-swarm)**
This software is a local automation framework. It does not guarantee returns and does not remove trading risk. Use paper trading first, verify all data and orders manually, and comply with your broker, tax, and regulatory obligations.
3 changes: 3 additions & 0 deletions market_research_agent/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .market_research_agent import create_market_research_agent

__all__ = ["create_market_research_agent"]
41 changes: 41 additions & 0 deletions market_research_agent/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Role

You are the **Market Research Analyst** for the trading swarm.

# Scope

You own:
- Company, sector, macro, political, geopolitical, regulatory, and sentiment research.
- Catalyst calendars, earnings context, analyst/research notes when available, and news synthesis.
- Interpreting emotional/behavioral market factors: positioning, crowd sentiment, narrative intensity, panic/euphoria, and event risk.
- Detecting paid research and news APIs available at runtime and using the best available source.

# Research Rules

- Use `TradingCapabilityDetector` before relying on paid research/data feeds.
- Use web research for current market, political, regulatory, and news claims.
- Prefer primary sources: filings, company releases, regulator/government publications, exchange notices, and central-bank sources.
- Cite sources for claims that are not derived from user-provided data.
- Distinguish fact, market narrative, consensus expectation, and your inference.
- If a paid API is detected but no direct tool exists, explain the required integration clearly instead of pretending to have queried it.

# Output

Use:

**Market Setup**
- Current state, catalysts, and relevant macro/political context.

**Sentiment and Narrative**
- Bullish and bearish narratives, emotional extremes, positioning clues, and confidence.

**Fundamental Context**
- Valuation, growth, balance-sheet, competitive, or sector drivers if relevant.

**Trade Implications**
- How the research supports or weakens daily, short, medium, and long-horizon ideas.

**Sources and Limits**
- Inline source links and explicit gaps.

Do not make execution decisions alone. Route portfolio sizing to Portfolio Manager and order placement to Trade Execution Agent.
38 changes: 38 additions & 0 deletions market_research_agent/market_research_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os

from agency_swarm import Agent, ModelSettings
from agency_swarm.tools import IPythonInterpreter, WebSearchTool
from openai.types.shared import Reasoning

from config import get_default_model, is_openai_provider
from trading_tools import MarketDataSnapshot, TradingCapabilityDetector
from virtual_assistant.tools.ScholarSearch import ScholarSearch

current_dir = os.path.dirname(os.path.abspath(__file__))


def create_market_research_agent() -> Agent:
return Agent(
name="Market Research Analyst",
description="Market, fundamental, sentiment, politics, macro, and paid-research synthesis specialist.",
instructions=os.path.join(current_dir, "instructions.md"),
tools=[
WebSearchTool(),
ScholarSearch,
TradingCapabilityDetector,
MarketDataSnapshot,
IPythonInterpreter,
],
model=get_default_model(),
model_settings=ModelSettings(
reasoning=Reasoning(effort="high", summary="auto") if is_openai_provider() else None,
truncation="auto",
response_include=["web_search_call.action.sources"] if is_openai_provider() else None,
),
conversation_starters=[
"Research the market setup for semiconductors this week.",
"Analyze sentiment and political risk around a stock.",
"Compare analyst, news, and macro factors for my watchlist.",
"Detect which paid research APIs are available and use them if possible.",
],
)
1 change: 1 addition & 0 deletions market_research_agent/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading