### Install and Setup with npm Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Install project dependencies and run the setup script using npm. This is an alternative quick start method. ```bash cd app && npm install && npm run setup ``` -------------------------------- ### Example: Complete Setup Steps Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md A step-by-step guide to setting up the project configuration. It includes copying an example `.env` file, obtaining API keys, and editing the `.env` file. ```bash # 1. Copy example config cp .env.example .env # 2. Get API keys from providers # - OpenAI: https://platform.openai.com/api-keys # - FinancialDatasets: https://www.financialdatasets.ai # 3. Edit .env with your keys nano .env ``` -------------------------------- ### Development Environment Setup Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example `.env.local` file for development setup. Includes API keys, database URL for SQLite, and logging level. ```bash # .env.local OPENAI_API_KEY=sk-test-... FINANCIAL_DATASETS_API_KEY=test-key DATABASE_URL=sqlite:///./hedge_fund_dev.db LOG_LEVEL=DEBUG ``` -------------------------------- ### Production Environment Setup Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example `.env.prod` file for production setup. Uses a PostgreSQL database and specifies allowed origins for security. ```bash # .env.prod (or environment variables in deployment) OPENAI_API_KEY=sk-prod-... FINANCIAL_DATASETS_API_KEY=prod-key DATABASE_URL=postgresql://user:pass@host:5432/hedge_fund_prod LOG_LEVEL=INFO WORKERS=8 ALLOWED_ORIGINS=https://app.example.com ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Clone the AI Hedge Fund repository and set up the project environment variables by copying the example configuration file. ```bash git clone https://github.com/virattt/ai-hedge-fund.git cd ai-hedge-fund ``` ```bash # Create .env file for your API keys (in the root directory) cp .env.example .env ``` -------------------------------- ### Backtesting Engine Initialization and Execution Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/03-backtesting-engine.md Demonstrates how to initialize and run the BacktestEngine. This example shows setting up the agent, engine parameters, and then executing the backtest to retrieve performance metrics. ```python from src.main import create_workflow from src.backtesting.engine import BacktestEngine workflow = create_workflow() agent = workflow.compile() engine = BacktestEngine( agent=agent, tickers=["AAPL", "MSFT"], start_date="2024-01-01", end_date="2024-03-31", initial_capital=100000.0, model_name="gpt-4o", model_provider="OpenAI", selected_analysts=None, initial_margin_requirement=0.25 ) metrics = engine.run_backtest() print(f"Sharpe Ratio: {metrics['sharpe_ratio']}") print(f"Max Drawdown: {metrics['max_drawdown']}") ``` -------------------------------- ### CLI Example: Backtester with Specific Arguments Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Provides a command-line example for running the backtester script with tickers, date range, and all analysts. ```bash poetry run python src/backtester.py \ --ticker AAPL,MSFT \ --start-date 2024-01-01 \ --end-date 2024-03-31 \ --analysts-all ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/frontend/README.md Installs the necessary dependencies for the project. Use npm, pnpm, or yarn. ```bash npm install # or `pnpm install` or `yarn install` ``` -------------------------------- ### Example ApiKey Data Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Illustrates how to instantiate the ApiKey model with sample provider and key information. ```python key = ApiKey( provider="OPENAI_API_KEY", key_value="sk-...", is_active=True, description="Main OpenAI account" ) key2 = ApiKey( provider="ANTHROPIC_API_KEY", key_value="sk-ant-...", is_active=True, description="Anthropic backup" ) ``` -------------------------------- ### CLI Example: Running with Defaults (All Analysts) Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Shows how to run the main script using all available analysts by default. ```bash # Use all analysts poetry run python src/main.py --ticker AAPL,MSFT --analysts-all ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Install frontend application dependencies using npm, pnpm, or yarn. This command should be run from the frontend directory. ```bash cd app/frontend npm install # or pnpm install or yarn install ``` -------------------------------- ### Database URL Configuration Examples Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Examples of SQLAlchemy database URLs for SQLite, PostgreSQL (sync and async), and MySQL. ```bash # SQLite (file-based, good for development) DATABASE_URL=sqlite:///./hedge_fund.db ``` ```bash # PostgreSQL DATABASE_URL=postgresql://user:password@localhost:5432/hedge_fund ``` ```bash # PostgreSQL (async) DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/hedge_fund ``` ```bash # MySQL DATABASE_URL=mysql+pymysql://user:password@localhost:3306/hedge_fund ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md A sample .env file demonstrating required and optional environment variables for the AI Hedge Fund project. ```bash # Required: LLM API Keys (choose at least one) OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... # Required: Financial Data FINANCIAL_DATASETS_API_KEY=your-api-key # Optional: Database DATABASE_URL=sqlite:///./hedge_fund.db # Optional: Ollama (if using local models) OLLAMA_BASE_URL=http://localhost:11434 # Optional: Custom OpenAI endpoint OPENAI_API_BASE=https://api.openai.com/v1 # Optional: Logging LOG_LEVEL=INFO ``` -------------------------------- ### CLI Example: Running with All Arguments Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Shows a command-line invocation with all possible arguments specified for the main script. ```bash poetry run python src/main.py \ --ticker AAPL,MSFT,NVDA \ --analysts warren_buffett,michael_burry \ --start-date 2024-01-01 \ --end-date 2024-03-31 \ --model gpt-4o \ --reasoning ``` -------------------------------- ### CLI Example: Running with Defaults (Ollama) Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Illustrates running the main script with tickers and specifying Ollama as the model provider. ```bash # Use Ollama poetry run python src/main.py --ticker AAPL,MSFT --ollama ``` -------------------------------- ### HedgeFundFlow Example Data Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Illustrates how to instantiate the HedgeFundFlow model with sample data for nodes, edges, and other attributes. ```python flow = HedgeFundFlow( name="Conservative Value Strategy", description="Warren Buffett + Ben Graham", nodes=[ {"id": "warren_buffett", "type": "agent", ...}, {"id": "ben_graham", "type": "agent", ...}, {"id": "portfolio_manager", "type": "portfolio"} ], edges=[ {"source": "warren_buffett", "target": "portfolio_manager"}, {"source": "ben_graham", "target": "portfolio_manager"} ], data={ "tickers": ["AAPL", "MSFT"], "initialCash": 100000 }, is_template=False, tags=["value", "conservative"] ) ``` -------------------------------- ### Run Frontend Development Server Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Start the frontend development server using npm. This command should be executed from the frontend directory. ```bash # In another terminal, from the frontend directory cd app/frontend npm run dev ``` -------------------------------- ### Install Root Project Dependencies Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Install the root project dependencies using Poetry. This command should be run from the project's root directory. ```bash # From the root directory poetry install ``` -------------------------------- ### Verify Uvicorn and FastAPI Installation Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Run this command to confirm that uvicorn and fastapi are correctly installed in the Poetry environment. ```bash cd app/backend poetry run python -c "import uvicorn; import fastapi" ``` -------------------------------- ### Install Backend Dependencies Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Install backend application dependencies. Depending on the backend's configuration, this can be done using pip with a requirements.txt file or with Poetry. ```bash # Navigate to the backend directory cd app/backend pip install -r requirements.txt # If there's a requirements.txt file # OR poetry install # If there's a pyproject.toml in the backend directory ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Install all project dependencies using Poetry. Ensure you are in the root directory of the cloned repository. ```bash poetry install ``` -------------------------------- ### Example: Using add_date_args with Default Lookback Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Shows how to use add_date_args to set default start and end dates based on a lookback period in months. This is useful for setting default date ranges for analysis. ```python import argparse from src.cli.input import add_date_args parser = argparse.ArgumentParser() add_date_args(parser, default_months_back=3) args = parser.parse_args() # args.start_date defaults to 3 months ago # args.end_date defaults to today ``` -------------------------------- ### Create Flow Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Demonstrates how to use the FlowRepository to create a new flow with specified name, description, nodes, and edges. ```python from sqlalchemy.orm import Session from app.backend.repositories.flow_repository import FlowRepository def create_strategy(db: Session): repo = FlowRepository(db) flow = repo.create_flow( name="My Strategy", description="Test strategy", nodes=[...], edges=[...], is_template=False ) return flow.id ``` -------------------------------- ### Record Flow Run Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Shows how to use the FlowRunRepository to create a new run, update its status, and record execution results. ```python from sqlalchemy.orm import Session from app.backend.repositories.flow_run_repository import FlowRunRepository def record_execution(db: Session, flow_id: int): repo = FlowRunRepository(db) run = repo.create_run( flow_id=flow_id, status="IN_PROGRESS", request_data={"tickers": ["AAPL"]} ) # ... execute strategy ... repo.update_run( run.id, status="COMPLETE", results={"decisions": {...}} ) ``` -------------------------------- ### Set up Environment Variables for API Keys Source: https://github.com/virattt/ai-hedge-fund/blob/main/README.md Copy the example environment file and populate it with your necessary API keys for LLMs and financial data. Ensure at least one LLM API key is set. ```bash # Create .env file for your API keys (in the root directory) cp .env.example .env ``` ```bash # For running LLMs hosted by openai (gpt-4o, gpt-4o-mini, etc.) OPENAI_API_KEY=your-openai-api-key # For getting financial data to power the hedge fund FINANCIAL_DATASETS_API_KEY=your-financial-datasets-api-key ``` -------------------------------- ### Backtest Engine Integration Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/03-backtesting-engine.md Demonstrates how to initialize and run the BacktestEngine with specified agents, tickers, and date ranges. Shows how to access computed metrics and portfolio values. ```python from src.main import create_workflow from src.backtesting.engine import BacktestEngine from src.backtesting.metrics import PerformanceMetricsCalculator # Create the agent workflow workflow = create_workflow(selected_analysts=["warren_buffett", "michael_burry"]) agent = workflow.compile() # Create and run the backtest engine engine = BacktestEngine( agent=agent, tickers=["AAPL", "MSFT", "NVDA"], start_date="2023-01-01", end_date="2023-12-31", initial_capital=100000.0, model_name="gpt-4o", model_provider="OpenAI", selected_analysts=["warren_buffett", "michael_burry"], initial_margin_requirement=0.25 ) metrics = engine.run_backtest() # Access results print(f"Sharpe Ratio: {metrics.get('sharpe_ratio')}") print(f"Max Drawdown: {metrics.get('max_drawdown')}%") print(f"Portfolio Values: {engine._portfolio_values}") ``` -------------------------------- ### GET /api-keys/ Response Body Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Example JSON structure for retrieving a list of API keys. Sensitive values like key_value are omitted for security. ```json [ { "provider": "OPENAI_API_KEY", "is_active": true, "last_used": "2024-01-15T10:00:00Z" }, ... ] ``` -------------------------------- ### Run Development Server Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/frontend/README.md Starts the development server for the application. Hot-reloading is enabled for automatic updates in the browser. ```bash npm run dev ``` -------------------------------- ### Docker Run Command with Environment Variables Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example `docker run` command to start a container with environment variables passed directly using the `-e` flag. ```bash docker run \ -e OPENAI_API_KEY=sk-... \ -e FINANCIAL_DATASETS_API_KEY=... \ ai-hedge-fund:latest ``` -------------------------------- ### AgentState Initialization Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/01-core-api.md Demonstrates how to initialize an AgentState object with sample messages, data, and metadata. This is useful for setting up the initial state of an agent workflow. ```python from src.graph.state import AgentState from langchain_core.messages import HumanMessage initial_state: AgentState = { "messages": [HumanMessage(content="Make trading decisions")], "data": { "tickers": ["AAPL", "MSFT"], "portfolio": {...}, "start_date": "2024-01-01", "end_date": "2024-03-01", "analyst_signals": {}, }, "metadata": { "show_reasoning": True, "model_name": "gpt-4o", "model_provider": "OpenAI", }, } ``` -------------------------------- ### CLI Example: Running with Defaults (Interactive Analyst Selection) Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Demonstrates running the main script with only required tickers, prompting for analyst selection interactively. ```bash # Interactive analyst selection poetry run python src/main.py --ticker AAPL,MSFT ``` -------------------------------- ### Install Poetry Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Install Poetry, a dependency management tool for Python, if it's not already installed on your system. ```bash curl -sSL https://install.python-poetry.org | python3 - ``` -------------------------------- ### POST /flows/ Response Body Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Example JSON structure for a successful response when creating or retrieving a flow. ```json { "id": 1, "name": "My Strategy", "description": "...", "nodes": [...], "edges": [...], "created_at": "2024-01-15T10:00:00Z", "updated_at": "2024-01-15T10:00:00Z" } ``` -------------------------------- ### Example HedgeFundFlowRun Data Instantiation Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Demonstrates how to create an instance of the HedgeFundFlowRun model with sample data. This includes setting flow ID, status, timestamps, trading mode, and detailed request, portfolio, and results data. ```python run = HedgeFundFlowRun( flow_id=1, status="COMPLETE", started_at=datetime.now() - timedelta(minutes=5), completed_at=datetime.now(), trading_mode="one-time", request_data={ "tickers": ["AAPL", "MSFT"], "model_name": "gpt-4o", "initial_cash": 100000 }, initial_portfolio={"cash": 100000, "positions": {}}, final_portfolio={"cash": 105000, "positions": {"AAPL": 100}}, results={ "decisions": {"AAPL": {"action": "buy", "quantity": 100}}, "analyst_signals": {...} }, run_number=1 ) ``` -------------------------------- ### POST /api-keys/ Request Body Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Example JSON payload for creating or updating an API key. Requires provider and key value. ```json { "provider": "OPENAI_API_KEY", "key_value": "sk-...", "description": "Main OpenAI key" } ``` -------------------------------- ### POST /flows/ Request Body Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Example JSON payload for creating a new hedge fund flow. It includes essential fields like name, nodes, and edges. ```json { "name": "My Strategy", "description": "...", "nodes": [...], "edges": [...], "viewport": {...}, "data": {...}, "is_template": false, "tags": [] } ``` -------------------------------- ### Run Backend Server Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Start the backend FastAPI server using Poetry to manage the environment. This command should be executed from the backend directory. ```bash # In one terminal, from the backend directory cd app/backend poetry run uvicorn main:app --reload ``` -------------------------------- ### Example HedgeFundFlowRunCycle Data Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Illustrates how to instantiate and populate a HedgeFundFlowRunCycle object with sample data, including signals, decisions, and performance metrics. ```python cycle = HedgeFundFlowRunCycle( flow_run_id=1, cycle_number=1, started_at=datetime.now(), completed_at=datetime.now() + timedelta(minutes=2), analyst_signals={ "warren_buffett_agent": { "AAPL": {"signal": "bullish", "confidence": 85} } }, trading_decisions={ "AAPL": {"action": "buy", "quantity": 100} }, executed_trades={"AAPL": 100}, portfolio_snapshot={"cash": 99900, "positions": {"AAPL": 100}}, status="COMPLETED", llm_calls_count=3, api_calls_count=5, estimated_cost="$0.12", trigger_reason="manual" ) ``` -------------------------------- ### Build Docker Image for AI Hedge Fund Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Build the Docker image for the AI Hedge Fund. Ensure Docker is installed and navigate to the 'docker' directory first. ```bash # On Linux/Mac: ./run.sh build # On Windows: run.bat build ``` -------------------------------- ### Create and Copy Environment File Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Create a .env file for storing environment variables by copying the example file. This file is used for API keys and other sensitive configurations. ```bash cp .env.example .env ``` -------------------------------- ### AnalystSignal Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/05-data-models.md Illustrates the expected structure of a dictionary containing signals from a specific analyst agent. ```python { "warren_buffett_agent": { "AAPL": { "signal": "bullish", "confidence": 85, "reasoning": "...", "valuation_score": 8.5 } } } ``` -------------------------------- ### Database Connection Setup Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/09-database-models.md Sets up the SQLAlchemy engine and session factory. Configured via the DATABASE_URL environment variable. Provides a FastAPI dependency for database sessions. ```python from sqlalchemy import create_engine from sqlalchemy.orm import declarative_base, sessionmaker # SQLAlchemy Base class for all ORM models Base = declarative_base() # Database engine (configured via DATABASE_URL environment variable) engine = create_engine(DATABASE_URL) # Session factory for creating database sessions SessionLocal = sessionmaker(bind=engine) def get_db(): """FastAPI dependency to get database session.""" db = SessionLocal() try: yield db finally: db.close() ``` ```bash DATABASE_URL=postgresql://user:password@localhost/hedge_fund # or DATABASE_URL=sqlite:///./hedge_fund.db ``` -------------------------------- ### Run the FastAPI Development Server Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Start the FastAPI development server using uvicorn. This command enables hot-reloading for development. ```bash poetry run uvicorn main:app --reload ``` -------------------------------- ### Display Agent Reasoning Example Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/01-core-api.md Shows how to use the show_agent_reasoning function with a sample analysis dictionary and agent name. This is helpful for debugging agent behavior. ```python from src.graph.state import show_agent_reasoning analysis = { "signal": "bullish", "confidence": 85, "reasoning": "Strong fundamentals and growth prospects" } show_agent_reasoning(analysis, "Warren Buffett") ``` -------------------------------- ### Example Usage of Progress Update Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/06-agent-system.md Demonstrates how to use the `progress.update_status` function to track an agent's progress through different stages of analysis. ```python progress.update_status("warren_buffett_agent", "AAPL", "Fetching financial metrics") progress.update_status("warren_buffett_agent", "AAPL", "Analyzing fundamentals") progress.update_status("warren_buffett_agent", "AAPL", "Done") ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker, Dates, and Tickers (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Windows, execute the backtester using Docker, defining a specific start and end date and the tickers for the backtesting period. ```bash run.bat --ticker AAPL,MSFT,NVDA --start-date 2024-01-01 --end-date 2024-03-01 backtest ``` -------------------------------- ### Example Usage of parse_cli_inputs Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Demonstrates how to call the `parse_cli_inputs` function with various options and access the parsed results. ```python from src.cli.input import parse_cli_inputs inputs = parse_cli_inputs( description="Run the hedge fund trading system", require_tickers=True, default_months_back=None, include_graph_flag=True, include_reasoning_flag=True, ) print(f"Tickers: {inputs.tickers}") print(f"Analysts: {inputs.selected_analysts}") print(f"Start: {inputs.start_date}") print(f"End: {inputs.end_date}") ``` -------------------------------- ### Error Handling Example with parse_cli_inputs Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Demonstrates how to use a try-except block to handle potential `SystemExit` or other exceptions during CLI input parsing. ```python from src.cli.input import parse_cli_inputs try: inputs = parse_cli_inputs( description="Run hedge fund", require_tickers=True, ) except SystemExit: # User pressed Ctrl+C or validation failed print("Input cancelled") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Run AI Hedge Fund with Docker, Dates, and Tickers (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Windows, run the AI hedge fund with Docker, defining a specific start and end date for analysis and the tickers to be included. ```bash run.bat --ticker AAPL,MSFT,NVDA --start-date 2024-01-01 --end-date 2024-03-01 main ``` -------------------------------- ### Example: Using add_common_args Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Demonstrates how to use the add_common_args function to configure an ArgumentParser with common CLI options, including making tickers a required argument. ```python import argparse from src.cli.input import add_common_args parser = argparse.ArgumentParser() add_common_args(parser, require_tickers=True) args = parser.parse_args() ``` -------------------------------- ### Integrate Data Access API Functions Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/07-data-access-api.md Example demonstrating how to fetch various financial data points including prices, metrics, line items, market cap, news, and insider trades, then combine them into an analysis object. ```python from src.tools.api import ( get_prices, get_financial_metrics, search_line_items, get_company_news, get_insider_trades, get_market_cap ) ticker = "AAPL" end_date = "2024-03-31" start_date = "2024-01-01" # Get price data prices = get_prices(ticker, start_date, end_date) latest_price = prices[-1].close if prices else 0 # Get financial metrics metrics = get_financial_metrics(ticker, end_date, limit=5) # Get specific line items line_items = search_line_items( ticker, ["revenue", "net_income", "free_cash_flow", "outstanding_shares"], end_date, limit=5 ) # Get market cap market_cap = get_market_cap(ticker, end_date) # Get recent news news = get_company_news(ticker, end_date, start_date, limit=20) # Get insider activity trades = get_insider_trades(ticker, end_date, start_date, limit=100) # Combine into analysis analysis = { "ticker": ticker, "latest_price": latest_price, "market_cap": market_cap, "pe_ratio": metrics[0].price_to_earnings_ratio if metrics else None, "recent_news_count": len(news), "insider_buys": sum(1 for t in trades if t.transaction_shares > 0), "insider_sells": sum(1 for t in trades if t.transaction_shares < 0), } ``` -------------------------------- ### Custom Agent Implementation Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/06-agent-system.md An example of creating a custom analyst agent that analyzes tickers, generates signals using an LLM, and updates progress. ```python from src.graph.state import AgentState, show_agent_reasoning from langchain_core.prompts import ChatPromptTemplate from pydantic import BaseModel, Field from typing_extensions import Literal from src.utils.llm import call_llm from src.utils.progress import progress import json class MySignal(BaseModel): signal: Literal["bullish", "bearish", "neutral"] confidence: int = Field(description="0-100") reasoning: str def my_custom_agent(state: AgentState, agent_id: str = "my_agent") -> dict: """Custom analyst agent.""" data = state["data"] tickers = data["tickers"] end_date = data["end_date"] signals = {} for ticker in tickers: progress.update_status(agent_id, ticker, "Analyzing") # Get LLM from state or create it llm = ... # Initialize your LLM prompt = ChatPromptTemplate.from_template( "Analyze {ticker} as of {date}. Provide your signal." ) signal = call_llm( llm=llm, prompt=prompt, output_schema=MySignal, input_variables={"ticker": ticker, "date": end_date} ) signals[ticker] = signal.model_dump() message = HumanMessage(content=json.dumps(signals), name=agent_id) if state["metadata"]["show_reasoning"]: show_agent_reasoning(signals, "My Custom Agent") return { "messages": state["messages"] + [message], "data": { "analyst_signals": { agent_id: signals } } } ``` -------------------------------- ### Example: Using select_analysts Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Illustrates different ways to use the select_analysts function: for interactive selection, when all analysts are requested via flags, or when specific analysts are provided. ```python from src.cli.input import select_analysts # Interactive selection analysts = select_analysts() # All analysts analysts = select_analysts({"analysts_all": True}) # Specific analysts analysts = select_analysts({"analysts": "warren_buffett,michael_burry"}) ``` -------------------------------- ### Docker Compose Environment Configuration Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example `docker-compose.yml` snippet showing how to set environment variables for the backend service, referencing variables from a `.env` file. ```yaml services: backend: environment: OPENAI_API_KEY: ${OPENAI_API_KEY} DATABASE_URL: postgresql://db:5432/hedge_fund ``` -------------------------------- ### Troubleshooting API Key Not Found Error Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example error message and solution steps for an 'API Key not found' error. Emphasizes checking the `.env` file, its contents, and reloading the shell. ```text ValueError: OpenAI API key not found. Please make sure OPENAI_API_KEY is set in your .env file Solution: 1. Check if .env file exists 2. Verify OPENAI_API_KEY=sk-... is in file 3. Run load_dotenv() before accessing key 4. Reload shell: source .env ``` -------------------------------- ### Python Request for Hedge Fund Run Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Example Python code using the requests library to send a POST request to the `/hedge-fund/run` endpoint and stream the SSE responses. ```python import requests import json url = "http://localhost:8000/hedge-fund/run" payload = { "tickers": ["AAPL", "MSFT"], "graph_nodes": [ {"id": "warren_buffett", "type": "agent"}, {"id": "portfolio_manager", "type": "portfolio"} ], "graph_edges": [ {"source": "warren_buffett", "target": "portfolio_manager"} ], "model_name": "gpt-4o", "model_provider": "OpenAI", "start_date": "2024-01-01", "end_date": "2024-01-15", "initial_cash": 100000.0, "api_keys": {"OPENAI_API_KEY": "sk-..."} } response = requests.post(url, json=payload, stream=True) for line in response.iter_lines(): if line: event_data = json.loads(line) print(event_data) ``` -------------------------------- ### get_market_cap() Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/07-data-access-api.md Gets the current market capitalization for a given stock ticker. ```APIDOC ## get_market_cap() ### Description Gets current market capitalization. ### Method get_market_cap ### Parameters #### Path Parameters - **ticker** (str) - Required - Stock symbol #### Query Parameters - **end_date** (str) - Optional - The date for which to retrieve market cap - **api_key** (str) - Optional - API key ### Returns Market cap in dollars (float) ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker and Ollama (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Windows, execute the backtester with Docker, enabling local LLM usage through Ollama. Tickers must be provided for the backtest. ```bash run.bat --ticker AAPL,MSFT,NVDA --ollama backtest ``` -------------------------------- ### Force Reinstall Poetry Dependencies Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Force a resynchronization of Poetry dependencies to resolve installation problems. ```bash cd app/backend poetry install --sync ``` -------------------------------- ### GET /hedge-fund/agents Response Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md This JSON structure details the response for retrieving a list of available agents. ```json { "agents": [ { "key": "warren_buffett", "display_name": "Warren Buffett", "description": "The Oracle of Omaha", "investing_style": "..." }, ... ] } ``` -------------------------------- ### GET /flows/ Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Retrieves a summary list of all existing flows. Optionally includes template flows in the response. ```APIDOC ## GET /flows/ ### Description Retrieves all flows (summary view). ### Method GET ### Endpoint /flows/ ### Parameters #### Query Parameters - **include_templates** (bool) - Optional - Default: true - Include template flows ### Response #### Success Response (200 OK) - Returns a list of `FlowSummaryResponse` objects. ``` -------------------------------- ### Clone the AI Hedge Fund Repository Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Clone the project repository using git. This is the first step in setting up the backend. ```bash git clone https://github.com/virattt/ai-hedge-fund.git cd ai-hedge-fund ``` -------------------------------- ### GET /api-keys/ Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Retrieves a list of all managed API keys. For security, the actual key values are excluded from the response. ```APIDOC ## GET /api-keys/ ### Description Retrieves all API keys (without values for security). ### Method GET ### Endpoint /api-keys/ ### Response #### Success Response - Returns a list of API key objects, each containing provider, is_active, and last_used. ### Response Example ```json [ { "provider": "OPENAI_API_KEY", "is_active": true, "last_used": "2024-01-15T10:00:00Z" }, ... ] ``` ``` -------------------------------- ### Get Price Data as DataFrame Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/07-data-access-api.md Fetches price data for a specific date range and returns it as a pandas DataFrame. ```python def get_price_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker and Ollama (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Linux/macOS, run the backtester using Docker and integrate local LLMs via Ollama. Specify the tickers for backtesting. ```bash ./run.sh --ticker AAPL,MSFT,NVDA --ollama backtest ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker, Dates, and Tickers (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Linux/macOS, run the backtester with Docker, specifying a date range and the tickers for the backtesting period. ```bash ./run.sh --ticker AAPL,MSFT,NVDA --start-date 2024-01-01 --end-date 2024-03-01 backtest ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Execute the backtester script on Windows using Docker. Ensure you are in the docker directory and specify the tickers for the backtest. ```bash cd docker run.bat --ticker AAPL,MSFT,NVDA backtest ``` -------------------------------- ### Run AI Hedge Fund with Docker and Ollama (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Execute the AI hedge fund on Windows with Docker, utilizing local LLMs through Ollama. Tickers are required. ```bash run.bat --ticker AAPL,MSFT,NVDA --ollama main ``` -------------------------------- ### BacktestEngine Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/03-backtesting-engine.md Initializes the BacktestEngine with all necessary parameters to run a backtest simulation. ```APIDOC ## BacktestEngine Class **Location:** `src/backtesting/engine.py:27` Main orchestrator for backtesting operations. ```python class BacktestEngine: def __init__( self, *, agent, tickers: list[str], start_date: str, end_date: str, initial_capital: float, model_name: str, model_provider: str, selected_analysts: list[str] | None, initial_margin_requirement: float, ) -> None ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | agent | Callable | ✓ | Compiled LangGraph agent (from create_workflow) | | tickers | list[str] | ✓ | Stock symbols to backtest | | start_date | str | ✓ | Backtest start date (YYYY-MM-DD) | | end_date | str | ✓ | Backtest end date (YYYY-MM-DD) | | initial_capital | float | ✓ | Starting portfolio cash | | model_name | str | ✓ | LLM model name (e.g., "gpt-4o") | | model_provider | str | ✓ | LLM provider (e.g., "OpenAI") | | selected_analysts | list[str] | None | ✓ | Analyst keys or None for all | | initial_margin_requirement | float | ✓ | Margin requirement ratio (0.0-1.0) | ``` -------------------------------- ### Backtest Request Model Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/05-data-models.md Defines the structure for a backtesting request, including start and end dates, and initial capital. Inherits from BaseHedgeFundRequest. ```python class BacktestRequest(BaseHedgeFundRequest): start_date: str end_date: str initial_capital: float = 100000.0 ``` -------------------------------- ### Run AI Hedge Fund with Docker and Custom Ollama URL (Windows) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Windows, execute the AI hedge fund via Docker, connecting to an external Ollama instance via a provided base URL. Tickers must be specified. ```bash run.bat --ticker AAPL,MSFT,NVDA --ollama --ollama-base-url http://localhost:11434 main ``` -------------------------------- ### Run AI Hedge Fund Backtester with Docker (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Navigate to the docker directory and run the backtester script on Linux/macOS using Docker. Specify tickers for backtesting. ```bash cd docker ./run.sh --ticker AAPL,MSFT,NVDA backtest ``` -------------------------------- ### Example: Parsing Tickers Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Demonstrates the usage of the parse_tickers function with a sample comma-separated string and with a None value, showing the expected list output. ```python from src.cli.input import parse_tickers tickers = parse_tickers("AAPL, MSFT , NVDA") # Returns: ["AAPL", "MSFT", "NVDA"] tickers = parse_tickers(None) # Returns: [] ``` -------------------------------- ### GET /flows/{flow_id} Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Retrieves the full details of a specific flow using its unique ID. This is useful for loading and editing an existing flow. ```APIDOC ## GET /flows/{flow_id} ### Description Retrieves a specific flow by ID. ### Method GET ### Endpoint /flows/{flow_id} ### Parameters #### Path Parameters - **flow_id** (int) - Required - Flow database ID ### Response #### Success Response (200 OK) - Returns a `FlowResponse` object containing the full details of the flow. ### Status Codes - 404: Not Found - 500: Server error ``` -------------------------------- ### Backtest Event Types Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Defines the structure of Server-Sent Events (SSE) for the backtesting endpoint, including start, progress, and daily result events. ```python # Start event {"type": "start"} ``` ```python # Progress update (daily) { "type": "progress", "agent": "backtest", "status": "Processing 2024-01-15 (5/252)", "analysis": null } ``` ```python # Backtest result (daily) { "type": "progress", "agent": "backtest", "status": "Completed 2024-01-15 - Portfolio: $102,500.00", "analysis": { "date": "2024-01-15", "portfolio_value": 102500.0, "cash": 45000.0, "decisions": {...}, "executed_trades": {"AAPL": 100}, "analyst_signals": {...}, "long_exposure": 35000.0, "short_exposure": 0.0, "gross_exposure": 35000.0, "net_exposure": 35000.0 } } ``` -------------------------------- ### Run AI Hedge Fund with Docker, Dates, and Tickers (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Execute the AI hedge fund on Linux/macOS using Docker, specifying a date range for analysis and the tickers to monitor. ```bash ./run.sh --ticker AAPL,MSFT,NVDA --start-date 2024-01-01 --end-date 2024-03-01 main ``` -------------------------------- ### Loading Environment Variables in Python Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Demonstrates how to load environment variables from a .env file and access them using Python's os module. Includes a default value for the database URL. ```python from dotenv import load_dotenv import os # Load from .env file load_dotenv() # Access variables api_key = os.getenv("OPENAI_API_KEY") db_url = os.getenv("DATABASE_URL", "sqlite:///./hedge_fund.db") ``` -------------------------------- ### Configure API Keys in .env File Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/backend/README.md Edit the .env file to add your API keys for various services like OpenAI, Groq, and financial data providers. Replace 'your-api-key' with your actual keys. ```bash # For running LLMs hosted by openai (gpt-4o, gpt-4o-mini, etc.) OPENAI_API_KEY=your-openai-api-key # For running LLMs hosted by groq (deepseek, llama3, etc.) GROQ_API_KEY=your-groq-api-key # For getting financial data to power the hedge fund FINANCIAL_DATASETS_API_KEY=your-financial-datasets-api-key ``` -------------------------------- ### Run AI Hedge Fund with Docker and Custom Ollama URL (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md On Linux/macOS, run the AI hedge fund with Docker, pointing to an external Ollama server using a specified base URL. Tickers are required. ```bash ./run.sh --ticker AAPL,MSFT,NVDA --ollama --ollama-base-url http://localhost:11434 main ``` -------------------------------- ### Run AI Hedge Fund with Docker and Ollama (Linux/Mac) Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Run the AI hedge fund using Docker on Linux or macOS, enabling local LLM integration via Ollama. Specify tickers. ```bash ./run.sh --ticker AAPL,MSFT,NVDA --ollama main ``` -------------------------------- ### Run AI Hedge Fund with Docker Source: https://github.com/virattt/ai-hedge-fund/blob/main/docker/README.md Execute the AI Hedge Fund using the built Docker image. Specify the tickers you want to analyze. ```bash # Navigate to the docker directory first cd docker # On Linux/Mac: ./run.sh --ticker AAPL,MSFT,NVDA main ``` -------------------------------- ### GET /hedge-fund/agents Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/04-http-endpoints.md Retrieves a list of all available agents that can be used within the system. Each agent has a unique key, display name, description, and investing style. ```APIDOC ## GET /hedge-fund/agents ### Description Retrieves the list of available agents. ### Method GET ### Endpoint /hedge-fund/agents ### Response #### Success Response (200 OK) - **agents** (list) - A list of agent objects, each containing key, display_name, description, and investing_style. ### Response Example ```json { "agents": [ { "key": "warren_buffett", "display_name": "Warren Buffett", "description": "The Oracle of Omaha", "investing_style": "..." }, ... ] } ``` ### Status Codes - 200: Successful - 500: Server error ``` -------------------------------- ### Environment Variable Configuration: Groq Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/08-cli-input.md Sets the Groq API key and runs the main script specifying a Groq model and provider. ```bash # Use Groq export GROQ_API_KEY=gsk_... poetry run python src/main.py --ticker AAPL --model mixtral-8x7b-32768 --provider Groq ``` -------------------------------- ### Portfolio Class Initialization Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/03-backtesting-engine.md Initializes the Portfolio class to manage financial state. Set up with tracked tickers, initial cash, and margin requirements. ```python class Portfolio: def __init__( self, *, tickers: list[str], initial_cash: float, margin_requirement: float, ) -> None ``` -------------------------------- ### Run Hedge Fund Execution Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/01-core-api.md Executes the hedge fund trading workflow with specified tickers and configuration. Use this function to start the main trading process. ```python def run_hedge_fund( tickers: list[str], start_date: str, end_date: str, portfolio: dict, show_reasoning: bool = False, selected_analysts: list[str] = [], model_name: str = "gpt-4.1", model_provider: str = "OpenAI", ) -> dict ``` ```python from src.main import run_hedge_fund portfolio = { "cash": 100000.0, "margin_requirement": 0.0, "margin_used": 0.0, "positions": { "AAPL": {"long": 0, "short": 0, "long_cost_basis": 0.0, "short_cost_basis": 0.0, "short_margin_used": 0.0} }, "realized_gains": {"AAPL": {"long": 0.0, "short": 0.0}} } result = run_hedge_fund( tickers=["AAPL", "MSFT"], start_date="2024-01-01", end_date="2024-03-01", portfolio=portfolio, selected_analysts=["warren_buffett", "michael_burry"], model_name="gpt-4o", model_provider="OpenAI" ) ``` -------------------------------- ### Troubleshooting Database Connection Error Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/10-configuration-env.md Example error message and solution steps for a database connection error. Covers URL format, credentials, and SQLite directory checks. ```text sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL Solution: 1. Verify DATABASE_URL format 2. Check credentials if using remote database 3. For SQLite: ensure directory exists 4. Examples: - sqlite:///./hedge_fund.db - postgresql://user:pass@localhost/db ``` -------------------------------- ### PerformanceMetricsCalculator Initialization Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/03-backtesting-engine.md Initializes the PerformanceMetricsCalculator with optional annual trading days and risk-free rate. Use default values if not specified. ```python class PerformanceMetricsCalculator: def __init__( self, *, annual_trading_days: int = 252, annual_rf_rate: float = 0.0434 ) -> None ``` -------------------------------- ### Get List of Agents for API Responses Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/06-agent-system.md Returns a JSON-serializable list of agents, including their key, display name, description, and investing style. This is used for API responses. ```python def get_agents_list() -> List[Dict[str, str]]: """ Returns JSON-serializable list of agents. Returns: [ { "key": "warren_buffett", "display_name": "Warren Buffett", "description": "...", "investing_style": "..." }, ... ] """ ``` -------------------------------- ### Run Shell Script (Mac/Linux) Source: https://github.com/virattt/ai-hedge-fund/blob/main/app/README.md Execute the main shell script to set up and run the application on Mac or Linux systems. If permission is denied, ensure the script is executable. ```bash ./run.sh ``` ```bash chmod +x run.sh && ./run.sh ``` ```bash bash run.sh ``` -------------------------------- ### HedgeFundRequest Class Definition Source: https://github.com/virattt/ai-hedge-fund/blob/main/_autodocs/05-data-models.md Defines the HTTP request schema for running a single hedge fund simulation, including optional start and end dates and initial cash. ```python class HedgeFundRequest(BaseHedgeFundRequest): end_date: Optional[str] = Field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d")) start_date: Optional[str] = None initial_cash: float = 100000.0 def get_start_date(self) -> str: """Calculate start date if not provided""" ```