OHLC.dev editorialMARKET

Trading Events Intelligence: Python-Based US Market and Short Selling Analysis

Trading Events Intelligence integrates Python-based financial data collection, corporate-action monitoring, technical analysis, short-selling signal scoring, trade planning, historical backtesting, and interactive dashboard visualization for US equity markets.

November 23, 202639 min readRafatar
Trading Events Intelligence: Python-Based US Market and Short Selling Analysis

Financial market analysis requires more than observing changes in stock prices. Corporate actions, trading liquidity, price momentum, technical trends, and transaction-related risks can influence the quality of a trading decision. These factors are particularly important in short selling, because a short position may incur losses when the share price rises and may also involve borrowing costs, dividend obligations, margin requirements, and short-squeeze risk.

Corporate actions such as cash dividends and stock splits can affect the interpretation of price movements and the economics of an open short position. An approaching ex-dividend date deserves attention because a short seller may be responsible for compensating the lender for a dividend. A stock split can also require verification that historical price and volume data have been adjusted consistently.

Technical analysis provides another layer of information. Moving averages can describe trend direction, while the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Average True Range (ATR), relative volume, and price-support levels can help characterize momentum, volatility, and selling activity. No single indicator is sufficient to establish a reliable short-selling decision. A combined framework can provide a more structured screening process.

Backtesting offers a way to examine how a rule-based strategy would have behaved on historical observations. However, historical simulation does not guarantee future performance. Results depend on data quality, signal timing, execution assumptions, transaction costs, slippage, borrow fees, and the completeness of the historical dataset.

This article presents the Trading Events Intelligence framework, a Python-based analytical system designed to combine US equity market data, corporate-action monitoring, technical indicators, short-selling candidate scoring, trade planning, historical backtesting, event-study calculations, and an interactive web dashboard. The implementation uses the MarketFlow All-in-One Market Finance API through RapidAPI for dividend and stock-split events, Yahoo Finance data through yfinance for historical market prices, Pandas and NumPy for data processing, and Plotly and Streamlit for interactive visualization.

The project is configured for a short-term US equity workflow and uses a watchlist of large-cap, growth, financial, consumer, healthcare, energy, industrial, and other stocks. The script defines a six-month daily historical-price window, an initial capital assumption of USD 10,000, a one-percent risk budget per trade, and a maximum position exposure of two percent of capital. These values are configurable parameters, not recommendations for actual trading.

The framework is organized into five computational cells: project configuration, corporate-action data collection, US market data and technical analysis, the short-selling intelligence engine, and the interactive Streamlit dashboard. The main objective is to create a repeatable research workflow that brings event information and technical market conditions into one analytical environment.

2. Methodology

The system follows a sequential computational workflow. Each cell produces data or analytical outputs required by the next cell. The original Python implementation is reproduced in full in the code sections below. The code is retained as supplied; the article explains its functions and does not claim that a live execution or independent validation has been performed.

Cell

Main function

Primary output

Cell 1

Library imports and project configuration

Configuration variables and output directory

Cell 2

MarketFlow API and corporate-action processing

Dividend, split, and combined event datasets

Cell 3

US market data, quality checks, and technical indicators

Historical price data, market snapshot, bearish candidates

Cell 4

Short-selling scoring, trade planning, backtesting, and event study

Scanner, trade plans, backtest metrics, event-study results

Cell 5

Streamlit dashboard preparation and deployment

CSV datasets, Streamlit app, public tunnel URL

2.1. System Configuration and Project Parameters

The first cell imports the libraries required for HTTP requests, data manipulation, numerical calculations, historical market data retrieval, visualization, date handling, secure API-key input, and file management. The project is configured for the US market, with NYSE and NASDAQ as the intended exchange universe and a short-term trading style.

The RapidAPI key is entered through getpass, which avoids displaying the key as ordinary notebook output. The API host is configured as marketflow-all-in-one-market-finance-api.p.rapidapi.com. The script sets the event query window from 90 days before the execution date to 30 days after it. Historical stock data are requested for six months at a daily interval.

Risk and indicator parameters include an initial capital of USD 10,000, a one-percent risk allocation per trade, a two-percent maximum position-risk allocation, a 2:1 reward-to-risk ratio, a maximum of five open positions, RSI period 14, EMA periods 20 and 50, ATR period 14, and a 20-day volume reference. The code also creates the trading_events_data directory for generated outputs.

Code — Cell 1: Import Libraries and Project Configuration

# -*- coding: utf-8 -*-

"""Trading_Events_Intelligence_US_Short_Selling.ipynb

Automatically generated by Colab.

Original file is located at

https://colab.research.google.com/drive/1TPCBItosx4Og8d_DGD9Z_O4npjauGdQC

CELL 1. Import Library & Project Configuration

"""

# ============================================================

# TRADING EVENTS INTELLIGENCE

# CELL 1: IMPORT & CONFIGURATION

# ============================================================

import os

import json

import time

import warnings

import requests

import pandas as pd

import numpy as np

import yfinance as yf

import plotly.express as px

import plotly.graph_objects as go

from datetime import datetime, date, timedelta

from getpass import getpass

from pathlib import Path

from IPython.display import display, HTML

warnings.filterwarnings("ignore")

pd.set_option("display.max_columns", 100)

pd.set_option("display.width", 200)

pd.set_option("display.float_format", "{:,.4f}".format)

# ------------------------------------------------------------

# PROJECT CONFIGURATION

# ------------------------------------------------------------

PROJECT_NAME = "Trading Events Intelligence"

MARKET = "US"

EXCHANGES = ["NYSE", "NASDAQ"]

TRADING_STYLE = "SHORT_TERM"

# API CONFIGURATION

RAPIDAPI_KEY = getpass("Masukkan RapidAPI Key: ")

RAPIDAPI_HOST = (

"marketflow-all-in-one-market-finance-api.p.rapidapi.com"

)

BASE_URL = f"https://{RAPIDAPI_HOST}"

HEADERS = {

"x-rapidapi-key": RAPIDAPI_KEY,

"x-rapidapi-host": RAPIDAPI_HOST

}

# DATE CONFIGURATION

START_DATE = (

date.today() - timedelta(days=90)

).isoformat()

END_DATE = (

date.today() + timedelta(days=30)

).isoformat()

# HISTORICAL DATA

PRICE_PERIOD = "6mo"

PRICE_INTERVAL = "1d"

# PORTFOLIO CONFIGURATION

INITIAL_CAPITAL = 10000

RISK_PER_TRADE = 0.01

MAX_POSITION_RISK = 0.02

RISK_REWARD_RATIO = 2.0

MAX_OPEN_POSITIONS = 5

# TECHNICAL INDICATORS

RSI_PERIOD = 14

EMA_FAST = 20

EMA_SLOW = 50

ATR_PERIOD = 14

VOLUME_PERIOD = 20

# MARKET SCANNER

MIN_PRICE = 5

MIN_AVG_VOLUME = 300000

MIN_RELATIVE_VOLUME = 1.5

MAX_RSI = 75

MIN_RSI = 40

# STORAGE

DATA_DIR = Path("trading_events_data")

DATA_DIR.mkdir(exist_ok=True)

print("=" * 65)

print("TRADING EVENTS INTELLIGENCE")

print("=" * 65)

print("Market:", MARKET)

print("Exchanges:", EXCHANGES)

print("Trading Style:", TRADING_STYLE)

print("Initial Capital: $", INITIAL_CAPITAL)

print("Project initialized successfully.")

"""CELL 2. MarketFlow API & Corporate Actions Intelligence"""

# ============================================================

2.2. Corporate-Action Data Collection and Normalization

The second cell defines a reusable MarketFlow request function. It sends date-range parameters and a pagination offset to the selected endpoint, checks the HTTP response, and returns JSON data. The extract_records() function recursively searches nested dictionaries and lists for record collections. The script then normalizes dividend and stock-split records into Pandas DataFrames. It attempts to identify fields such as ticker, ex-dividend date, record date, payment date, declaration date, dividend amount, currency, split effective date, and split ratio. The resulting dividend and split records are combined into a single corporate-action event table. Each event receives a day-distance value and a status label: historical, upcoming within 14 days, or upcoming. The implementation calls the endpoints dividens-events and splits-events; endpoint availability and response-field compatibility depend on the API service.

Code — CELL 2: Full Implementation

# TRADING EVENTS INTELLIGENCE

# CELL 2: MARKETFLOW API & CORPORATE ACTIONS

# ============================================================

# ------------------------------------------------------------

# 1. MARKETFLOW API REQUEST

# ------------------------------------------------------------

def marketflow_request(

endpoint,

start_date=START_DATE,

end_date=END_DATE,

skip=0

):

url = f"{BASE_URL}/{endpoint}"

params = {

"skip": skip,

"start_date": start_date,

"end_date": end_date

}

response = requests.get(

url,

headers=HEADERS,

params=params,

timeout=45

)

response.raise_for_status()

return response.json()

# ------------------------------------------------------------

# 2. JSON EXTRACTION

# ------------------------------------------------------------

def extract_records(payload):

candidates = []

def walk(obj):

if isinstance(obj, list):

if obj and all(

isinstance(x, dict)

for x in obj

):

candidates.append(obj)

for item in obj:

if isinstance(item, (dict, list)):

walk(item)

elif isinstance(obj, dict):

for value in obj.values():

if isinstance(value, (dict, list)):

walk(value)

if payload is None:

return []

walk(payload)

if candidates:

return max(

candidates,

key=len

)

if isinstance(payload, dict):

return [payload]

return []

# ------------------------------------------------------------

# 3. COLUMN DETECTION

# ------------------------------------------------------------

def find_column(df, aliases):

columns = {

str(col).lower(): col

for col in df.columns

}

for alias in aliases:

for lower_name, original_name in columns.items():

if (

lower_name == alias

or lower_name.endswith("_" + alias)

):

return original_name

return None

# ------------------------------------------------------------

# 4. NORMALIZE DIVIDEND DATA

# ------------------------------------------------------------

def normalize_dividend(records):

if not records:

return pd.DataFrame()

df = pd.json_normalize(

records,

sep="_"

)

symbol_col = find_column(

df,

["symbol", "ticker", "stock_symbol"]

)

ex_date_col = find_column(

df,

["ex_dividend_date", "ex_date"]

)

record_date_col = find_column(

df,

["record_date"]

)

payment_date_col = find_column(

df,

["payment_date", "pay_date"]

)

announcement_col = find_column(

df,

["declaration_date", "announcement_date"]

)

amount_col = find_column(

df,

["dividend_amount", "amount", "cash_amount"]

)

currency_col = find_column(

df,

["currency", "currency_code"]

)

df["symbol"] = (

df[symbol_col].astype(str).str.upper().str.strip()

if symbol_col else None

)

def parse_date(col):

if col:

return pd.to_datetime(

df[col],

errors="coerce",

utc=True

).dt.tz_convert(None)

return pd.Series(

pd.NaT,

index=df.index

)

df["ex_date"] = parse_date(ex_date_col)

df["record_date"] = parse_date(record_date_col)

df["payment_date"] = parse_date(payment_date_col)

df["announcement_date"] = parse_date(announcement_col)

df["dividend_amount"] = (

pd.to_numeric(

df[amount_col].astype(str).str.replace(",", "", regex=False),

errors="coerce"

)

if amount_col else np.nan

)

df["currency"] = (

df[currency_col].astype(str)

if currency_col else None

)

return df

# ------------------------------------------------------------

# 5. NORMALIZE STOCK SPLIT DATA

# ------------------------------------------------------------

def normalize_splits(records):

if not records:

return pd.DataFrame()

df = pd.json_normalize(

records,

sep="_"

)

symbol_col = find_column(

df,

["symbol", "ticker", "stock_symbol"]

)

split_date_col = find_column(

df,

["effective_date", "execution_date", "split_date"]

)

ratio_col = find_column(

df,

["split_ratio", "ratio"]

)

df["symbol"] = (

df[symbol_col].astype(str).str.upper().str.strip()

if symbol_col else None

)

df["split_date"] = (

pd.to_datetime(

df[split_date_col],

errors="coerce",

utc=True

).dt.tz_convert(None)

if split_date_col else pd.NaT

)

df["split_ratio"] = (

df[ratio_col].astype(str)

if ratio_col else None

)

return df

# ------------------------------------------------------------

# 6. FETCH DIVIDEND EVENTS

# ------------------------------------------------------------

print("Fetching Dividend Events...")

dividend_raw = marketflow_request(

"dividens-events"

)

dividend_records = extract_records(

dividend_raw

)

dividend_df = normalize_dividend(

dividend_records

)

# ------------------------------------------------------------

# 7. FETCH STOCK SPLITS

# ------------------------------------------------------------

print("Fetching Stock Split Events...")

split_raw = marketflow_request(

"splits-events"

)

split_records = extract_records(

split_raw

)

split_df = normalize_splits(

split_records

)

# ------------------------------------------------------------

# 8. CORPORATE ACTION EVENT DATABASE

# ------------------------------------------------------------

dividend_events = pd.DataFrame()

if not dividend_df.empty:

dividend_events = pd.DataFrame({

"symbol": dividend_df["symbol"],

"event_kind": "DIVIDEND",

"event_date": dividend_df["ex_date"],

"event_value": dividend_df["dividend_amount"]

})

split_events = pd.DataFrame()

if not split_df.empty:

split_events = pd.DataFrame({

"symbol": split_df["symbol"],

"event_kind": "STOCK SPLIT",

"event_date": split_df["split_date"],

"event_value": split_df["split_ratio"]

})

all_events = pd.concat(

[dividend_events, split_events],

ignore_index=True

)

if not all_events.empty:

all_events["symbol"] = (

all_events["symbol"].fillna("").astype(str).str.upper().str.strip()

)

all_events["days_to_event"] = (

all_events["event_date"].dt.normalize()

- pd.Timestamp.today().normalize()

).dt.days

all_events["event_status"] = np.select(

[

all_events["days_to_event"].lt(0),

all_events["days_to_event"].between(0, 14),

all_events["days_to_event"].gt(14)

],

[

"HISTORICAL",

"UPCOMING 14 DAYS",

"UPCOMING"

],

default="UNKNOWN"

)

# ------------------------------------------------------------

# 9. CORPORATE ACTION SUMMARY

# ------------------------------------------------------------

print("\n" + "=" * 60)

print("CORPORATE ACTION INTELLIGENCE")

print("=" * 60)

print("Dividend Records:", len(dividend_df))

print("Stock Split Records:", len(split_df))

print("Total Corporate Actions:", len(all_events))

if not all_events.empty:

display(

all_events.sort_values(

"event_date",

ascending=False,

na_position="last"

).head(30)

)

print("\nCELL 2 COMPLETED.")

"""CELL 3. US Market Data & Advanced Technical Analysis"""

# ============================================================

2.3. US Market Data, Quality Control, and Technical Indicators

The third cell defines a watchlist of US-listed stock symbols across several market sectors. It downloads six months of daily OHLCV data through yfinance. The download function checks for empty results, handles MultiIndex columns, orders the observations by date, removes duplicate dates, and excludes invalid or incomplete rows. The quality-control function requires at least 60 observations, positive OHLC prices, a valid high-low relationship, non-negative volume, a latest close of at least USD 5, average 20-day volume of at least 300,000 shares, and average dollar volume of at least USD 5 million. It also excludes symbols with repeated extreme daily price changes. Accepted price histories are processed to calculate moving averages, RSI, MACD, ATR, relative volume, dollar volume, a cumulative VWAP proxy, Bollinger Bands, return horizons, price gaps, prior support and resistance levels, and bearish-condition flags. The latest observations are assembled into a market snapshot. A preliminary bearish-candidate list is created when at least one of bearish trend, bearish momentum, or support breakdown is present.

Code — CELL 3: Full Implementation

# TRADING EVENTS INTELLIGENCE

# CELL 3: US MARKET DATA & SHORT SELLING INTELLIGENCE

# ============================================================

# ------------------------------------------------------------

# 1. US STOCK UNIVERSE

# ------------------------------------------------------------

DEFAULT_WATCHLIST = [

# Technology

"AAPL", "MSFT", "NVDA", "AMD", "AVGO",

"AMZN", "META", "GOOGL", "ORCL", "CRM",

"ADBE", "NFLX", "INTC", "QCOM", "MU",

"AMAT", "TSM", "ARM", "SMCI", "PLTR",

# High beta / growth

"TSLA", "COIN", "MSTR", "HOOD", "SOFI",

"RBLX", "SHOP", "SNOW", "NET", "CRWD",

"PANW", "UBER", "ABNB", "CVNA", "APP",

# Financial

"JPM", "BAC", "GS", "MS", "WFC",

"C", "PYPL", "AFRM", "UPST", "NU",

# Consumer

"COST", "WMT", "TGT", "HD", "LOW",

"NKE", "MCD", "SBUX", "DIS", "CMG",

# Healthcare

"LLY", "UNH", "PFE", "MRK", "ABBV",

"MRNA", "BMY", "CVS", "HIMS", "NVO",

# Energy

"XOM", "CVX", "OXY", "SLB", "HAL",

# Industrial / other

"CAT", "DE", "BA", "GE", "F",

"GM", "RIVN", "LCID", "CCL", "DAL"

]

TICKER_UNIVERSE = sorted(

set(DEFAULT_WATCHLIST)

)

print("=" * 65)

print("US SHORT SELLING STOCK UNIVERSE")

print("=" * 65)

print("Total tickers:", len(TICKER_UNIVERSE))

# ------------------------------------------------------------

# 2. DATA DOWNLOAD

# ------------------------------------------------------------

def download_history(

ticker,

period=PRICE_PERIOD,

interval=PRICE_INTERVAL

):

try:

df = yf.download(

ticker,

period=period,

interval=interval,

auto_adjust=True,

progress=False,

threads=False

)

if df.empty:

return pd.DataFrame()

# Handle MultiIndex columns

if isinstance(df.columns, pd.MultiIndex):

df.columns = df.columns.get_level_values(0)

required = [

"Open",

"High",

"Low",

"Close",

"Volume"

]

if not all(

col in df.columns

for col in required

):

return pd.DataFrame()

df = df[required].copy()

df.index = pd.to_datetime(df.index)

df = df.sort_index()

df = df[

~df.index.duplicated(keep="last")

]

df = df.replace(

[np.inf, -np.inf],

np.nan

)

df = df.dropna(

subset=required

)

return df

except Exception:

return pd.DataFrame()

# ------------------------------------------------------------

# 3. MARKET DATA QUALITY CONTROL

# ------------------------------------------------------------

MIN_HISTORY = 60

MIN_PRICE = 5

MIN_AVG_VOLUME = 300000

MIN_AVG_DOLLAR_VOLUME = 5_000_000

def validate_market_data(df):

if df.empty:

return False, "No historical data"

if len(df) < MIN_HISTORY:

return False, "Insufficient history"

# Basic OHLC validation

if (

(df["Close"] <= 0).any()

or (df["Open"] <= 0).any()

or (df["High"] <= 0).any()

or (df["Low"] <= 0).any()

or (df["High"] < df["Low"]).any()

or (df["Volume"] < 0).any()

):

return False, "Invalid OHLCV"

last = df.iloc[-1]

if last["Close"] < MIN_PRICE:

return False, "Price below minimum"

if last["Volume"] <= 0:

return False, "No latest trading volume"

# Average volume

avg_volume = df["Volume"].tail(20).mean()

if avg_volume < MIN_AVG_VOLUME:

return False, "Low average volume"

# Dollar volume

avg_dollar_volume = (

df["Close"] * df["Volume"]

).tail(20).mean()

if avg_dollar_volume < MIN_AVG_DOLLAR_VOLUME:

return False, "Low dollar liquidity"

# Recent activity

if df["Volume"].tail(5).sum() <= 0:

return False, "No recent activity"

# Extreme price movement:

# Do not automatically reject split-related moves.

# Instead, report data anomaly for further review.

returns = df["Close"].pct_change().dropna()

extreme_moves = int(

(returns.abs() > 0.50).sum()

)

if extreme_moves >= 3:

return False, "Multiple extreme price movements"

return True, "PASS"

# ------------------------------------------------------------

# 4. TECHNICAL INDICATORS

# ------------------------------------------------------------

