Skip to content

shuoguo/Free_US_Investment_Agent_System

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Free US Investment Agent System ๐Ÿš€

A sophisticated AI-powered investment agent system for US stock market analysis and trading decisions, leveraging yfinance for market data and AlphaVantage for news sentiment analysis.

๐ŸŒ English | ็ฎ€ไฝ“ไธญๆ–‡

๐Ÿ›ก๏ธ Disclaimer

This project is for educational and research purposes only.

  • Not intended for real trading or investment
  • No warranties or guarantees provided
  • Past performance does not indicate future results
  • Creator assumes no liability for financial losses
  • Consult a financial advisor for investment decisions

By using this software, you agree to use it solely for learning purposes.

โœจ Features

  • Real-time US stock market data analysis using yfinance
  • News sentiment analysis through AlphaVantage API
  • AI-powered trading decision making
  • Comprehensive backtesting capabilities
  • Detailed reasoning for investment decisions
  • Support for multiple trading strategies

๐Ÿ—๏ธ System Architecture

The system employs multiple AI agents working together to make investment decisions:

graph TD
    MD[Market Data Agent] --> TA[Technical Analyst]
    MD --> FA[Fundamentals Analyst]
    MD --> SA[Sentiment Analyst]
    TA --> RM[Risk Manager]
    FA --> RM
    SA --> RM
    RM --> PM[Portfolio Manager]
    PM --> Decision[Final Decision]
Loading

Agent Descriptions

  1. Market Data Agent

    • Gathers historical price data from yfinance
    • Collects financial metrics and statements
    • Preprocesses data for other agents
  2. Technical Analyst

    • Analyzes price trends and patterns
    • Calculates technical indicators
    • Generates technical trading signals
  3. Fundamentals Analyst

    • Evaluates company financial health
    • Analyzes growth metrics
    • Provides fundamental analysis signals
  4. Sentiment Analyst

    • Fetches news from AlphaVantage
    • Analyzes news sentiment using Gemini
    • Generates sentiment-based signals
  5. Risk Manager

    • Integrates signals from all analysts
    • Evaluates potential risks
    • Sets position limits
    • Provides risk-adjusted recommendations
  6. Portfolio Manager

    • Makes final trading decisions
    • Manages position sizing
    • Balances risk and reward
    • Generates executable orders

Workflow

  1. Market Data Agent collects all necessary data
  2. Three analysts (Technical, Fundamental, Sentiment) work in parallel
  3. Risk Manager combines and evaluates all signals
  4. Portfolio Manager makes the final decision

๐Ÿ“ Project Structure

Free_US_Investment_Agent_System/
โ”œโ”€โ”€ src/                    # Source code
โ”‚   โ”œโ”€โ”€ agents/            # AI agents implementation
โ”‚   โ”œโ”€โ”€ tools/             # Utility tools
โ”‚   โ”œโ”€โ”€ utils/             # Helper functions
โ”‚   โ”œโ”€โ”€ data/              # Data storage
โ”‚   โ”œโ”€โ”€ img/               # Image resources
โ”‚   โ”œโ”€โ”€ backtester.py      # Backtesting implementation
โ”‚   โ”œโ”€โ”€ main.py            # Main application entry
โ”‚   โ””โ”€โ”€ test_*.py          # Test files
โ”œโ”€โ”€ logs/                  # Application logs
โ”œโ”€โ”€ .env.example          # Environment variables template
โ”œโ”€โ”€ pyproject.toml        # Poetry dependency management
โ”œโ”€โ”€ poetry.lock          # Poetry lock file
โ””โ”€โ”€ LICENSE              # MIT License

Logs and Data

The system generates two types of logs:

  • api_calls_[date].log: Records all API calls and their responses
  • backtest_[ticker]_[date]_[start]_[end].log: Records backtesting results and analysis

