Skip to content

TjTheDj2011/trading-indicators

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

trading-indicators

Quantitative trading indicators for Python. Anchored VWAP and Value at Risk.

Installation

pip install trading-indicators

Or install from source:

git clone https://github.com/TjTheDj2011/trading-indicators.git
cd trading-indicators
pip install -e .

Dependencies

  • Python >= 3.10
  • pandas >= 2.0
  • numpy >= 1.24
  • scipy >= 1.10

Anchored VWAP (AVWAP)

An implementation of the Anchored Volume-Weighted Average Price indicator based on the anchored VWAP's methodology. AVWAP anchors a VWAP calculation to a significant event -- a gap, earnings release, swing high/low, breakout, or any user-defined point -- and tracks the volume-weighted average cost basis from that anchor forward.

Key features

  • 12 anchor types: High/low of day, earnings, gap up/down, reversal, swing high/low, breakout/breakdown, custom
  • Auto-detection: Automatically identifies significant anchor points (period highs/lows, gaps >= 2%, swing pivots)
  • Standard deviation bands: +/- 1 and 2 standard deviation bands around the VWAP line
  • Signal generation: Produces buy/sell signals with strength scores based on price position relative to AVWAP and its bands
  • Multiple AVWAPs: Calculate from several anchor points simultaneously for layered context

Usage

import pandas as pd
from trading_indicators import AnchoredVWAP, AnchorType, calculate_multiple_avwaps

# df is a pandas DataFrame with columns: open, high, low, close, volume
avwap = AnchoredVWAP()

# Calculate from a specific anchor index
line = avwap.calculate_avwap(df, anchor_index=50, anchor_type=AnchorType.SWING_LOW)
print(f"VWAP: {line.current_vwap:.2f}")
print(f"+1 std: {line.upper_band_1:.2f}, -1 std: {line.lower_band_1:.2f}")

# Auto-detect anchors and calculate multiple AVWAPs
avwaps = calculate_multiple_avwaps(df, auto_anchor=True)
for key, line in avwaps.items():
    print(f"{key}: VWAP={line.current_vwap:.2f}")

# Analyze price relative to an AVWAP
analysis = avwap.analyze_price_vs_avwap(current_price=150.25, avwap=line)
print(f"Bias: {analysis['bias']}, Zone: {analysis['zone']}")
for signal in analysis['signals']:
    print(f"  {signal['action']} (strength={signal['strength']:.1f}): {signal['reason']}")

Signal methodology

Price position relative to the AVWAP and its standard deviation bands determines the trading bias:

Zone Price position Signal
EXTENDED_HIGH > +2 std dev Overbought -- caution on longs
HIGH +1 to +2 std dev Consider taking profits
ABOVE_VWAP VWAP to +1 std dev Bullish bias
BELOW_VWAP -1 std dev to VWAP Bearish bias
LOW -2 to -1 std dev Potential buying opportunity
EXTENDED_LOW < -2 std dev Oversold -- strong buy signal

Value at Risk (VaR)

A full-featured VaR calculator supporting four calculation methods, portfolio aggregation, stress testing, backtesting, and position optimization.

Calculation methods

  1. Historical Simulation -- Uses the empirical distribution of past returns. No distributional assumptions.
  2. Parametric (Variance-Covariance) -- Assumes returns are normally distributed. Fast but may underestimate tail risk.
  3. Monte Carlo Simulation -- Generates 10,000 random scenarios from fitted parameters. Captures path-dependent behavior.
  4. Cornish-Fisher Expansion -- Adjusts the normal quantile for observed skewness and excess kurtosis. Better tail accuracy than parametric with minimal computational overhead.

Features

  • Multiple confidence levels: 90%, 95%, 99%, 99.5%, 99.9%
  • Time horizon scaling: Square-root-of-time scaling for multi-day VaR
  • Expected Shortfall (CVaR): Included in every result
  • Portfolio VaR: Aggregates across positions with diversification adjustment
  • Stress testing: Apply custom scenario shocks and compare against normal VaR
  • Backtesting: Kupiec's proportion-of-failures test for model validation
  • Position optimization: Risk-parity-based sizing constrained to a maximum VaR

Usage

import numpy as np
from trading_indicators import VaRCalculator, AdvancedVaRManager, VaRMethod, ConfidenceLevel

# Generate sample returns
np.random.seed(42)
returns = np.random.normal(0.0005, 0.02, 500).tolist()

calc = AdvancedVaRManager()

# Single-asset VaR
result = calc.calculate_var(
    returns,
    portfolio_value=1_000_000,
    confidence_level=ConfidenceLevel.CONF_95,
    time_horizon=1,
    method=VaRMethod.HISTORICAL
)
print(f"VaR: ${result.value_at_risk:,.2f} ({result.var_percent:.2f}%)")
print(f"Expected Shortfall: ${result.expected_shortfall:,.2f}")

# Compare all four methods
comparison = calc.get_var_comparison(returns, portfolio_value=1_000_000)
for method_name, res in comparison.items():
    print(f"{method_name}: ${res.value_at_risk:,.2f}")

# Stress testing
stress = calc.calculate_var_with_stress_testing(
    returns, 1_000_000,
    stress_scenarios=[-0.05, -0.10, -0.15]
)
print(f"Normal VaR: ${stress['normal_var'].value_at_risk:,.2f}")
print(f"Max stress VaR: ${stress['stress_var']:,.2f}")

# Risk compliance
calc.set_risk_limits(var_limit=50_000, es_limit=70_000)
compliance = calc.check_risk_compliance(result)
print(f"Within limits: {compliance['var_within_limit']}")

# Backtesting
backtest = calc.perform_backtesting(returns[:400], returns[400:])
print(f"Violation rate: {backtest['violation_rate']:.2%}")
print(f"Kupiec p-value: {backtest['kupiec_p_value']:.4f}")
print(f"Model reliability: {backtest['model_reliability']}")

License

MIT -- see LICENSE for details.

About

Quantitative trading indicators for Python. Anchored VWAP and Value at Risk with 4 calculation methods.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages