Asheesh7298/Trading-agent
Folders and files
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Repository files navigation
================================================================================
ASSET ALPHA TRADING AGENT — README
Team Strategy: Volatility-Regime Aware Trend Following
================================================================================
--------------------------------------------------------------------------------
SECTION 1: WHAT PATTERN DID WE FIND?
--------------------------------------------------------------------------------
We ran an extensive data-driven analysis of the training CSV using the starter
notebook as a guide. The three features computed in Section 3 of the notebook
were the starting point:
1. Rolling 5-period volatility
2. Volume ratio vs 10-period average
3. 30-period Z-score
KEY DISCOVERY — The chart revealed two critical facts:
(a) VOLATILITY is the real signal, not volume.
The 15th-percentile volatility line sits near zero, meaning the asset
spends ~85% of its time in an extremely flat, quiet state. Volatility
spikes are rare and sharp (0.5–1.9 std) and coincide precisely with
large price moves.
(b) CASH DECAY is the dominant enemy, not bad trades.
At 0.02% per tick, staying in cash over 1,080 ticks (3-hour session)
costs approximately 19.6%. Any strategy that spends too much time in
cash will lose primarily to decay, not to the market.
(c) The market goes UP in ~54% of competition-length windows.
Average raw market return per 1,080-tick window = +0.41%.
This means the asset is NOT inherently bearish over a session.
The correct posture is to stay invested and only exit on confirmed
danger signals.
CONCLUSION: The winning approach is to be INVESTED most of the time, and only
exit when a confirmed, multi-timeframe downtrend is detected.
--------------------------------------------------------------------------------
SECTION 2: HOW DID WE SIZE POSITIONS?
--------------------------------------------------------------------------------
Position sizing uses 55% of current net worth per buy order:
qty = int((net_worth * 0.55) / current_price)
Rationale:
- 55% stays within the 60% maximum position rule
- Leaves 45% cash buffer to absorb volatility without forced liquidation
- Large enough position to meaningfully offset cash decay
- Single position at a time (no pyramiding) keeps logic simple and robust
--------------------------------------------------------------------------------
SECTION 3: HOW DID WE MANAGE RISK?
--------------------------------------------------------------------------------
Three layers of risk management:
LAYER 1 — Hard Stop Loss (2%)
If price drops more than 2% from entry price, sell immediately regardless
of any other signal. This prevents catastrophic losses from sharp drops.
LAYER 2 — Volatility Spike Exit
If the 5-period volatility exceeds 4x the 30-period baseline AND price
is falling (slope_10 < 0), exit immediately. This detects the rare but
dangerous sharp drops that the chart showed coincide with vol spikes.
LAYER 3 — Multi-Timeframe Downtrend Exit
Exit only when ALL THREE timeframes confirm a downtrend simultaneously:
slope_10 < -0.004 (10-bar momentum strongly negative)
slope_30 < -0.003 (30-bar trend negative)
slope_50 < -0.003 (50-bar trend negative)
Requiring all three prevents premature exits on noise.
Re-entry after any exit is triggered immediately when:
- Market returns to quiet (vol_ratio < 2.5)
- Z-score is not extreme (z < 1.5)
- Short-term momentum is non-negative (slope_10 >= 0)
OR
- Price is deeply oversold (z < -1.5)
The goal is to minimise time in cash while avoiding confirmed crashes.
--------------------------------------------------------------------------------
SECTION 4: BACKTEST RESULTS
--------------------------------------------------------------------------------
We tested across 107 non-overlapping 1,080-tick windows extracted from the
full 116,346-bar training dataset. Each window matches the competition length
(3 hours at 10-second ticks).
Results summary:
Strategy | Avg P&L | Best | Worst | UP mkt avg | DN mkt avg
----------------|----------|----------|----------|------------|------------
FINAL (ours) | -4.36% | +6.66% | -22.58% | +2.85% | -8.70%
Hold always | -11.91% | -1.15% | -20.59% | -3.85% | -18.18%
V3 trend | -11.42% | -5.97% | -21.20% | -9.27% | -12.75%
Baseline SMA | -18.04% | -15.00% | -22.04% | n/a | n/a
Key takeaways:
- Our strategy beats baseline in 95%+ of windows
- In UP markets (54% of windows): avg +2.85% — actually profitable
- In DOWN markets: avg -8.70% vs Hold's -18.18% — half the loss
- Best case: +6.66% — competitive to win
- The strategy adapts to market direction automatically
--------------------------------------------------------------------------------
SECTION 5: INDICATORS USED
--------------------------------------------------------------------------------
All indicators are computed from the rolling price history buffer:
Z-SCORE (30-period)
z = (current_price - mean_30) / std_30
Measures how many standard deviations price is from its 30-bar mean.
Used to detect overbought (z > 2.0) and oversold (z < -1.5) conditions.
VOLATILITY RATIO
vol_ratio = std(last 5 prices) / std(last 30 prices)
Detects sudden volatility spikes relative to recent baseline.
Threshold: > 4.0x = danger signal.
MULTI-TIMEFRAME MOMENTUM (slopes)
slope_10 = (price_now - price_10_bars_ago) / price_10_bars_ago
slope_30 = (price_now - price_30_bars_ago) / price_30_bars_ago
slope_50 = (price_now - price_50_bars_ago) / price_50_bars_ago
All three must agree for a sell signal — prevents false exits on noise.
--------------------------------------------------------------------------------
SECTION 6: AGENT TECHNICAL DETAILS
--------------------------------------------------------------------------------
Entry point: agent.py
Language: Python 3.8+
Dependencies: requests, numpy (see requirements.txt)
Environment variables required:
API_URL — base URL of the competition server
TEAM_API_KEY — your team's API key
Run command:
Linux/macOS:
API_URL=http://live-server TEAM_API_KEY=your-key python agent.py
Windows PowerShell:
$env:API_URL='http://live-server'
$env:TEAM_API_KEY='your-key'
python agent.py
Error handling:
- All API calls retry up to 3 times with 1-second delay between attempts
- Empty responses handled gracefully (skips tick, waits, retries)
- KeyboardInterrupt exits cleanly
- Any unhandled exception is caught, printed, and the loop continues
Tick timing:
- Agent polls every 8 seconds (not 10) to ensure no ticks are missed
- History pre-loaded on startup via /api/history to warm indicators
--------------------------------------------------------------------------------
SECTION 7: WHAT THE AGENT DOES EACH TICK
--------------------------------------------------------------------------------
Every 8 seconds the agent:
1. Fetches current price from /api/price
2. Fetches portfolio state from /api/portfolio
3. Appends new price to rolling history buffer
4. Computes z-score, volatility ratio, and 3 momentum slopes
5. Evaluates signal logic in this order:
a. Is this the first tick? → BUY immediately
b. Stop loss breached? → SELL immediately
c. Vol spike + falling? → SELL
d. All slopes down? → SELL
e. Overbought + falling? → SELL
f. Quiet + momentum up? → BUY (re-enter)
g. Deeply oversold? → BUY
h. Otherwise → HOLD
6. Executes trade if signal differs from current position state
7. Logs full state to terminal: tick, signal, price, shares, NW, PNL, reason
8. Sleeps 8 seconds until next tick
================================================================================
END OF README
================================================================================