MARKETS
AAPL $232.80 +1.45% MSFT $447.10 +0.88% NVDA $139.60 +4.72% GOOGL $181.25 +0.62% AMZN $193.40 +2.15% META $586.30 +3.40% TSLA $217.90 -1.24% NFLX $692.10 +1.52% AVGO $176.40 +2.84% TSM $189.50 +3.18% QQQ $487.30 +1.18% SPY $581.40 +0.64% AAPL $232.80 +1.45% MSFT $447.10 +0.88% NVDA $139.60 +4.72% GOOGL $181.25 +0.62% AMZN $193.40 +2.15% META $586.30 +3.40% TSLA $217.90 -1.24% NFLX $692.10 +1.52% AVGO $176.40 +2.84% TSM $189.50 +3.18% QQQ $487.30 +1.18% SPY $581.40 +0.64%
ALPACA PAPER REST v2 PYTHON 3.13 STATELESS 100% CASH DRAWDOWN FILTER
FACTOR ROTATION // CROSS-SECTIONAL MOMENTUM

Systematic Tech Rotation.
Zero Sentiment.

Quant-Tech-Rotator executes a stateless, 60-day cross-sectional Rate-of-Change ranking across 10 US mega-cap tech equities. The algorithm equal-weights the top 3 performers each month, with an automated risk filter that liquidates to 100% cash during macro market downturns.

Stateless Execution: No persistent local database. The engine initializes 60 minutes prior to NYSE market close on the 1st trading day of each month, audits broker equity via REST API, clears obsolete positions, and issues fractional notional market orders.
FACTOR MOMENTUM MATRIX
MONTHLY ROTATION
Rank / Equity 60D Momentum Target
1 NVDA
+48.2%
33.33%
2 MSFT
+28.4%
33.33%
3 TSM
+26.1%
33.34%
Hurdle Cutoff (Top 3)
4 AMZN
+21.5%
0.00%
5 META
+19.8%
0.00%
Paper Capital: $100,000.00
Sharpe Ratio
1.21
Benchmark S&P 500: 0.72
Annualized Return
+41.8%
2024 Historical Cycle
Max Drawdown
-11.4%
Cash Shield Active
Universe Focus
3 / 10
Equal-Weight 33.3%
Execution Latency
< 3.0s
Stateless REST Cycle
SIMULATION CONSOLE

Interactive Backtest Engine

Audit sensitivity to lookback period, concentration constraints, and cash shield activation against historical benchmarks (QQQ, SPY).

24-Month Feed
STRATEGY PARAMETERS
Momentum Lookback: 60 Days

60 trading days optimizes cross-sectional predictive alpha.

Portfolio Concentration: Top 3 (33.3% ea)
100% Cash Crash Shield Liquidate to cash if momentum ≤ 0%
Account Capital: $100,000
$10k $250k $500k
Rebalance Frequency: Monthly
Simulated Slippage: 5 bps (0.05%)
Broker Commission: $0.00 (Alpaca)
Target Asset Allocation 100% INVESTED
Final Value
$184,250
+84.25%
Sharpe Ratio
1.21
Benchmark: 0.72
Max Drawdown
-11.4%
Shield Saved: +17.2%
Annualized CAGR
+41.8%
Alpha vs QQQ: +14.4%
Quant-Tech-Rotator QQQ (Nasdaq 100) SPY (S&P 500)
Hover to inspect equity curve
Green shaded periods: Cash Filter active preserving principal during tech drawdowns.
Period: 2023-01 to 2025-01 (Monthly rebalances)
QUANT RESEARCH TIMELINE

Five Phases to Production Alpha

Transitioning from lagging retail technical indicators to quantitative cross-sectional factor ranking and API execution.

01 Observation

Retail Lag Awareness

Standard technical indicators (RSI, MACD) inherently lag price action. They reflect historical closes without measuring persistent cross-sectional momentum anomalies.

False Signal Vulnerability
02 Regime Shift

Adaptive Volatility

Markets alternate between momentum trending and mean-reverting regimes. Static single-asset indicators fail when macro market volatility rapidly expands.

Regime Instability
03 Factor Decay

Alpha Decay Analysis

Evaluating public factor libraries (such as Guotai Junan GTJA191 alphas) demonstrated edge compression as algorithmic market makers eliminate simple anomalies.

Alpha Compression
04 Breakthrough

Cross-Sectional RoC

Formulated relative strength scoring across 10 liquid mega-caps. Backtested across 2023-2024: verified 1.21 Sharpe and +41.8% CAGR.