def calculate_technical_indicators(df):

df = df.copy()

close = df["Close"]

high = df["High"]

low = df["Low"]

volume = df["Volume"]

# EMA

df["EMA_9"] = close.ewm(

span=9,

adjust=False

).mean()

df["EMA_20"] = close.ewm(

span=20,

adjust=False

).mean()

df["EMA_50"] = close.ewm(

span=50,

adjust=False

).mean()

df["EMA_200"] = close.ewm(

span=200,

adjust=False

).mean()

# SMA

df["SMA_20"] = close.rolling(20).mean()

df["SMA_50"] = close.rolling(50).mean()

df["SMA_200"] = close.rolling(200).mean()

# RSI 14

delta = close.diff()

gain = delta.clip(lower=0)

loss = -delta.clip(upper=0)

avg_gain = gain.ewm(

alpha=1/RSI_PERIOD,

adjust=False

).mean()

avg_loss = loss.ewm(

alpha=1/RSI_PERIOD,

adjust=False

).mean()

rs = (

avg_gain /

avg_loss.replace(0, np.nan)

)

df["RSI_14"] = 100 - (

100 / (1 + rs)

)

df.loc[

(avg_loss == 0) & (avg_gain > 0),

"RSI_14"

] = 100

df.loc[

(avg_gain == 0) & (avg_loss > 0),

"RSI_14"

] = 0

df.loc[

(avg_gain == 0) & (avg_loss == 0),

"RSI_14"

] = 50

# MACD

ema12 = close.ewm(

span=12,

adjust=False

).mean()

ema26 = close.ewm(

span=26,

adjust=False

).mean()

df["MACD"] = ema12 - ema26

df["MACD_SIGNAL"] = df["MACD"].ewm(

span=9,

adjust=False

).mean()

df["MACD_HIST"] = (

df["MACD"] - df["MACD_SIGNAL"]

)

# ATR

previous_close = close.shift(1)

true_range = pd.concat(

[

high - low,

(high - previous_close).abs(),

(low - previous_close).abs()

],

axis=1

).max(axis=1)

df["ATR_14"] = true_range.ewm(

alpha=1/ATR_PERIOD,

adjust=False

).mean()

df["ATR_PERCENT"] = (

df["ATR_14"] / close * 100

)

# Volume

df["AVG_VOLUME_20"] = volume.rolling(20).mean()

df["REL_VOLUME"] = (

volume /

df["AVG_VOLUME_20"].replace(0, np.nan)

)

# Dollar volume

df["DOLLAR_VOLUME"] = close * volume

df["AVG_DOLLAR_VOLUME_20"] = (

df["DOLLAR_VOLUME"].rolling(20).mean()

)

# Daily cumulative VWAP proxy

typical_price = (

high + low + close

) / 3

df["VWAP"] = (

(typical_price * volume).cumsum()

/

volume.cumsum().replace(0, np.nan)

)

# Bollinger Bands

df["BB_MIDDLE"] = close.rolling(20).mean()

bb_std = close.rolling(20).std()

df["BB_UPPER"] = (

df["BB_MIDDLE"] + 2 * bb_std

)

df["BB_LOWER"] = (

df["BB_MIDDLE"] - 2 * bb_std

)

df["BB_WIDTH"] = (

(df["BB_UPPER"] - df["BB_LOWER"])

/

df["BB_MIDDLE"]

)

# Momentum

df["RETURN_1D"] = close.pct_change(1) * 100

df["RETURN_5D"] = close.pct_change(5) * 100

df["RETURN_10D"] = close.pct_change(10) * 100

df["RETURN_20D"] = close.pct_change(20) * 100

# Gap

df["GAP_PERCENT"] = (

(df["Open"] / previous_close) - 1

) * 100

# Previous support and resistance

df["PREVIOUS_20D_LOW"] = (

low.shift(1).rolling(20).min()

)

df["PREVIOUS_20D_HIGH"] = (

high.shift(1).rolling(20).max()

)

df["PREVIOUS_10D_LOW"] = (

low.shift(1).rolling(10).min()

)

df["PREVIOUS_10D_HIGH"] = (

high.shift(1).rolling(10).max()

)

# Bearish trend

df["BEARISH_TREND"] = (

(df["EMA_20"] < df["EMA_50"])

&

(df["EMA_50"] < df["EMA_200"])

)

# Bearish momentum

df["BEARISH_MOMENTUM"] = (

(df["MACD"] < df["MACD_SIGNAL"])

&

(df["RSI_14"] < 50)

)

# Breakdown

df["BREAKDOWN"] = (

close < df["PREVIOUS_20D_LOW"]

)

# Selling pressure

df["SELLING_PRESSURE"] = (

(close < df["EMA_20"])

&

(df["REL_VOLUME"] >= 1.5)

)

# Bearish pullback

df["BEARISH_PULLBACK"] = (

(close < df["EMA_50"])

&

(close > df["EMA_20"])

&

(df["RSI_14"] < 55)

)

return df

# ------------------------------------------------------------

# 5. DOWNLOAD AND VALIDATE ALL US TICKERS

# ------------------------------------------------------------

price_data = {}

failed_tickers = []

excluded_tickers = []

quality_report = []

print("\nDownloading US market data...")

for i, ticker in enumerate(

TICKER_UNIVERSE,

start=1

):

hist = download_history(ticker)

valid, reason = validate_market_data(hist)

if valid:

hist = calculate_technical_indicators(hist)

price_data[ticker] = hist

quality_report.append({

"Ticker": ticker,

"Status": "ACCEPTED",

"Reason": reason,

"Price": hist["Close"].iloc[-1],

"Average_Volume": (

hist["Volume"].tail(20).mean()

),

"Average_Dollar_Volume": (

hist["Close"] * hist["Volume"]

).tail(20).mean()

})

else:

if hist.empty:

failed_tickers.append(ticker)

else:

excluded_tickers.append(ticker)

quality_report.append({

"Ticker": ticker,

"Status": "EXCLUDED",

"Reason": reason

})

if i % 10 == 0:

print(

f"Progress: {i}/{len(TICKER_UNIVERSE)}"

)

time.sleep(0.10)

# ------------------------------------------------------------

# 6. CREATE MARKET SNAPSHOT

# ------------------------------------------------------------

market_snapshot = []

for ticker, hist in price_data.items():

last = hist.iloc[-1]

market_snapshot.append({

"Ticker": ticker,

"Date": hist.index[-1],

"Close": last["Close"],

"Volume": last["Volume"],

"Average_Volume": last["AVG_VOLUME_20"],

"Average_Dollar_Volume": last["AVG_DOLLAR_VOLUME_20"],

"RSI": last["RSI_14"],

"EMA9": last["EMA_9"],

"EMA20": last["EMA_20"],

"EMA50": last["EMA_50"],

"EMA200": last["EMA_200"],

"MACD": last["MACD"],

"MACD_Hist": last["MACD_HIST"],

"ATR": last["ATR_14"],

"ATR_Percent": last["ATR_PERCENT"],

"Relative_Volume": last["REL_VOLUME"],

"Return_1D": last["RETURN_1D"],

"Return_5D": last["RETURN_5D"],

"Return_10D": last["RETURN_10D"],

"Return_20D": last["RETURN_20D"],

"Gap_Percent": last["GAP_PERCENT"],

"Bearish_Trend": last["BEARISH_TREND"],

"Bearish_Momentum": last["BEARISH_MOMENTUM"],

"Breakdown": last["BREAKDOWN"],

"Selling_Pressure": last["SELLING_PRESSURE"],

"Bearish_Pullback": last["BEARISH_PULLBACK"]

})

market_df = pd.DataFrame(

market_snapshot

)

if not market_df.empty:

market_df = market_df.sort_values(

"Return_5D",

ascending=True

).reset_index(drop=True)

# ------------------------------------------------------------

# 7. SHORT SELLING MARKET CANDIDATES

# ------------------------------------------------------------

if not market_df.empty:

bearish_candidates = market_df[

(market_df["Bearish_Trend"] == True)

|

(market_df["Bearish_Momentum"] == True)

|

(market_df["Breakdown"] == True)

].copy()

bearish_candidates = bearish_candidates.sort_values(

["Return_5D", "Relative_Volume"],

ascending=[True, False]

)

else:

bearish_candidates = pd.DataFrame()

# ------------------------------------------------------------

# 8. QUALITY REPORT

# ------------------------------------------------------------

quality_df = pd.DataFrame(

quality_report

)

print("\n" + "=" * 65)

print("US MARKET DATA QUALITY REPORT")

print("=" * 65)

print("Total US Universe:", len(TICKER_UNIVERSE))

print("Accepted:", len(price_data))

print("Failed Downloads:", len(failed_tickers))

print("Excluded:", len(excluded_tickers))

print("Bearish Candidates:", len(bearish_candidates))

# ------------------------------------------------------------

# 9. DISPLAY RESULTS

# ------------------------------------------------------------

print("\nTOP BEARISH CANDIDATES")

if not bearish_candidates.empty:

display(

bearish_candidates.head(30)

)

else:

print("No bearish candidates detected.")

print("\nUS MARKET SNAPSHOT")

display(

market_df.head(30)

)

print("\nEXCLUDED TICKERS")

display(

quality_df[

quality_df["Status"] == "EXCLUDED"

]

)

# ------------------------------------------------------------

# 10. EXPORT CELL 3 DATA

# ------------------------------------------------------------

market_df.to_csv(

DATA_DIR / "us_market_snapshot.csv",

index=False

)

quality_df.to_csv(

DATA_DIR / "market_data_quality.csv",

index=False

)

bearish_candidates.to_csv(

DATA_DIR / "bearish_candidates.csv",

index=False

)

print("\n" + "=" * 65)

print("CELL 3 COMPLETED")

print("=" * 65)

print("Historical datasets:", len(price_data))

print("Market snapshot:", len(market_df))

print("Bearish candidates:", len(bearish_candidates))

print("Data saved to:", DATA_DIR.resolve())

"""CELL 4. Advanced Short-Selling Intelligence Engine"""

# ============================================================

2.4. Short-Selling Intelligence, Trade Planning, and Backtesting