The system stores data in JSON format:

  • News data: src/data/stock_news/[ticker]/[date]_news.json (Note: The date in filename represents the day before the analysis date, as we use historical news to make current day's decisions)
{
  "date": "2024-12-10",
  "news": [
    {
      "title": "Tesla Stock Surges Post-Trump Win",
      "content": "Musk-Trump ties and autonomous driving growth...",
      "publish_time": "2024-12-10 20:05:00",
      "source": "Zacks Commentary",
      "url": "https://www.zacks.com/..."
    }
  ]
}
  • Sentiment cache: src/data/sentiment_cache.json
{
  "2024-12-09": 0.1, // Sentiment score: -1 (very negative) to 1 (very positive)
  "2024-12-10": 0.6
}

๐Ÿ“‹ Prerequisites

  • Python 3.11
  • Poetry for dependency management
  • AlphaVantage API key (Get your free API key from AlphaVantage)
    • Note: Free API key has a limit of 25 requests per day for news data
  • Gemini API key (Get your free API key from Google AI Studio)

โš ๏ธ Important Notes

The investment strategy implemented in this system is for educational purposes only. Users are encouraged to:

  • Develop and implement their own trading strategies
  • Customize the analysis parameters
  • Modify the decision-making logic
  • Test thoroughly before any real trading

๐Ÿ”ง Installation

  1. Install Poetry:

Windows (PowerShell)

(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -

Unix/macOS

curl -sSL https://install.python-poetry.org | python3 -
  1. Clone the repository:
git clone https://github.com/24mlight/Free_US_Investment_Agent_System.git
cd Free_US_Investment_Agent_System
  1. Install dependencies:
poetry install
  1. Set up your environment variables:

You can set up your environment variables in two ways:

a) Directly edit the .env file (Recommended):

cp .env.example .env

Then edit the .env file:

ALPHA_VANTAGE_API_KEY=your_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_MODEL=gemini-1.5-flash

b) Via command line:

Unix/macOS:

export ALPHA_VANTAGE_API_KEY='your_api_key_here'
export GEMINI_API_KEY='your_gemini_api_key_here'
export GEMINI_MODEL='gemini-1.5-flash'

Windows PowerShell:

$env:ALPHA_VANTAGE_API_KEY='your_api_key_here'
$env:GEMINI_API_KEY='your_gemini_api_key_here'
$env:GEMINI_MODEL='gemini-1.5-flash'

๐Ÿš€ Usage

Real-time Analysis

The system predicts trading decisions for the next trading day based on current market data and historical news:

  1. Basic Usage
poetry run python src/main.py --ticker TSLA
  1. Show Detailed Analysis
poetry run python src/main.py --ticker TSLA --show-reasoning
  1. Custom Date and News Analysis
poetry run python src/main.py --ticker TSLA --show-reasoning --end-date 2024-12-13 --num-of-news 5

Parameters:

  • --ticker: Stock symbol (e.g., TSLA for Tesla)
  • --show-reasoning: Display AI reasoning for decisions
  • --end-date: The date for which to predict next day's trading decision (YYYY-MM-DD format)
  • --num-of-news: Number of historical news articles to analyze (default: 5, max: 100)
  • --initial-capital: Initial cash amount (optional, default: 100,000)

Backtesting

To run backtesting analysis:

poetry run python src/backtester.py --ticker TSLA --start-date 2024-12-10 --end-date 2024-12-17 --num-of-news 5

Parameters:

  • --ticker: Stock symbol
  • --start-date: Backtesting start date (YYYY-MM-DD format)
  • --end-date: Backtesting end date (YYYY-MM-DD format)
  • --num-of-news: Number of news articles to analyze (default: 5, max: 100)
  • --initial-capital: Initial cash amount (optional, default: 100,000)

Output Description

The system will output:

  1. Fundamental analysis results
  2. Technical analysis results
  3. Sentiment analysis results
  4. Risk management assessment
  5. Final trading decision

When using --show-reasoning, you'll see detailed analysis from each agent.

Example Output:

{
  "action": "buy",
  "quantity": 100,
  "confidence": 0.75,
  "agent_signals": [
    {
      "agent": "Technical Analysis",
      "signal": "bullish",
      "confidence": 0.8
    },
    {
      "agent": "Sentiment Analysis",
      "signal": "neutral",
      "confidence": 0.6
    }
  ],
  "reasoning": "Technical indicators show strong upward momentum..."
}

๐Ÿ“Š Results

Here's an example of our backtesting results:

Backtesting Results

๐Ÿ“„ License

This project is licensed under the MIT License.

๐Ÿ™ Acknowledgments

This project is modified from ai-hedge-fund. We sincerely thank the original authors for their excellent work and inspiration.

Additional acknowledgments:

โ˜• Support the Project

If you find this project helpful, consider buying me a coffee!

Buy Me a Coffee

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 80.2%
  • PowerShell 13.7%
  • Roff 2.9%
  • C 2.5%
  • Batchfile 0.7%