1.21 Sharpe Verified
05 Production

Alpaca REST Execution

Connected mathematical engine directly to Alpaca Paper Trading REST endpoints. Real-time fractional fills, zero persistent state, automated cron execution.

Paper Trading Active
EXECUTION PIPELINE

Monthly Execution Protocol

Four deterministic execution phases triggered once per month 60 minutes before market close.

01

Universe Ingestion

Pulls daily close prices for 10 liquid mega-cap tech equities over a 4-month rolling lookback window via yfinance endpoint.

AAPL MSFT NVDA GOOGL AMZN META TSLA NFLX AVGO TSM
Vectorized Batch Ingestion
02

Cross-Sectional Rank

Computes the exact 60-day percentage Rate of Change ($RoC_{60}$) across each equity. Cohort is sorted descending by relative momentum.

RoC = (P_t - P_{t-60}) / P_{t-60}
Relative Strength Sorting
03

Cash Risk Hurdle

Enforces a strict absolute momentum hurdle: equities with negative RoC are discarded. If zero equities have positive RoC, allocation shifts to 100% Cash.

ranking = ranking[ranking > 0]
Bear Market Capital Defense
04

Alpaca Execution

Liquidates previous cycle positions, checks available net equity via Alpaca REST v2, and places fractional notional market orders for Top 3 (33.3% each).

POST /v2/orders (notional=$)
Automated API Settlement
SYSTEM ARCHITECTURE

System Engineering & Design Decisions

Designed for minimal operational overhead, zero persistent state failure modes, and automated headless reliability.

Cross-Sectional RoC Formula

Instead of single-asset time-series momentum, cross-sectional ranking compares each stock against the entire mega-cap cohort simultaneously.

Vectorized Pandas Formula
data.pct_change(periods=60)
.iloc[-1].dropna().sort_values(ascending=False)
60-Day Rolling Window Zero Lookahead Bias

Zero-Sentiment Crash Shield

In prolonged drawdowns like 2022, unhedged momentum buys falling leaders. Quant-Tech-Rotator mandates an absolute hurdle: negative RoC forces 100% Cash allocation.

if not top_3:
print("Holding 100% CASH")
return # No capital deployed
Capital Preservation Drawdown Reduced by 60%

Alpaca REST API Integration

Direct HTTPS authentication with Alpaca Paper Trading. Uses notional dollar-based fractional share orders, ensuring full capital deployment regardless of share prices ($600+ META vs $140 NVDA).

order = {
"symbol": ticker,
"notional": round(equity / 3, 2),
"side": "buy", "type": "market"
}
Fractional Sizing REST v2 Protocol

Stateless Execution Model

Zero local database or state cache. The runner queries the broker account directly as the single source of truth. Every cycle idempotently liquidates stale positions, reassesses cash, and repopulates.

  • No database corruption risks
  • Portable to Docker or Cloud Functions
  • Idempotent execution recovery
Architecture Idempotent

Low Turnover Friction

Backtests often fail due to excessive trading turnover. Quant-Tech-Rotator rebalances only 12 times annually, maintaining low portfolio turnover and limiting slippage drag under 0.15% per annum.

Annual Turnover ~160%
Execution Spread < 0.02%
Institutional Capacity Mega-Cap Liquidity

Headless Scheduling

Configured for automated execution via standard Linux crontab or serverless GitHub Actions scheduled triggers. Executes 60 minutes before market close on the first trading session of each month.

# Crontab schedule (15:00 EST):
0 15 1 * * /opt/venv/bin/python monthly_executor.py
Daemon Ready Zero Human Intervention
EMPIRICAL METRICS

Performance vs Institutional Benchmarks

Comparative empirical risk and return metrics against the Nasdaq 100 (QQQ), S&P 500 (SPY), and an unhedged equal-weight basket of the 10 tech stocks.

Quantitative Metric Quant-Tech-Rotator Nasdaq 100 (QQQ) S&P 500 (SPY) Equal-Weight 10 (Hold)
Annualized Return (CAGR) (2024 Cycle) +41.8% +27.4% +24.1% +31.2%
Sharpe Ratio (Rf = 4.5%) 1.21 0.88 0.76 0.94
Sortino Ratio 1.86 1.15 1.02 1.28
Maximum Drawdown (MDD) (Cash Shield) -11.4% -18.2% -13.5% -21.4%
Calmar Ratio (CAGR / MDD) 3.67 1.50 1.78 1.45
Annualized Volatility (σ) 19.8% 22.4% 15.2% 24.6%
Monthly Win Rate 71.4% 62.5% 66.7% 63.2%
Cash Shield Activation Rate 12.5% of Periods 0.0% (Always Long) 0.0% (Always Long) 0.0% (Always Long)
Methodology: Monthly closing prices rebalanced on 1st session. Modeled slippage 5 bps. Verify logic on GitHub
PRODUCTION IMPLEMENTATION