The fourth cell is the main analytical engine. It defines risk parameters, corporate-action warnings, a short-squeeze risk proxy, a weighted short-selling score, trade-plan calculations, a historical strategy simulation, and event-study calculations. The signal score considers EMA alignment, RSI, MACD, support breakdown, selling pressure, price relative to the VWAP proxy, bearish pullbacks, five-day momentum, and gap-down pressure. It deducts points for elevated short-squeeze proxy risk and an upcoming dividend. The final categories are STRONG SHORT, SHORT CANDIDATE, WATCH, and NEUTRAL / AVOID, with event-risk overrides where applicable. Trade planning uses ATR-based stop-loss and target levels and constrains share quantity using both a per-trade risk budget and a maximum position value. The backtest uses an EMA and bearish-momentum rule, shifts the signal by one bar to approximate next-bar execution, deducts transaction costs, slippage, and an estimated daily borrow fee, and calculates equity, drawdown, return, volatility, Sharpe ratio, win rate, and profit factor. The event study measures subsequent short-direction returns over 1-, 3-, 5-, and 10-trading-day horizons around retrieved corporate-action dates.

Code — CELL 4: Full Implementation

# TRADING EVENTS INTELLIGENCE

# CELL 4: ADVANCED SHORT-SELLING ENGINE

# ============================================================

# ------------------------------------------------------------

# 1. SHORT SELLING CONFIGURATION

# ------------------------------------------------------------

SHORT_RISK_PER_TRADE = 0.01

SHORT_MAX_POSITION_RISK = 0.02

SHORT_REWARD_RATIO = 2.0

SHORT_STOP_ATR = 1.5

SHORT_TARGET_ATR = 3.0

SHORT_MIN_SCORE = 60

SHORT_STRONG_SCORE = 75

SHORT_SLIPPAGE = 0.0005

SHORT_TRANSACTION_COST = 0.0005

SHORT_ANNUAL_BORROW_FEE = 0.03

# ------------------------------------------------------------

# 2. CORPORATE ACTION RISK

# ------------------------------------------------------------

def get_corporate_action_risk(ticker):

result = {

"Upcoming_Dividend": False,

"Upcoming_Split": False,

"Dividend_Risk": False,

"Corporate_Action_Risk": False,

"Event_Details": []

}

if all_events.empty:

return result

events = all_events[

all_events["symbol"].astype(str).str.upper()

== ticker.upper()

].copy()

if events.empty:

return result

today = pd.Timestamp.today().normalize()

upcoming = events[

(events["event_date"] >= today)

& (

events["event_date"]

<= today + pd.Timedelta(days=14)

)

]

for _, event in upcoming.iterrows():

kind = str(event["event_kind"]).upper()

if "DIVIDEND" in kind:

result["Upcoming_Dividend"] = True

result["Dividend_Risk"] = True

result["Event_Details"].append(

f"Upcoming dividend: {event['event_date']}"

)

elif "SPLIT" in kind:

result["Upcoming_Split"] = True

result["Event_Details"].append(

f"Upcoming split: {event['event_date']}"

)

result["Corporate_Action_Risk"] = (

result["Upcoming_Dividend"]

or result["Upcoming_Split"]

)

return result

# ------------------------------------------------------------

# 3. SHORT SQUEEZE RISK PROXY

# ------------------------------------------------------------

def calculate_short_squeeze_risk(df):

if len(df) < 25:

return "UNKNOWN", 0

last = df.iloc[-1]

score = 0

# High relative volume with positive price movement

if (

pd.notna(last["REL_VOLUME"])

and last["REL_VOLUME"] >= 2

and last["RETURN_1D"] > 0

):

score += 30

# Strong upward momentum

if (

pd.notna(last["RETURN_5D"])

and last["RETURN_5D"] >= 10

):

score += 25

# Overbought condition

if (

pd.notna(last["RSI_14"])

and last["RSI_14"] >= 70

):

score += 20

# Bullish MACD

if last["MACD"] > last["MACD_SIGNAL"]:

score += 15

# Strong positive gap

if (

pd.notna(last["GAP_PERCENT"])

and last["GAP_PERCENT"] >= 3

):

score += 10

if score >= 60:

level = "HIGH"

elif score >= 35:

level = "MEDIUM"

else:

level = "LOW"

return level, score

# ------------------------------------------------------------

# 4. SHORT SELLING SIGNAL ENGINE

# ------------------------------------------------------------

def calculate_short_signal(ticker, df):

if df.empty or len(df) < 60:

return None

last = df.iloc[-1]

previous = df.iloc[-2]

close = float(last["Close"])

score = 0

reasons = []

warnings_list = []

# ----------------------------------------

# A. Bearish trend

# ----------------------------------------

if (

last["EMA_20"] < last["EMA_50"]

and last["EMA_50"] < last["EMA_200"]

):

score += 20

reasons.append("Strong bearish EMA alignment")

elif last["EMA_20"] < last["EMA_50"]:

score += 12

reasons.append("Bearish EMA trend")

# ----------------------------------------

# B. RSI bearish momentum

# ----------------------------------------

rsi = last["RSI_14"]

if pd.notna(rsi):

if 30 <= rsi <= 45:

score += 15

reasons.append("Bearish RSI momentum")

elif 45 < rsi <= 50:

score += 8

reasons.append("Weak momentum")

elif rsi < 25:

warnings_list.append(

"Extremely oversold: bounce risk"

)

elif rsi > 65:

warnings_list.append(

"Bullish momentum: avoid premature short"

)

# ----------------------------------------

# C. MACD bearish

# ----------------------------------------

if last["MACD"] < last["MACD_SIGNAL"]:

score += 12

reasons.append("Bearish MACD")

if last["MACD_HIST"] < previous["MACD_HIST"]:

score += 5

reasons.append("MACD histogram weakening")

# ----------------------------------------

# D. Breakdown

# ----------------------------------------

if last["BREAKDOWN"]:

score += 20

reasons.append("20-day support breakdown")

elif close < last["PREVIOUS_10D_LOW"]:

score += 12

reasons.append("10-day support breakdown")

# ----------------------------------------

# E. Selling pressure

# ----------------------------------------

if (

last["RETURN_1D"] < 0

and last["REL_VOLUME"] >= 1.5

):

score += 15

reasons.append("High-volume selling pressure")

elif (

last["RETURN_1D"] < 0

and last["REL_VOLUME"] >= 1.2

):

score += 8

reasons.append("Above-average selling volume")

# ----------------------------------------

# F. Price below VWAP

# ----------------------------------------

if close < last["VWAP"]:

score += 5

reasons.append("Price below VWAP proxy")

# ----------------------------------------

# G. Bearish pullback

# ----------------------------------------

if last["BEARISH_PULLBACK"]:

score += 10

reasons.append("Bearish pullback setup")

# ----------------------------------------

# H. Negative momentum

# ----------------------------------------

if (

pd.notna(last["RETURN_5D"])

and last["RETURN_5D"] < -3

):

score += 8

reasons.append("Negative 5-day momentum")

# ----------------------------------------

# I. Gap down

# ----------------------------------------

if (

pd.notna(last["GAP_PERCENT"])

and last["GAP_PERCENT"] <= -2

):

score += 5

reasons.append("Gap-down pressure")

# ----------------------------------------

# J. Short squeeze risk

# ----------------------------------------

squeeze_level, squeeze_score = (

calculate_short_squeeze_risk(df)

)

if squeeze_level == "HIGH":

score -= 20

warnings_list.append(

"High short squeeze proxy risk"

)

elif squeeze_level == "MEDIUM":

score -= 8

warnings_list.append(

"Moderate short squeeze proxy risk"

)

# ----------------------------------------

# K. Corporate action risk

# ----------------------------------------

event_risk = get_corporate_action_risk(

ticker

)

if event_risk["Upcoming_Dividend"]:

score -= 15

warnings_list.append(

"Upcoming ex-dividend: short seller may owe dividend"

)

if event_risk["Upcoming_Split"]:

warnings_list.append(

"Upcoming stock split: verify adjusted data"

)

# ----------------------------------------

# L. Liquidity

# ----------------------------------------

liquidity_ok = (

close >= MIN_PRICE

and last["AVG_DOLLAR_VOLUME_20"]

>= MIN_AVG_DOLLAR_VOLUME

)

if not liquidity_ok:

score = 0

warnings_list.append(

"Insufficient liquidity"

)

# ----------------------------------------

# M. Final score

# ----------------------------------------

score = max(0, min(100, score))

if score >= SHORT_STRONG_SCORE:

signal = "STRONG SHORT"

elif score >= SHORT_MIN_SCORE:

signal = "SHORT CANDIDATE"

elif score >= 40:

signal = "WATCH"

else:

signal = "NEUTRAL / AVOID"

# Avoid issuing a strong short classification

# when squeeze or dividend risk is high.

if (

squeeze_level == "HIGH"

or event_risk["Upcoming_Dividend"]

):

if signal in [

"STRONG SHORT",

"SHORT CANDIDATE"

]:

signal = "WATCH - EVENT RISK"

return {

"Ticker": ticker,

"Date": df.index[-1],

"Price": close,

"Score": score,

"Signal": signal,

"RSI": rsi,

"Relative_Volume": last["REL_VOLUME"],

"Return_1D": last["RETURN_1D"],

"Return_5D": last["RETURN_5D"],

"Return_20D": last["RETURN_20D"],

"ATR": last["ATR_14"],

"Bearish_Trend": bool(last["BEARISH_TREND"]),

"Breakdown": bool(last["BREAKDOWN"]),

"Bearish_Pullback": bool(last["BEARISH_PULLBACK"]),

"Short_Squeeze_Risk": squeeze_level,

"Squeeze_Score": squeeze_score,

"Upcoming_Dividend": event_risk["Upcoming_Dividend"],

"Upcoming_Split": event_risk["Upcoming_Split"],

"Reasons": " | ".join(reasons),

"Warnings": " | ".join(warnings_list)

}

# ------------------------------------------------------------

# 5. BUILD SHORT SELLING SCANNER

# ------------------------------------------------------------

short_results = []

for ticker, df in price_data.items():

result = calculate_short_signal(

ticker,

df

)

if result is not None:

short_results.append(result)

short_scanner_df = pd.DataFrame(

short_results

)

if not short_scanner_df.empty:

short_scanner_df = short_scanner_df.sort_values(

["Score", "Return_5D"],

ascending=[False, True]

).reset_index(drop=True)

# ------------------------------------------------------------

# 6. SHORT TRADE PLAN

# ------------------------------------------------------------

def calculate_short_trade_plan(

ticker,

df,

capital=INITIAL_CAPITAL

):

if df.empty:

return {}

last = df.iloc[-1]

entry = float(last["Close"])

atr = float(last["ATR_14"])

if not np.isfinite(atr) or atr <= 0:

return {}

# Short position:

# Stop loss above entry

# Target below entry

stop_loss = entry + (

SHORT_STOP_ATR * atr

)

risk_per_share = stop_loss - entry

target = entry - (

SHORT_REWARD_RATIO * risk_per_share

)

if target <= 0:

return {

"Ticker": ticker,

"Status": "INVALID TARGET",

"Entry": entry,

"Stop_Loss": stop_loss,

"Target": target

}

risk_budget = (

capital * SHORT_RISK_PER_TRADE

)

max_position_value = (

capital * SHORT_MAX_POSITION_RISK

)

shares_by_risk = int(

risk_budget / risk_per_share

)

shares_by_capital = int(

max_position_value / entry

)

shares = max(

0,

min(

shares_by_risk,

shares_by_capital

)

)

position_value = shares * entry

risk_amount = shares * risk_per_share

reward_amount = shares * (

entry - target

)

return {

"Ticker": ticker,

"Status": "PLANNING ONLY",

"Direction": "SHORT",

"Entry_Reference": round(entry, 2),

"Stop_Loss": round(stop_loss, 2),

"Take_Profit": round(target, 2),

"Risk_Per_Share": round(risk_per_share, 2),

"Shares": shares,

"Position_Value": round(position_value, 2),

"Risk_Amount": round(risk_amount, 2),

"Potential_Reward": round(reward_amount, 2),

"Reward_Risk": SHORT_REWARD_RATIO

}

# ------------------------------------------------------------

# 7. GENERATE SHORT TRADE PLANS

# ------------------------------------------------------------

short_trade_plans = []

for ticker, df in price_data.items():

plan = calculate_short_trade_plan(

ticker,

df

)

if plan:

short_trade_plans.append(plan)

short_trade_plan_df = pd.DataFrame(

short_trade_plans

)

# ------------------------------------------------------------

# 8. SHORT SELLING BACKTEST

# EMA + BEARISH MOMENTUM STRATEGY

# ------------------------------------------------------------

def backtest_short_strategy(

df,

initial_capital=INITIAL_CAPITAL,

transaction_cost=SHORT_TRANSACTION_COST,

slippage=SHORT_SLIPPAGE,

annual_borrow_fee=SHORT_ANNUAL_BORROW_FEE

):

if df.empty or len(df) < 60:

return pd.DataFrame(), {}

data = df.copy()

# Signal uses completed daily bar.

# Execution is approximated from the following bar.

data["SHORT_SIGNAL"] = (

(data["EMA_20"] < data["EMA_50"])

& (data["MACD"] < data["MACD_SIGNAL"])

& (data["RSI_14"] < 50)

& (data["Close"] < data["SMA_20"])

& (data["AVG_DOLLAR_VOLUME_20"] >= MIN_AVG_DOLLAR_VOLUME)

).astype(int)

# High squeeze proxy excludes new short positions.

squeeze_block = []

for i in range(len(data)):

sample = data.iloc[:i+1]

if len(sample) >= 25:

level, = calculateshort_squeeze_risk(

sample

)

squeeze_block.append(

0 if level == "HIGH" else 1

)

else:

squeeze_block.append(0)

data["SQUEEZE_ALLOWED"] = squeeze_block

data["SHORT_SIGNAL"] = (

data["SHORT_SIGNAL"]

* data["SQUEEZE_ALLOWED"]

)

# Position decided from previous completed bar

data["POSITION"] = (

data["SHORT_SIGNAL"].shift(1).fillna(0)

)

# Close-to-close return approximation

data["MARKET_RETURN"] = (

data["Close"].pct_change().fillna(0)

)

# Short position gains when price falls

data["GROSS_SHORT_RETURN"] = (

-data["POSITION"]

* data["MARKET_RETURN"]

)

# Turnover cost

data["TURNOVER"] = (

data["POSITION"].diff().abs().fillna(

data["POSITION"].abs()

)

)

total_cost = (

transaction_cost

+ slippage

)

data["BORROW_COST"] = (

data["POSITION"]

* annual_borrow_fee

/ 252

)

data["NET_SHORT_RETURN"] = (

data["GROSS_SHORT_RETURN"]

- data["TURNOVER"] * total_cost

- data["BORROW_COST"]

)

data["EQUITY"] = (

initial_capital

* (1 + data["NET_SHORT_RETURN"]).cumprod()

)

data["BUY_HOLD_EQUITY"] = (

initial_capital

* (1 + data["MARKET_RETURN"]).cumprod()

)

data["PEAK"] = data["EQUITY"].cummax()

data["DRAWDOWN"] = (

data["EQUITY"] / data["PEAK"] - 1

) * 100

returns = data["NET_SHORT_RETURN"]

total_return = (

data["EQUITY"].iloc[-1]

/ initial_capital - 1

) * 100

years = max(

len(data) / 252,

1 / 252

)

cagr = (

(

data["EQUITY"].iloc[-1]

/ initial_capital

) ** (1 / years) - 1

) * 100

volatility = (

returns.std() np.sqrt(252) 100

)

sharpe = (

returns.mean()

/ returns.std()

* np.sqrt(252)

if returns.std() > 0

else np.nan

)

max_drawdown = data["DRAWDOWN"].min()

# Closed trade returns

trade_returns = []

entry_price = None

for i in range(1, len(data)):

current_position = data["POSITION"].iloc[i]

previous_position = data["POSITION"].iloc[i-1]

if (

current_position == 1

and previous_position == 0

):

entry_price = data["Open"].iloc[i]

elif (

current_position == 0

and previous_position == 1

and entry_price is not None

):

exit_price = data["Open"].iloc[i]

if entry_price > 0:

trade_return = (

(entry_price - exit_price)

/ entry_price

) * 100

trade_returns.append(trade_return)

entry_price = None

wins = [

x for x in trade_returns

if x > 0

]

losses = [

x for x in trade_returns

if x < 0

]

win_rate = (

len(wins) / len(trade_returns) * 100

if trade_returns

else 0

)

gross_profit = sum(wins)

gross_loss = abs(sum(losses))

profit_factor = (

gross_profit / gross_loss

if gross_loss > 0

else np.inf if gross_profit > 0

else 0

)

metrics = {

"Total_Return_Pct": total_return,

"CAGR_Pct": cagr,

"Volatility_Pct": volatility,

"Sharpe_Ratio": sharpe,

"Maximum_Drawdown_Pct": max_drawdown,

"Win_Rate_Pct": win_rate,

"Profit_Factor": profit_factor,

"Closed_Trades": len(trade_returns),

"Average_Trade_Pct": (

np.mean(trade_returns)

if trade_returns else 0

)

}

return data, metrics

# ------------------------------------------------------------

# 9. RUN BACKTEST

# ------------------------------------------------------------

short_backtest_results = []

short_backtest_equity = {}

for ticker, df in price_data.items():

bt, metrics = backtest_short_strategy(

df

)

if not bt.empty:

short_backtest_equity[ticker] = bt

short_backtest_results.append({

"Ticker": ticker,

**metrics

})

short_backtest_df = pd.DataFrame(

short_backtest_results

)

if not short_backtest_df.empty:

short_backtest_df = short_backtest_df.sort_values(

"Total_Return_Pct",

ascending=False

).reset_index(drop=True)

# ------------------------------------------------------------

# FIX: CORPORATE ACTION TICKER LOOKUP

# ------------------------------------------------------------

def get_ticker_events(ticker):

if (

"all_events" not in globals()

or all_events.empty

):

return pd.DataFrame()

required_columns = [

"symbol",

"event_kind",

"event_date",

"event_value"

]

if not all(

col in all_events.columns

for col in required_columns

):

return pd.DataFrame()

events = all_events.copy()

events["symbol"] = (

events["symbol"]

.fillna("")

.astype(str)

.str.upper()

.str.strip()

)

result = events[

events["symbol"] == str(ticker).upper().strip()

].copy()

result["event_date"] = pd.to_datetime(

result["event_date"],

errors="coerce"

)

return result.dropna(

subset=["event_date"]

).reset_index(drop=True)

print("Corporate action lookup function initialized.")

# ------------------------------------------------------------

# 10. EVENT STUDY FOR SHORT SELLING

# ------------------------------------------------------------

def short_event_study(ticker, df, events):

if df.empty or events.empty:

return pd.DataFrame()

close = df["Close"]

results = []

for _, event in events.iterrows():

event_date = event["event_date"]

if pd.isna(event_date):

continue

index = close.index.get_indexer(

[pd.Timestamp(event_date)],

method="nearest"

)[0]

if index < 0 or index >= len(close):

continue

base_price = close.iloc[index]

if base_price <= 0:

continue

row = {

"Ticker": ticker,

"Event": event["event_kind"],

"Event_Date": event_date

}

for horizon in [1, 3, 5, 10]:

target_index = index + horizon

if target_index < len(close):

future_price = close.iloc[target_index]

# Positive value = favorable for short

short_return = (

(base_price - future_price)

/ base_price

) * 100

row[f"Short_Return_{horizon}D"] = (

round(short_return, 2)

)

else:

row[f"Short_Return_{horizon}D"] = np.nan

results.append(row)

return pd.DataFrame(results)

short_event_results = []

for ticker, df in price_data.items():

ticker_events = get_ticker_events(ticker)

study = short_event_study(

ticker,

df,

ticker_events

)

if not study.empty:

short_event_results.append(study)

short_event_study_df = (

pd.concat(

short_event_results,

ignore_index=True

)

if short_event_results

else pd.DataFrame()

)

# ------------------------------------------------------------

# 11. EXPORT ALL SHORT SELLING DATA

# ------------------------------------------------------------

