Skip to content

digantk31/Alpha-Long-Short

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Alpha-Based Long-Short Trading Strategy

A sophisticated quantitative trading strategy implemented in Python that generates alpha by going long on stocks expected to outperform and short on those expected to underperform.

🎯 Project Objective

(From Original Requirements)

Create a quantitative trading strategy that maintains Dollar-Neutrality and generates Alpha using a defined universe of 10 large-cap US stocks.

Data Collection

  • Source: Yahoo Finance (yfinance).
  • Universe: AAPL, MSFT, AMZN, GOOGL, META, TSLA, NVDA, JPM, JNJ, WMT.
  • History: 5 Years of Daily OHLCV + Fundamental Data.

Alpha Signal Logic

The strategy combines three distinct alpha signals:

  1. Momentum: 20-day returns (Ranked High to Low).
  2. Mean Reversion: Deviation from 50-day MA (Oversold = Buy).
  3. Volatility: 30-day historical volatility (Lower volatility = Preferred).

Optimization: We used Walk-Forward Analysis to determine the optimal weights for these signals:

  • Momentum: 61%
  • Mean Reversion: 23%
  • Volatility: 16%

Portfolio Construction

  • Long: Top 3 Ranked Stocks.
  • Short: Bottom 3 Ranked Stocks.
  • Rebalancing: Monthly.
  • Regime Filter: Strategies switch to Long-Only during strong Bull Markets (SPY > MA200) to mitigate negative beta exposure.

Risk Management

  • Stop-Loss: -10% per individual position.
  • Dollar-Neutral: Equal exposure to Long and Short sides (default mode).

πŸ› οΈ Installation

  1. Clone the repository:

    git clone https://github.com/digantk31/Alpha-Long-Short.git
    cd Alpha-Long-Short
  2. Set up Virtual Environment: It is recommended to use a virtual environment to manage dependencies.

    # Create virtual environment
    python -m venv venv
    
    # Activate virtual environment (Windows)
    venv\Scripts\activate
    
    # Activate virtual environment (Mac/Linux)
    # source venv/bin/activate

    (You should see (venv) appear in your command prompt)

    To Deactivate: Simply run deactivate when you are done.

  3. Install Dependencies:

    pip install -r requirements.txt

πŸš€ How to Run

1. Run Strategy (Recommended)

Executes the full pipeline: Data Collection -> Signal Generation -> Backtesting -> Optimization Analysis -> Performance Reporting.

python main.py

Note: This includes the Bonus Task (Walk-Forward Optimization) which creates the "winning weights" analysis.

2. Fast Run (Skip Optimization)

If you only want to run the backtest without the time-consuming optimization step:

python main.py --no-optimize

πŸ“Š Performance Output

The strategy generates detailed visualizations in the output/ directory:

Cumulative Returns vs S&P 500

Cumulative Returns

Strategy Drawdown

Drawdown

Signal Contribution Analysis

Signal Contribution

Monthly Returns Heatmap

Heatmap


οΏ½ Mathematical Formulas

Alpha Signal Calculations

1. Momentum Signal (20-day Returns)

Momentum = (Price_today - Price_20_days_ago) / Price_20_days_ago

         P_t - P_{t-20}
Mom_t = ─────────────────
            P_{t-20}

Higher momentum β†’ Higher rank β†’ BUY signal

2. Mean Reversion Signal (50-day MA Deviation)

MA_50 = (1/50) Γ— Ξ£ P_{t-i}  for i = 0 to 49

Deviation = (Price - MA_50) / MA_50

Mean_Reversion = -Deviation

Price below MA β†’ Positive signal β†’ BUY (expect bounce back)

3. Volatility Signal (30-day Historical Volatility)

Daily_Return = (P_t - P_{t-1}) / P_{t-1}

Οƒ_30 = StdDev(Daily_Returns over 30 days)

Annualized_Volatility = Οƒ_30 Γ— √252

Volatility_Signal = -Annualized_Volatility

Lower volatility β†’ Higher score β†’ Preferred

4. Z-Score Normalization (Applied to Each Signal)

         X - ΞΌ
Z = ───────────
         Οƒ

Where: ΞΌ = mean across all stocks, Οƒ = standard deviation

5. Combined Alpha Score

Alpha = (0.61 Γ— Momentum_Z) + (0.23 Γ— MeanRev_Z) + (0.16 Γ— Volatility_Z)

Performance Metrics

Sharpe Ratio

              R_p - R_f
Sharpe = ─────────────────
              Οƒ_p

Where:
  R_p = Annualized portfolio return
  R_f = Risk-free rate (2%)
  Οƒ_p = Annualized volatility

Maximum Drawdown

Drawdown_t = (Peak_t - Value_t) / Peak_t

Max_Drawdown = min(Drawdown_t) over all t

Alpha (Jensen's Alpha)

Ξ± = R_p - [R_f + Ξ² Γ— (R_m - R_f)]

Where:
  R_m = Market (benchmark) return
  Ξ² = Portfolio beta

Beta

        Cov(R_p, R_m)
Ξ² = ─────────────────────
        Var(R_m)

Portfolio Weights

Dollar-Neutral Mode (Default)

Long_Weight = 0.50 / n_long = 0.50 / 3 β‰ˆ 16.67% per stock
Short_Weight = -0.50 / n_short = -0.50 / 3 β‰ˆ -16.67% per stock

Bull Market Mode (SPY > 200-day MA)

Long_Weight = 1.00 / n_long = 1.00 / 3 β‰ˆ 33.33% per stock
Short_Weight = 0%

Transaction Costs

Cost = Trade_Value Γ— 0.0010  (10 basis points)

πŸ“ Code Structure

  • main.py: Entry point. Orchestrates the entire workflow.
  • quant_strategy/:
    • data_collector.py: Fetches historical data.
    • alpha_signals.py: Logic for Momentum, Mean Reversion, and Volatility.
    • portfolio.py: Ranking and weighting logic (including Regime Filter).
    • backtester.py: Event-driven simulation engine.
    • risk_manager.py: Stop-loss and position sizing.
    • performance.py: Metrics and plotting.
    • optimizer.py: Walk-Forward Analysis logic.

About

A Python trading bot that combines momentum, mean reversion, and volatility signals to run a long-short strategy. Includes a custom walk-forward optimizer to automatically tune the model as market conditions change.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages