File size: 5,302 Bytes
d53dc44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# Automated Trading System

Production-grade automated stock trading bot with FinBERT sentiment analysis, technical indicators, risk management, and a live Rich terminal dashboard.

## Overview

This project is a fully automated, algorithmic trading bot designed to trade U.S. equities via the Alpaca API. It utilizes a hybrid approach, combining technical analysis (RSI, MACD, Bollinger Bands, VWAP) with AI-driven sentiment analysis (FinBERT + VADER) to generate trading signals. The system features a strict, 8-layer risk management pipeline to ensure capital preservation.

---

## πŸš€ Quick Start Guide

Follow these steps to download, configure, and run the project locally.

### 1. Download the Project
If you are downloading this from Hugging Face or GitHub, you can clone the repository or download the ZIP file and extract it.

`ash
git clone <your-repository-url>
cd trading_system

`



### 2. Set Up a Virtual Environment (Recommended)

It is highly recommended to run this bot inside a Python virtual environment to avoid dependency conflicts.



**On Windows:**

`ash

python -m venv .venv

.venv\Scriptsctivate

`



**On macOS/Linux:**

`ash

python3 -m venv .venv

source .venv/bin/activate

`



### 3. Install Requirements

Install all required Python packages using the provided 

equirements.txt file.



`ash

pip install -r requirements.txt

`



*(Optional)* For CUDA GPU support (highly recommended for faster FinBERT sentiment analysis):

`ash

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

`



### 4. Configure Your Environment

The bot requires an Alpaca account (Paper or Live) and a NewsAPI key to function.



1. Copy the example configuration file to create your active .env file:

   `ash

   # On Windows (Command Prompt/PowerShell)

   copy .env.example .env

   

   # On macOS/Linux

   cp .env.example .env

   `

2. Open the .env file in a text editor and fill in your API keys:

   - ALPACA_API_KEY & ALPACA_SECRET_KEY: Get these from your [Alpaca Dashboard](https://app.alpaca.markets). (Live keys start with AK, Paper keys start with PK).

   - ALPACA_BASE_URL: Use https://paper-api.alpaca.markets for paper trading, or https://api.alpaca.markets for live trading.

   - TRADING_MODE: Set to paper or live.
   - NEWS_API_KEY: Get this from [NewsAPI](https://newsapi.org).
   - *(Optional)* TELEGRAM_BOT_TOKEN & TELEGRAM_CHAT_ID: For mobile alerts.

### 5. Run the Bot
Once your .env file is configured, you can start the bot!

`ash
python main.py
`
*Note: The bot will automatically check if the market is open. If the market is closed, it will sleep until the next trading session.*

---

## πŸ“Š Backtesting

Before running the bot with real money, you should backtest the strategy against historical data.

`ash
# Run a backtest on specific symbols over a date range
python -m backtester.engine --symbol AAPL --start 2023-01-01 --end 2024-12-31
`
The backtester includes a realistic cost model (slippage, commissions) and utilizes a vectorized engine for fast execution.

---

## πŸ›‘οΈ Risk Management Pipeline

The bot will **never** place a trade without passing the strict 8-check risk pipeline:
1. **Safe Mode** β€” Auto-triggered on 3 consecutive broker API errors.
2. **Daily Loss** β€” Blocks all trades if the daily loss limit (e.g., ) is hit.
3. **Equity Drop** β€” Blocks trading if the account equity drops >5% from the start of the day.
4. **Consecutive Losses** β€” Halts trading for 30 minutes and halves position size after 3 consecutive losses.
5. **Profit Lock** β€” (Optional) Stops trading for the day after a specific profit target is hit to protect gains.
6. **Max Positions** β€” Hard cap on simultaneous open positions.
7. **PDT Compliance** β€” Prevents Pattern Day Trader flags on accounts under ,000.
8. **Overnight Protection** β€” Refuses new entries after 15:45 ET and force-closes positions before the bell.

---

## πŸ“ Architecture Overview

`	ext
trading_system/

β”œβ”€β”€ .env                 # Secret API keys and configuration

β”œβ”€β”€ main.py              # Main orchestrator / Entry point

β”œβ”€β”€ config.py            # Environment variable loader & validator

β”œβ”€β”€ contracts.py         # Cross-module typed interfaces (Pydantic)

β”œβ”€β”€ data/                # SQLite storage & Alpaca market data fetchers

β”œβ”€β”€ signals/             # Technical indicators (RSI, MACD, VWAP) & Sentiment (FinBERT)

β”œβ”€β”€ strategy/            # Trend-following, Mean Reversion, & Regime detection

β”œβ”€β”€ execution/           # Alpaca API wrapper, Risk limits, Order routing, Portfolio state

β”œβ”€β”€ monitoring/          # Rich terminal dashboard, Telegram alerts, & JSON logging

β”œβ”€β”€ backtester/          # Vectorized backtest engine & CSV reporting

└── tests/               # pytest test suite

`



## πŸ§ͺ Running Tests

To ensure everything is working correctly, you can run the test suite:

`ash

pytest tests/ -v

`



## Disclaimer

*This software is for educational and research purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. The authors and all affiliates assume no responsibility for your trading results.*