short_scanner_columns = [

"Ticker",

"Date",

"Price",

"Score",

"Signal",

"RSI",

"Relative_Volume",

"Return_1D",

"Return_5D",

"Return_20D",

"Short_Squeeze_Risk",

"Upcoming_Dividend",

"Reasons",

"Warnings"

]

if not short_scanner_df.empty:

short_scanner_df[

short_scanner_columns

].to_csv(

DATA_DIR / "short_selling_scanner.csv",

index=False

)

short_trade_plan_df.to_csv(

DATA_DIR / "short_trade_plans.csv",

index=False

)

short_backtest_df.to_csv(

DATA_DIR / "short_backtesting_results.csv",

index=False

)

if not short_event_study_df.empty:

short_event_study_df.to_csv(

DATA_DIR / "short_event_study.csv",

index=False

)

# Save historical price data for web dashboard

HISTORY_DIR = DATA_DIR / "history"

HISTORY_DIR.mkdir(

parents=True,

exist_ok=True

)

for ticker, df in price_data.items():

df.to_csv(

HISTORY_DIR / f"{ticker}.csv"

)

# ------------------------------------------------------------

# 12. FINAL SUMMARY

# ------------------------------------------------------------

print("\n" + "=" * 70)

print("SHORT SELLING INTELLIGENCE SUMMARY")

print("=" * 70)

print("Scanned Tickers:", len(short_scanner_df))

print(

"Strong Short:",

len(short_scanner_df[

short_scanner_df["Signal"] == "STRONG SHORT"

])

if not short_scanner_df.empty else 0

)

print(

"Short Candidates:",

len(short_scanner_df[

short_scanner_df["Signal"] == "SHORT CANDIDATE"

])

if not short_scanner_df.empty else 0

)

print("Trade Plans:", len(short_trade_plan_df))

print("Backtested Stocks:", len(short_backtest_df))

print("\nTOP SHORT SELLING CANDIDATES")

display(

short_scanner_df.head(20)

)

print("\nSHORT TRADE PLANS")

display(

short_trade_plan_df.head(20)

)

print("\nSHORT BACKTEST PERFORMANCE")

display(

short_backtest_df.head(20)

)

print("\nSHORT EVENT STUDY")

display(

short_event_study_df.head(20)

)

print("\nCELL 4 COMPLETED.")

"""CELL 5. Interactive Web Trading Dashboard"""

# ============================================================

2.5. Interactive Dashboard and Data Export

The fifth cell exports the analytical datasets to CSV, preserves historical price files and backtest equity curves, verifies required output files, installs Streamlit if needed, writes a Streamlit application to app.py, and launches the local web server. The dashboard contains six tabs: Market Overview, Short Scanner, Technical Analysis, Corporate Actions, Trade Planner, and Backtesting. It uses Streamlit controls for minimum score, signal categories, and ticker search. Plotly visualizations show signal distribution, five-day momentum against short score, candlestick charts with EMA overlays, RSI, MACD, volume, corporate-action distributions, equity curves, and drawdown. LocalTunnel is then started to expose the dashboard through a public URL when the runtime supports Node.js and the tunnel process starts successfully.

Code — CELL 5: Full Implementation

# TRADING EVENTS INTELLIGENCE

# CELL 5: PROFESSIONAL WEB TRADING DASHBOARD

# US MARKET | SHORT SELLING

# ============================================================

import os

import sys

import time

import subprocess

import importlib.util

from pathlib import Path

import pandas as pd

import numpy as np

# ------------------------------------------------------------

# 1. CONFIGURATION

# ------------------------------------------------------------

DATA_DIR = Path("trading_events_data")

HISTORY_DIR = DATA_DIR / "history"

BACKTEST_DIR = DATA_DIR / "short_backtest_history"

DATA_DIR.mkdir(exist_ok=True)

HISTORY_DIR.mkdir(exist_ok=True)

BACKTEST_DIR.mkdir(exist_ok=True)

print("=" * 65)

print("PREPARING TRADING DASHBOARD")

print("=" * 65)

# ------------------------------------------------------------

# 2. EXPORT ALL DATASETS

# ------------------------------------------------------------

def export_dataframe(df, filename):

if isinstance(df, pd.DataFrame):

df.to_csv(

DATA_DIR / filename,

index=False

)

print("Saved:", filename)

# Corporate actions

if "all_events" in globals():

export_dataframe(

all_events,

"corporate_actions.csv"

)

# Short scanner

if "short_scanner_df" in globals():

export_dataframe(

short_scanner_df,

"short_selling_scanner.csv"

)

# Trade plans

if "short_trade_plan_df" in globals():

export_dataframe(

short_trade_plan_df,

"short_trade_plans.csv"

)

# Backtesting

if "short_backtest_df" in globals():

export_dataframe(

short_backtest_df,

"short_backtesting_results.csv"

)

# Event study

if "short_event_study_df" in globals():

export_dataframe(

short_event_study_df,

"short_event_study.csv"

)

# Market snapshot

if "market_df" in globals():

export_dataframe(

market_df,

"us_market_snapshot.csv"

)

# Historical price data

if "price_data" in globals():

for ticker, df in price_data.items():

df.to_csv(

HISTORY_DIR / f"{ticker}.csv"

)

print(

"Historical datasets:",

len(price_data)

)

# Save actual backtest equity curves

if "short_backtest_equity" in globals():

for ticker, df in short_backtest_equity.items():

df.to_csv(

BACKTEST_DIR / f"{ticker}.csv"

)

print(

"Backtest equity datasets:",

len(short_backtest_equity)

)

# ------------------------------------------------------------

# 3. CHECK REQUIRED DATA

# ------------------------------------------------------------

required_files = [

"short_selling_scanner.csv",

"short_trade_plans.csv",

"short_backtesting_results.csv"

]

missing_files = [

f for f in required_files

if not (DATA_DIR / f).exists()

]

if missing_files:

raise FileNotFoundError(

f"Missing datasets: {missing_files}. "

"Please execute CELL 4 again."

)

# ------------------------------------------------------------

# 4. INSTALL STREAMLIT IF REQUIRED

# ------------------------------------------------------------

if importlib.util.find_spec("streamlit") is None:

print("Installing Streamlit...")

subprocess.check_call([

sys.executable,

"-m",

"pip",

"install",

"-q",

"streamlit"

])

print("Streamlit ready.")

# ------------------------------------------------------------

# 5. CREATE STREAMLIT APP

# ------------------------------------------------------------