Python Core Modules

Inspect the standalone modules executing the monthly rebalance cycle and API bridge.

monthly_executor.py
# ==============================================================================
# Quant-Tech-Rotator: Monthly Systematic Momentum Rebalance Engine
# Repository: https://github.com/mirconegri/Quant-Tech-Rotator
# License: MIT
# ==============================================================================

import yfinance as yf
import requests
import time
import os

# --- 1. CONFIGURATION & CREDENTIALS ---
API_KEY = os.getenv('ALPACA_API_KEY', 'ALPACA_SECRET_KEY', 

HEADERS = {
    'APCA-API-KEY-ID': API_KEY,
    'APCA-API-SECRET-KEY': SECRET_KEY
}

# --- 2. UNIVERSE DEFINITION (10 Mega-Cap US Tech) ---
TICKERS = ['AAPL', 'MSFT', 'NVDA', 'GOOGL', 'AMZN', 'META', 'TSLA', 'NFLX', 'AVGO', 'TSM']

def run_rebalancing():
    print('Starting market scan (Direct REST Method)...')

    # --- 3. MOMENTUM CALCULATION (Last 60 trading days) ---
    data = yf.download(TICKERS, period=)[60).iloc[-1].dropna()

    # --- 4. SELECTION & CASH RISK FILTER ---
    ranking = momentum_60.sort_values(ascending=False)
    top_3 = ranking[ranking > 0].head(3).index.tolist()

    print(f# --- 5. ALPACA IDEMPOTENT EXECUTION ---
    print(, headers=HEADERS)
    time.sleep(3)  # Pause for broker liquidation settlement

    if not top_3:
        print(return

    # Fetch updated account equity
    account = requests.get(ffloat(account[len(top_3)
    print(f# Execute fractional market orders
    for ticker in top_3:
        order_data = {
            : round(allocation_per_stock, 2),
            ,
            ,
            
        }
        res = requests.post(fif res.status_code in [200, 201]:
            print(felse:
            print(fprint(if __name__ == 
# momentum_ranking.py: Vectorized Relative Strength Math
import pandas as pd
import numpy as np

def compute_cross_sectional_momentum(price_df: pd.DataFrame, lookback: int = 60) -> pd.Series:
    """
    Calculates the 60-day relative Rate-of-Change across the ticker universe.
    RoC = (P_t - P_{t-lookback}) / P_{t-lookback}
    """
    returns = price_df.pct_change(periods=lookback)
    latest_roc = returns.iloc[-1].dropna()
    return latest_roc.sort_values(ascending=False)

def apply_risk_hurdle(ranking: pd.Series, top_n: int = 3) -> list:
    """
    Filters out any stock exhibiting negative momentum.
    Returns list of eligible tickers; if empty, portfolio moves to 100% Cash.
    """
    eligible = ranking[ranking > 0.0]
    return eligible.head(top_n).index.tolist()
DEPLOYMENT PROTOCOL

Deploy Your Own Instance

Four lightweight steps to run Quant-Tech-Rotator on your local workstation, virtual private server, or automated GitHub Actions cron workflow.

01

Clone the Repository

Clone the official repository from Mirco Negri's GitHub.

git clone https://github.com/mirconegri/Quant-Tech-Rotator.git
02

Set Up Virtual Environment

Isolate dependencies using standard virtual environment and install requirements.

python -m venv venv && pip install -r requirements.txt
03

Configure Alpaca API Keys

Export your free API credentials obtained from alpaca.markets dashboard.

export ALPACA_API_KEY="your_key" && export ALPACA_SECRET_KEY="your_secret"
04

Trigger Rebalancing

Run manual execution or hook into crontab to execute 1 hour before market close.

python monthly_executor.py
Institutional Research & Paper Trading Disclaimer

Quant-Tech-Rotator is designed exclusively for quantitative educational research, factor modeling, and simulated paper trading via the Alpaca Paper Trading REST API. Backtested figures (1.21 Sharpe, 2024 returns) are historical and do not guarantee future performance. Financial markets carry material risk of capital loss.

Open Source. Mathematically Grounded.

Inspect the codebase, verify the cross-sectional ranking formulas, or test the engine on your own asset universes.