An automated, AI-powered portfolio manager designed to optimize your investments, monitor the market, and execute trades via Alpaca. Combining mathematical precision (Modern Portfolio Theory) with LLM-based reasoning (Gemini), it allows for a "Human-in-the-Loop" automated investing experience.
The agent doesn't just look at prices; it reads the news.
- Market Intelligence: Fetches live headlines from BBC World and Yahoo Finance.
- Context Awareness: Uses Gemini AI to calculate real-time risk scores (0-10) for:
- Global Conflict (Protects Defense stocks like LMT, RTX)
- Inflation Trend (Protects Energy/Real Assets like XOM, CVX)
- Economic Instability (Protects Recession Shields like KO, PG, JNJ)
- Thesis Protection: If the world is dangerous, the agent refuses to sell your insurance assets, even if they are up.
- Anti-Casino Constraint: In Conservative mode, the agent is mathematically blocked from buying high-volatility assets (>35% Ann. Vol) like Crypto or Meme stocks.
- Core Preservation: Strict constraints prevent "dumping" your long-term winners. It forces the optimizer to build around your core positions.
Instead of executing blindly at market prices, Aegis computes 10-day forward volatility and drift forecasts.
- Dynamic Limits: Calculates the statistically probable "local low" for Buys, and "local high" for Sells individually for each stock based on its historical variance.
- Good-Till-Cancelled (GTC): Orders sit patiently on the books waiting for the perfect technical entry or exit within your 2-week execution block.
- Bi-Weekly Checkups: Runs optimization to keep your portfolio aligned with your risk profile.
- Executive Summaries: All rebalances and investment reports are generated into executive, highly scannable HTML emails featuring bolded mathematical rationales, tables grouping holds by sector, and detailed news summaries.
- Tax-Awareness: The AI Advisor explains why a trade is happening, warning you if a sale might trigger a tax event but is necessary for risk reduction.
- Auto-Monitoring: Checks your portfolio every morning.
- Aegis Masterclass (V3): Generates a highly personalized, daily educational curriculum. The agent maintains a persistent topic memory to build a progressive syllabus over time, natively formats math using LaTeX blocks, and curates reading lists.
- Dynamic Persona: Analysis is tailored explicitly to your demographic and risk profile.
- Smart Alerts & Autonomous Action: Sends an email ONLY if a stock moves >10% intraday. It then automatically pivots into an emergency rebalance to address the high volatility, generating a specialized 🚨 Volatility Rebalance Report directly to your inbox detailing whether it bought the dip or legally held the asset as insurance.
Developers and users can monitor the agent's performance in terms of raw trade outputs and portfolio metrics:
- FIFO Trade Matching: Pairs down historical
FILLactivities into individual closed trades to compute exact Win Rates and Profit Factors. - Money-Weighted Returns (IRR): Computes annualized Internal Rate of Return (IRR) to correctly evaluate performance while adjusting for deposits/withdrawals.
- Risk Metrics: Calculates Annualized Sharpe Ratio, Annualized Sortino Ratio, Daily Volatility, and Maximum Drawdown.
- Reporting & Visualization: Generates terminal dashboards, Markdown reports (
data/performance_report.md), and matplotlib equity curve comparison charts with drawdowns (data/performance_chart.png) along with individual trade returns and symbol PnL contributions (data/trade_analysis_chart.png).
The agent runs autonomously in the cloud via GitHub Actions schedulers:
- Daily Watchdog: Checks your positions every day at 4:30 PM. Alerts you only if a stock moves >10%.
- Bi-Weekly Tactical Rebalance: Reminds you every two weeks to realign your portfolio.
- Monthly Investment Day: Reminds you on the 1st of the month to deploy new capital.
- All AI communication is sent beautifully formatted directly to your inbox.
- Supports native LaTeX rendering via CodeCogs, macro-sector tables, conditional green/red market badging, and emojis.
Follow these steps to deploy Aegis as your personal autonomous investment agent.
git clone https://github.com/medhansh29/Investment_Agent.git
cd Investment_Agent
pip install -r requirements.txtAegis relies on three free services to operate. You must obtain the following keys:
- Alpaca Trading API (Broker):
- Go to the Alpaca Dashboard.
- Sign up and generate your Paper Trading API Key and Secret Key. Use Paper keys first to safely test the agent with play money!
- Google Gemini (AI Brain):
- Medhansh will provide you with the shared
GEMINI_API_KEYto use.
- Medhansh will provide you with the shared
- Gmail SMTP (Email Alerts):
- You need an App Password to allow the agent to send you Masterclass emails.
- Go to your Google Account -> Security -> 2-Step Verification -> App Passwords.
- Create a new App Password named "Aegis". It will be a 16-character string.
Copy the provided template files to create your personal local configuration.
Environment Variables:
cp .env.example .envOpen .env and paste the exact keys you generated in Step 2.
User State & Portfolio Memory:
cp data/user_state.example.json data/user_state.jsonOpen data/user_state.json and configure your name, email, baseline monthly_investment (e.g., $1000), and your universe of stock tickers you want the agent to track.
To have the agent run in the background 24/7 without keeping your computer on, simply push it to a private GitHub repository!
- Go to your repository Settings -> Secrets and variables -> Actions.
- Add the following New repository secrets:
ALPACA_API_KEYALPACA_SECRET_KEYGEMINI_API_KEYSMTP_EMAIL(Your Gmail address)SMTP_PASSWORD(Your 16-digit App Password)
- Under the Actions tab, ensure workflows are enabled. The
.github/workflows/cron jobs will now automatically run the Daily Watchdog, Bi-Weekly Rebalance, and Monthly Investment loops.
You can interact with the agent manually using the helper script in the scripts/ folder:
The standard way to run the agent manually.
# Verify and execute trades (Bi-Weekly Rebalance)
./scripts/run_agent.sh interactive rebalance
# Deploy monthly capital (Monthly Invest)
./scripts/run_agent.sh interactive invest
# Choose mode interactively
./scripts/run_agent.sh interactiveSimulate the automated alerts (sends actionable notifications/emails):
./scripts/run_agent.sh rebalance # Triggers Bi-Weekly Alert
./scripts/run_agent.sh invest # Triggers Monthly Alert
./scripts/run_agent.sh daily # Runs Daily Watchdog CheckTo evaluate the agent's performance and output reports:
# Run analysis on live Alpaca Paper/Live account
python3 scripts/analyze_performance.py
# Run analysis offline using local CSV cached data
python3 scripts/analyze_performance.py --use-csvThe project follows a modular Source Layout:
src/: Source Codecore/: The Brain (main.py,config.py,state_manager.py)strategies/: The Math (portfolio_optimizer.py)integrations/: The Connections (alpaca_client.py,gemini_client.py)utils/: Helpers (notifications,templates,performance_analyzer.py)
scripts/: Automation Scriptsrun_agent.sh: Main entry point helper.analyze_performance.py: Performance analysis and reporting script.install_cron.sh: Setup script for automation.
data/: Storageuser_state.json: Portfolio history and settings.performance_report.md: Generated report (git ignored).performance_chart.png: Generated equity curve and drawdown chart (git ignored).trade_analysis_chart.png: Generated closed trade distribution and realized PnL contribution chart (git ignored).
Disclaimer: This is an automated trading tool. Use at your own risk. Paper trading is recommended for testing.