APP_CODE = r'''

import streamlit as st

import pandas as pd

import numpy as np

import plotly.graph_objects as go

import plotly.express as px

from pathlib import Path

# ============================================================

# CONFIGURATION

# ============================================================

st.set_page_config(

page_title="Trading Events Intelligence",

page_icon="📉",

layout="wide"

)

DATA_DIR = Path("trading_events_data")

HISTORY_DIR = DATA_DIR / "history"

BACKTEST_DIR = DATA_DIR / "short_backtest_history"

# ============================================================

# CUSTOM STYLE

# ============================================================

st.markdown("""

<style>

.main {

background-color: #0b1120;

}

.block-container {

padding-top: 1.5rem;

}

[data-testid="stMetric"] {

background-color: #172337;

padding: 15px;

border-radius: 10px;

}

h1, h2, h3 {

color: #e5edf8;

}

</style>

""", unsafe_allow_html=True)

# ============================================================

# DATA LOADER

# ============================================================

@st.cache_data

def load_csv(filename):

path = DATA_DIR / filename

if path.exists():

return pd.read_csv(path)

return pd.DataFrame()

@st.cache_data

def load_history(ticker):

path = HISTORY_DIR / f"{ticker}.csv"

if not path.exists():

return pd.DataFrame()

df = pd.read_csv(

path,

index_col=0,

parse_dates=True

)

return df

@st.cache_data

def load_backtest_history(ticker):

path = BACKTEST_DIR / f"{ticker}.csv"

if not path.exists():

return pd.DataFrame()

return pd.read_csv(

path,

index_col=0,

parse_dates=True

)

scanner = load_csv(

"short_selling_scanner.csv"

)

plans = load_csv(

"short_trade_plans.csv"

)

backtest = load_csv(

"short_backtesting_results.csv"

)

events = load_csv(

"corporate_actions.csv"

)

event_study = load_csv(

"short_event_study.csv"

)

market = load_csv(

"us_market_snapshot.csv"

)

# ============================================================

# HEADER

# ============================================================

st.markdown("""

# 📉 TRADING EVENTS INTELLIGENCE

US EQUITY MARKET | SHORT-SELLING ANALYTICS

Dividend Intelligence • Stock Split • Bearish Momentum

• Breakdown • Short Squeeze Risk • Backtesting

""")

st.divider()

# ============================================================

# SIDEBAR

# ============================================================

st.sidebar.title("TRADING TERMINAL")

st.sidebar.caption(

"US Market | Short-Term Strategy"

)

st.sidebar.markdown("---")

min_score = st.sidebar.slider(

"Minimum Short Score",

min_value=0,

max_value=100,

value=40

)

signal_options = [

"STRONG SHORT",

"SHORT CANDIDATE",

"WATCH",

"NEUTRAL / AVOID",

"WATCH - EVENT RISK"

]

selected_signals = st.sidebar.multiselect(

"Signal Classification",

signal_options,

default=signal_options

)

ticker_search = st.sidebar.text_input(

"Search Ticker",

placeholder="Example: NVDA"

).upper().strip()

# ============================================================

# FILTER SCANNER

# ============================================================

filtered = scanner.copy()

if not filtered.empty:

filtered = filtered[

filtered["Score"] >= min_score

]

filtered = filtered[

filtered["Signal"].isin(selected_signals)

]

if ticker_search:

filtered = filtered[

filtered["Ticker"].astype(str).str.contains(

ticker_search,

case=False,

na=False

)

]

# ============================================================

# MAIN KPI

# ============================================================

total_stocks = len(scanner)

strong_short = (

len(scanner[

scanner["Signal"] == "STRONG SHORT"

])

if not scanner.empty else 0

)

short_candidates = (

len(scanner[

scanner["Signal"] == "SHORT CANDIDATE"

])

if not scanner.empty else 0

)

high_squeeze = (

len(scanner[

scanner["Short_Squeeze_Risk"] == "HIGH"

])

if (

not scanner.empty

and "Short_Squeeze_Risk" in scanner.columns

)

else 0

)

c1, c2, c3, c4 = st.columns(4)

c1.metric(

"US Stocks Scanned",

total_stocks

)

c2.metric(

"Strong Short",

strong_short

)

c3.metric(

"Short Candidates",

short_candidates

)

c4.metric(

"High Squeeze Risk",

high_squeeze

)

# ============================================================

# NAVIGATION

# ============================================================

tabs = st.tabs([

"📊 Market Overview",

"🔎 Short Scanner",

"📈 Technical Analysis",

"📅 Corporate Actions",

"🎯 Trade Planner",

"🧪 Backtesting"

])

# ============================================================

# TAB 1: MARKET OVERVIEW

# ============================================================

with tabs[0]:

st.subheader("Market Intelligence")

if not scanner.empty:

left, right = st.columns(2)

with left:

signal_counts = (

scanner["Signal"]

.value_counts()

.reset_index()

)

signal_counts.columns = [

"Signal",

"Count"

]

fig = px.pie(

signal_counts,

names="Signal",

values="Count",

hole=0.55,

title="Signal Distribution"

)

fig.update_layout(

template="plotly_dark"

)

st.plotly_chart(

fig,

use_container_width=True

)

with right:

fig = px.scatter(

scanner,

x="Return_5D",

y="Score",

color="Signal",

size="Relative_Volume",

hover_name="Ticker",

title="5D Momentum vs Short Score"

)

fig.update_layout(

template="plotly_dark"

)

st.plotly_chart(

fig,

use_container_width=True

)

st.subheader("Top Short Opportunities")

st.dataframe(

scanner.sort_values(

"Score",

ascending=False

).head(20),

use_container_width=True,

hide_index=True

)

else:

st.warning(

"No scanner data available."

)

if not market.empty:

st.subheader("US Market Snapshot")

st.dataframe(

market.head(30),

use_container_width=True,

hide_index=True

)

# ============================================================

# TAB 2: SHORT SCANNER

# ============================================================

with tabs[1]:

st.subheader("Short Selling Scanner")

st.caption(

"Ranking berdasarkan bearish technical scoring."

)

if not filtered.empty:

st.dataframe(

filtered.sort_values(

"Score",

ascending=False

),

use_container_width=True,

hide_index=True

)

st.download_button(

"Download Scanner CSV",

filtered.to_csv(index=False),

"short_selling_scanner.csv",

"text/csv"

)

else:

st.info(

"No stocks match the selected filters."

)

# ============================================================

# TAB 3: TECHNICAL ANALYSIS

# ============================================================

with tabs[2]:

st.subheader("Advanced Technical Analysis")

history_files = (

list(HISTORY_DIR.glob("*.csv"))

if HISTORY_DIR.exists()

else []

)

available_tickers = sorted(

[f.stem for f in history_files]

)

if available_tickers:

ticker = st.selectbox(

"Select Stock",

available_tickers,

key="technical_ticker"

)

hist = load_history(ticker)

if not hist.empty:

last = hist.iloc[-1]

a, b, c, d = st.columns(4)

a.metric(

"Last Close",

f"${last['Close']:.2f}"

)

b.metric(

"RSI 14",

f"{last['RSI_14']:.2f}"

if pd.notna(last["RSI_14"])

else "N/A"

)

c.metric(

"ATR 14",

f"${last['ATR_14']:.2f}"

if pd.notna(last["ATR_14"])

else "N/A"

)

d.metric(

"Relative Volume",

f"{last['REL_VOLUME']:.2f}"

if pd.notna(last["REL_VOLUME"])

else "N/A"

)

# Candlestick

fig = go.Figure()

fig.add_trace(

go.Candlestick(

x=hist.index,

open=hist["Open"],

high=hist["High"],

low=hist["Low"],

close=hist["Close"],

name="Price"

)

)

for column, label in [

("EMA_9", "EMA 9"),

("EMA_20", "EMA 20"),

("EMA_50", "EMA 50"),

("EMA_200", "EMA 200")

]:

if column in hist.columns:

fig.add_trace(

go.Scatter(

x=hist.index,

y=hist[column],

name=label

)

)

fig.update_layout(

title=f"{ticker} Price Chart",

template="plotly_dark",

height=600,

xaxis_rangeslider_visible=False

)

st.plotly_chart(

fig,

use_container_width=True

)

# RSI

fig = go.Figure()

fig.add_trace(

go.Scatter(

x=hist.index,

y=hist["RSI_14"],

name="RSI"

)

)

fig.add_hline(

y=70,

line_dash="dash"

)

fig.add_hline(

y=30,

line_dash="dash"

)

fig.update_layout(

title="RSI Analysis",

template="plotly_dark",

height=300

)

st.plotly_chart(

fig,

use_container_width=True

)

# MACD

fig = go.Figure()

fig.add_trace(

go.Scatter(

x=hist.index,

y=hist["MACD"],

name="MACD"

)

)

fig.add_trace(

go.Scatter(

x=hist.index,

y=hist["MACD_SIGNAL"],

name="Signal"

)

)

fig.update_layout(

title="MACD Analysis",

template="plotly_dark",

height=300

)

st.plotly_chart(

fig,

use_container_width=True

)

# Volume

fig = px.bar(

hist.tail(60),

y="Volume",

title="Trading Volume"

)

fig.update_layout(

template="plotly_dark",

height=300

)

st.plotly_chart(

fig,

use_container_width=True

)

else:

st.warning(

"Historical price data not found."

)

# ============================================================

# TAB 4: CORPORATE ACTIONS

# ============================================================

with tabs[3]:

st.subheader("Dividend & Stock Split Intelligence")

if not events.empty:

st.dataframe(

events,

use_container_width=True,

hide_index=True

)

st.download_button(

"Download Corporate Actions",

events.to_csv(index=False),

"corporate_actions.csv",

"text/csv"

)

if "event_kind" in events.columns:

fig = px.histogram(

events,

x="event_kind",

title="Corporate Action Distribution"

)

fig.update_layout(

template="plotly_dark"

)

st.plotly_chart(

fig,

use_container_width=True

)

else:

st.info(

"Corporate action data unavailable."

)

st.subheader("Short Event Study")

if not event_study.empty:

st.dataframe(

event_study,

use_container_width=True,

hide_index=True

)

else:

st.info(

"No event study records available."

)

# ============================================================

# TAB 5: SHORT TRADE PLANNER

# ============================================================

with tabs[4]:

st.subheader("Short Trade Planning")

if not plans.empty:

st.dataframe(

plans,

use_container_width=True,

hide_index=True

)

st.download_button(

"Download Trade Plans",

plans.to_csv(index=False),

"short_trade_plans.csv",

"text/csv"

)

if "Ticker" in plans.columns:

selected_plan = st.selectbox(

"Select Trade Plan",

plans["Ticker"].tolist()

)

plan = plans[

plans["Ticker"] == selected_plan

].iloc[0]

a, b, c = st.columns(3)

a.metric(

"Entry Reference",

f"${plan['Entry_Reference']:.2f}"

)

b.metric(

"Stop Loss",

f"${plan['Stop_Loss']:.2f}"

)

c.metric(

"Take Profit",

f"${plan['Take_Profit']:.2f}"

)

st.write(

"Position Size:",

int(plan["Shares"]),

"shares"

)

st.write(

"Position Value:",

f"${plan['Position_Value']:,.2f}"

)

st.write(

"Estimated Risk:",

f"${plan['Risk_Amount']:,.2f}"

)

else:

st.info(

"No trade plans available."

)

st.warning(

"Planning only. Verify stock borrow availability, "

"borrow fees, dividend obligations, margin requirements "

"and broker execution conditions."

)

# ============================================================

# TAB 6: BACKTESTING

# ============================================================

with tabs[5]:

st.subheader("Short Strategy Performance")

if not backtest.empty:

st.dataframe(

backtest.sort_values(

"Total_Return_Pct",

ascending=False

),

use_container_width=True,

hide_index=True

)

st.download_button(

"Download Backtest Results",

backtest.to_csv(index=False),

"short_backtesting_results.csv",

"text/csv"

)

ticker_options = backtest["Ticker"].tolist()

selected = st.selectbox(

"Select Backtested Ticker",

ticker_options,

key="backtest_ticker"

)

bt = load_backtest_history(selected)

if not bt.empty:

if "EQUITY" in bt.columns:

fig = go.Figure()

fig.add_trace(

go.Scatter(

x=bt.index,

y=bt["EQUITY"],

name="Short Strategy Equity"

)

)

fig.add_trace(

go.Scatter(

x=bt.index,

y=bt["BUY_HOLD_EQUITY"],

name="Buy & Hold Benchmark"

)

)

fig.update_layout(

title=f"{selected} Equity Curve",

template="plotly_dark",

height=450

)

st.plotly_chart(

fig,

use_container_width=True

)

if "DRAWDOWN" in bt.columns:

fig = px.area(

bt,

y="DRAWDOWN",

title="Strategy Drawdown"

)

fig.update_layout(

template="plotly_dark",

height=300

)

st.plotly_chart(

fig,

use_container_width=True

)

else:

st.info(

"Historical backtest equity curve unavailable."

)

else:

st.info(

"Backtesting results unavailable."

)

# ============================================================

# FOOTER

# ============================================================

st.divider()

st.caption(

"TRADING EVENTS INTELLIGENCE | US MARKET"

)

st.caption(

"Research platform only. Not financial advice. "

"Short selling involves unlimited theoretical loss "

"and may involve forced liquidation."

)

'''

# ------------------------------------------------------------

# 6. WRITE APP FILE

# ------------------------------------------------------------

APP_PATH = Path("app.py")

APP_PATH.write_text(

APP_CODE,

encoding="utf-8"

)

print("Streamlit application created.")

# ------------------------------------------------------------

# 7. STOP PREVIOUS SERVER

# ------------------------------------------------------------

if (

"streamlit_process" in globals()

and streamlit_process.poll() is None

):

streamlit_process.terminate()

time.sleep(2)

# ------------------------------------------------------------

# 8. START STREAMLIT

# ------------------------------------------------------------

log_file = open(

"streamlit.log",

"w"

)

