📈 TSLA Mean Reversion

Enhanced Multi-Signal Mean Reversion on TSLA — Alpaca Paper Account · Extended Hours


● Paper Trading  |  📈 Long / Mean Reversion  |  🕐 Extended Hours

📡 Strategy Overview

A mean reversion equity strategy that buys TSLA when multiple indicators signal an oversold extreme and exits when price reverts toward its mean. The script runs a continuous polling loop every 60 seconds during the extended session (4:00 AM – 8:00 PM ET) and uses the Alpaca market calendar to automatically skip weekends and holidays.

The TSLA version uses a slightly higher RSI entry threshold (35 vs 30 for SPY) and a weighted confirmation score of ≥ 1.5 before entering — reflecting TSLA’s higher individual-stock volatility. Maximum shares held at any time: 100. All orders are limit orders at the current bid (sells) or ask (buys) with extended_hours=True.

Parameters Summary

ParameterValueDescription
TickerTSLAUnderlying equity
Bar size1-minute barsGranularity for all indicators
RSI period14Look-back window
Entry RSI threshold< 35Oversold entry
Exit RSI threshold> 55Mild overbought exit
Position size95% of cashPer entry
Max shares100Cap across all entries
Stop-loss0.5%Below weighted avg entry
Session hours4:00 AM – 8:00 PM ETExtended hours
Poll interval60 sContinuous loop during session
Order typeLimitBid for sells, ask for buys

Entry Logic — BUY (when below max shares)

An entry is triggered when RSI(14) < 35 (required) and confirmation score ≥ 1.5:

SignalScoreCondition
MACD ↑+1.0MACD histogram rising vs prior bar
BB touch+1.0Price ≤ lower Bollinger Band (2 std below 20-bar MA)
BB mid+0.5Price ≤ middle Bollinger Band (below mean)
Volume+1.0Current volume ≥ 0.5× its 20-bar MA
shares_to_buy = int((cash * 0.95) // current_price)
shares_to_buy = min(shares_to_buy, MAX_SHARES − current_qty)  # cap at 100 total

Exit Logic — SELL (when long, ANY of)

TriggerCondition
Stop-lossPrice ≤ entry × 0.995 (−0.5%)
RSI overboughtRSI > 55
BB upperPrice ≥ upper Bollinger Band
MACD fadingMACD histogram falling AND RSI > 55

🧮 Technical Indicators

RSI (Relative Strength Index)

rsi = 100 − (100 / (1 + avg_gain / avg_loss))    # EWM, period=14

MACD

macd_line   = EMA(close, 12) − EMA(close, 26)
signal_line = EMA(macd_line, 9)
histogram   = macd_line − signal_line

Bollinger Bands

middle = SMA(close, 20)
upper  = middle + 2.0 × std(close, 20)
lower  = middle − 2.0 × std(close, 20)

Volume MA

20-bar SMA of volume. Entry requires current volume ≥ 0.5× this average (VOLUME_MULTIPLIER=0.5).

⚙️ Configuration Reference

VariableDefaultDescription
SYMBOLTSLATicker
RSI_PERIOD14RSI look-back
RSI_OVERSOLD35Entry threshold
RSI_OVERBOUGHT55Exit threshold
POSITION_SIZE_PCT0.95Cash fraction per entry
MAX_SHARES100Max total shares held
STOP_LOSS_PCT0.0050.5% stop-loss
LOOKBACK_DAYS3Calendar days of bars
INTERVAL_SECONDS60Poll interval
TRADING_START_HOUR4Session start (ET)
TRADING_END_HOUR20Session end (ET)
VOLUME_MULTIPLIER0.5Volume gate fraction
USE_PAPERTruePaper vs live trading

🕐 Schedule & Execution

EventTime (ET)Days
Session start4:00 AMMon–Fri
Session end8:00 PMMon–Fri
Poll intervalEvery 60 sDuring session
Stale order cancelStart of every pass
Market calendar refreshOnce per calendar day

Each pass: cancel unfilled limit order → fetch 1-min bars (3 days) → compute indicators → check exit → check entry.

📋

Credentials from Supabase

Trading keys loaded from alpaca table (acctname = 'Aiv010'); data keys from data_key table (name = 'DanSavage1P1'). Connection details read from strategies-single/.env.

⚠️ Risk Assessment

Stop-Loss

0.5%

Max Position Size

95% of cash

Max Shares

100

Overnight Risk

Extended hrs

Order Type

Limit

Direction

Long only
⚠️

TSLA Volatility Risk

TSLA is significantly more volatile than SPY. Intraday moves of 5–10%+ are common around earnings, macro events, or news. The 0.5% stop-loss limits individual loss per trade but does not protect against gap opens or rapid moves that skip the limit price.

📋

Position Building

The strategy can add to an existing position on subsequent signals up to MAX_SHARES=100. Weighted average entry price is maintained across adds. All shares are sold together on any exit trigger.

🛠️ Prerequisites & Usage

Activate Virtual Environment & Install

cd strategies-single
source ../.venv/bin/activate
pip install -r requirements.txt

Environment File — strategies-single/.env

SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-service-role-key

Run Live Trading

python mean_reversion_tsla.py

Run Persistently (screen)

screen -S tsla_mr
python mean_reversion_tsla.py
# Detach: Ctrl-A D    Reattach: screen -r tsla_mr

Logs are written to both stdout and strategies-single/logs/mean_reversion.log. Key log lines per pass include RSI, MACD histogram, Bollinger Bands, and P&L on exits.

⚠️

Paper Trading Only — Not Financial Advice

This strategy runs on an Alpaca paper trading account. Set USE_PAPER = False at your own risk. Past performance does not guarantee future results.

⚠️ Equities Permission Requirements (Alpaca)

This strategy trades TSLA multiple times a day and will trigger the Pattern Day Trader (PDT) flag, which requires you to maintain a balance of $25,000 in your account.

A pattern day trader is defined by FINRA as any trader who executes four or more day trades within five business days in a margin account, where those trades represent more than 6% of their total trading activity during that period. Once flagged, your account must maintain a minimum equity of $25,000 on any day you trade; failure to do so will restrict the account to closing transactions only.

💰

$25,000 Minimum Balance Required

Ensure your Alpaca paper account reflects at least $25,000 equity before running this strategy to avoid PDT restrictions during testing.