streamlit_process = subprocess.Popen(

[

sys.executable,

"-m",

"streamlit",

"run",

str(APP_PATH),

"--server.port",

"8501",

"--server.address",

"0.0.0.0",

"--server.headless",

"true",

"--browser.gatherUsageStats",

"false"

],

stdout=log_file,

stderr=subprocess.STDOUT

)

time.sleep(5)

if streamlit_process.poll() is not None:

log_file.close()

print(

Path("streamlit.log").read_text(

encoding="utf-8",

errors="ignore"

)

)

raise RuntimeError(

"Streamlit server failed to start."

)

print("Streamlit server started successfully.")

# ------------------------------------------------------------

# 9. START LOCALTUNNEL

# ------------------------------------------------------------

# Check Node.js and npm

node_check = subprocess.run(

["node", "--version"],

capture_output=True,

text=True

)

if node_check.returncode != 0:

raise RuntimeError(

"Node.js is unavailable in this runtime."

)

# Stop previous tunnel if any

if (

"tunnel_process" in globals()

and tunnel_process.poll() is None

):

tunnel_process.terminate()

tunnel_process = subprocess.Popen(

[

"npx",

"--yes",

"localtunnel",

"--port",

"8501"

],

stdout=subprocess.PIPE,

stderr=subprocess.STDOUT,

text=True,

bufsize=1

)

print("\nWaiting for public dashboard URL...")

dashboard_url = None

for _ in range(30):

line = tunnel_process.stdout.readline()

if line:

print(line.strip())

if "https://" in line:

import re

match = re.search(

r"https://[^\s]+",

line

)

if match:

dashboard_url = match.group(0)

break

if tunnel_process.poll() is not None:

break

time.sleep(1)

# ------------------------------------------------------------

# 10. FINAL STATUS

# ------------------------------------------------------------

print("\n" + "=" * 65)

print("TRADING EVENTS INTELLIGENCE DASHBOARD")

print("=" * 65)

if dashboard_url:

print("DASHBOARD URL:")

print(dashboard_url)

display(

HTML(

f'''

<div style="

padding:20px;

border-radius:12px;

background:#172337;

color:white;

margin-top:15px;">

<h3>Trading Dashboard is Ready</h3>

<a href="{dashboard_url}"

target="_blank"

style="

color:#60a5fa;

font-size:18px;

font-weight:bold;">

OPEN TRADING DASHBOARD

</a>

</div>

'''

)

)

else:

print(

"Tunnel URL not detected automatically."

)

print(

"Check the LocalTunnel output above."

)

Result:

result



3. Results and Discussion

3.1. Corporate-Action Intelligence

The corporate-action module produces separate dividend and stock-split datasets and combines them into a unified event table. The normalized fields support ticker-level lookup, event-date filtering, and event classification. The system identifies events that occurred before the current date, events scheduled within the next 14 days, and events scheduled later. These labels provide context for subsequent short-selling analysis. The actual number of retrieved records cannot be stated from the source code alone because the script does not include a captured API response or execution log.

3.2. Market Data Quality and Technical Analysis

The market-data module applies explicit data-quality filters before calculating technical indicators. This reduces the likelihood that missing, malformed, illiquid, or unusually discontinuous observations enter the scanner. Accepted histories are summarized in a market snapshot containing price, volume, RSI, EMA values, MACD, ATR, relative volume, return horizons, gap percentage, and bearish-condition flags. The watchlist is a predefined research universe. Although NYSE and NASDAQ are named in the project configuration, the supplied code does not independently verify the listing exchange for each ticker.

3.3. Short-Selling Candidate Classification

The scoring engine combines multiple technical observations into a single score capped between zero and 100. Strong bearish EMA alignment contributes more points than a partial bearish alignment. Bearish RSI, MACD weakness, support breakdown, high-volume selling, price below the VWAP proxy, bearish pullback, negative five-day return, and a gap-down condition add further points. A high short-squeeze proxy score reduces the score, while an upcoming ex-dividend event reduces it further and may change a short classification to WATCH - EVENT RISK. The score is a rule-based ranking mechanism defined by the script. It is not a statistically calibrated probability of a price decline.

3.4. Short Trade Planning and Position Sizing

The trade planner uses the latest close as the reference entry. For a short position, the stop-loss is placed above the reference entry by 1.5 ATR. The target is calculated using a two-times risk/reward multiple. The risk budget equals one percent of initial capital, while the maximum position value equals two percent of capital. The share quantity is the lower of the quantity allowed by the risk budget and the quantity allowed by the maximum position value. The resulting plan is labelled PLANNING ONLY. It does not verify actual stock-borrow availability, broker-specific margin rules, locate requirements, real-time execution prices, or actual borrow rates.

3.5. Historical Backtesting

The backtesting function defines a short signal when EMA 20 is below EMA 50, MACD is below its signal line, RSI is below 50, closing price is below SMA 20, and average dollar volume meets the liquidity threshold. A high short-squeeze proxy blocks new positions. The signal is shifted by one trading bar before the position is applied, which is intended to reduce look-ahead bias in the position timing. The simulation approximates short returns as the negative of close-to-close market returns while a short position is active. It subtracts turnover-based transaction costs and slippage, plus a daily borrow-fee estimate based on 252 trading days.

The backtest reports total return, CAGR, annualized volatility, Sharpe ratio, maximum drawdown, win rate, profit factor, closed trades, and average trade return. These metrics are useful descriptive measures, but the implementation contains simplifying assumptions. For example, portfolio-level interactions across multiple simultaneous positions are not modeled as a combined account. The backtest does not simulate intraday stop-loss or take-profit execution, changing borrow availability, recalls, forced buy-ins, financing and margin changes, or all corporate-action cash flows. The closed-trade return calculation uses opening prices for detected entry and exit transitions, while the equity curve uses close-to-close returns. These are different approximations and should be considered when interpreting the reported metrics.

3.6. Corporate-Action Event Study

The event-study function matches each corporate-action date to the nearest available trading date in the historical closing-price index. It then calculates short-direction returns over 1, 3, 5, and 10 trading-day horizons. A positive value indicates that the share price declined over the selected horizon and was therefore directionally favorable to a short position before costs. The study is descriptive. It does not establish that the corporate action caused the subsequent price movement, and the nearest-date matching approach may associate a non-trading event date with an adjacent trading session.

3.7. Interactive Dashboard

The Streamlit dashboard consolidates the system outputs into six functional areas. Market Overview presents key counts and market-level visualizations. Short Scanner displays ranked candidates and supports CSV downloads. Technical Analysis provides ticker selection, latest indicator metrics, candlestick charts, EMA overlays, RSI, MACD, and volume. Corporate Actions displays dividend and split records alongside the event-study table. Trade Planner presents reference entry, stop-loss, take-profit, position size, position value, and estimated risk. Backtesting compares the strategy equity curve with a buy-and-hold benchmark and displays drawdown.

The dashboard is designed to read files generated by the preceding cells. Therefore, the data-collection and analysis cells must run successfully before the dashboard is launched. The public URL depends on the notebook runtime, Node.js availability, and LocalTunnel execution. A URL is not embedded in the source code because it is generated dynamically when the tunnel starts.

3.8. Output Files

The script exports corporate-action records, the short-selling scanner, trade plans, backtesting results, event-study results, a US market snapshot, market-data quality information, historical price files, and per-ticker backtest equity histories. The principal CSV outputs include corporate_actions.csv, short_selling_scanner.csv, short_trade_plans.csv, short_backtesting_results.csv, short_event_study.csv, and us_market_snapshot.csv. The dashboard also reads historical price files from trading_events_data/history and backtest histories from trading_events_data/short_backtest_history.

3.9. Limitations and Further Development

Several limitations should guide interpretation. First, the corporate-action module depends on the MarketFlow endpoint names and response schema. Second, the technical indicators are calculated from the historical data returned by yfinance, so missing observations, adjusted-price conventions, ticker changes, and data-provider differences can affect results. Third, the short-squeeze measure is a proxy based on price and volume indicators. It does not use short interest, days to cover, securities-lending utilization, borrow availability, or options positioning. Fourth, the trade planner uses fixed assumptions for ATR distance, risk allocation, and reward-to-risk ratio. Fifth, the backtest is a simplified daily-bar simulation and does not represent live execution.

Further development could incorporate verified exchange metadata, short-interest and securities-lending datasets, real borrow-rate observations, earnings calendars, regulatory halts, market-wide regime filters, portfolio-level exposure constraints, more realistic order execution, corporate-action cash-flow adjustments, walk-forward validation, out-of-sample testing, and sensitivity analysis. These additions would improve the framework's ability to support systematic research and risk assessment.

4. Conclusion

This article presents Trading Events Intelligence, a Python-based framework that integrates corporate-action monitoring, US equity market data, technical analysis, short-selling candidate scoring, trade planning, backtesting, event-study calculations, and an interactive Streamlit dashboard.

The system retrieves dividend and stock-split information through the MarketFlow API and historical OHLCV data through yfinance. It applies data-quality checks before calculating technical indicators such as EMA, SMA, RSI, MACD, ATR, relative volume, Bollinger Bands, price gaps, and prior support and resistance levels. These indicators support the identification and ranking of bearish market conditions.

The short-selling engine combines technical signals with corporate-action and short-squeeze proxy warnings. It also calculates ATR-based trade plans and position sizes under predefined capital-risk constraints. The backtesting module evaluates a rule-based EMA and bearish-momentum strategy after estimated transaction costs, slippage, and borrow fees. The event-study module measures subsequent short-direction returns around corporate-action dates.

The Streamlit dashboard brings the resulting datasets and visualizations into one interface. It supports market overview, candidate screening, technical chart review, corporate-action monitoring, trade planning, and backtest inspection. The framework therefore provides a structured research workflow for examining short-selling conditions in a selected US equity universe.

The system should be interpreted as a descriptive and rule-based research tool, not as an autonomous trading system or a source of guaranteed trading signals. Its conclusions depend on data availability, API response quality, indicator definitions, and simulation assumptions. Before any live use, the implementation requires testing, validation, and additional controls for stock borrowing, margin, dividends, execution costs, and portfolio-level risk. Short selling can produce losses that exceed the initial proceeds of the position and may involve forced liquidation. The framework does not replace independent financial, legal, or broker-specific review.