Skip to content

DataContext API Reference

The DataContext object provides access to market data and technical indicators for a specific symbol.

Class: DataContext

python
data = data_contexts['AAPL']  # Get DataContext for Apple

Properties

Price Data

open

Type: float
Description: Opening price of the current bar
Example:

python
opening_price = data.open
print(f"Market opened at ${opening_price:.2f}")

high

Type: float
Description: Highest price during the current bar
Example:

python
daily_high = data.high
if data.close == data.high:
    print("Closing at the high of the day - bullish!")

low

Type: float
Description: Lowest price during the current bar
Example:

python
daily_low = data.low
support_level = daily_low * 0.99  # 1% below low

close

Type: float
Description: Closing price of the current bar (current price)
Example:

python
current_price = data.close
print(f"Current price: ${current_price:.2f}")

volume

Type: int
Description: Number of shares traded during the current bar
Example:

python
current_volume = data.volume
if current_volume > 1000000:
    print("High volume day!")

Methods

Technical Indicators

sma(period)

Calculate Simple Moving Average

Parameters:

  • period (int): Number of bars to average

Returns: float - SMA value or NaN if insufficient data

Example:

python
sma_20 = data.sma(20)   # 20-period simple moving average
sma_50 = data.sma(50)   # 50-period simple moving average

if sma_20 > sma_50:
    print("Short-term trend is up")

Common Periods:

  • 9, 20: Short-term trend
  • 50: Medium-term trend
  • 200: Long-term trend

ema(period)

Calculate Exponential Moving Average

Parameters:

  • period (int): Number of bars for EMA calculation

Returns: float - EMA value or NaN if insufficient data

Example:

python
ema_12 = data.ema(12)   # Fast EMA
ema_26 = data.ema(26)   # Slow EMA

# MACD calculation (manual)
macd_line = ema_12 - ema_26

Key Differences from SMA:

  • Gives more weight to recent prices
  • Reacts faster to price changes
  • Common in MACD and trend following

rsi(period)

Calculate Relative Strength Index

Parameters:

  • period (int): Number of bars for RSI (default: 14)

Returns: float - RSI value between 0 and 100, or NaN

Example:

python
rsi_14 = data.rsi(14)

if rsi_14 < 30:
    print(f"RSI {rsi_14:.1f} - Oversold condition")
elif rsi_14 > 70:
    print(f"RSI {rsi_14:.1f} - Overbought condition")
else:
    print(f"RSI {rsi_14:.1f} - Neutral")

RSI Levels:

  • < 30: Oversold (potential buy)
  • 30-70: Normal range
  • 70: Overbought (potential sell)

  • < 20 or > 80: Extreme levels

history(field, periods)

Get historical values for any field

Parameters:

  • field (str): Column name ('open', 'high', 'low', 'close', 'volume')
  • periods (int): Number of historical bars to retrieve

Returns: List[float] - Historical values (oldest first)

Example:

python
# Get last 10 closing prices
close_history = data.history('close', 10)

# Calculate price momentum
if len(close_history) >= 10:
    momentum = (close_history[-1] - close_history[0]) / close_history[0]
    print(f"10-bar momentum: {momentum:.2%}")

# Find highest high in last 20 bars
high_history = data.history('high', 20)
resistance = max(high_history)

# Calculate average volume
volume_history = data.history('volume', 30)
avg_volume = sum(volume_history) / len(volume_history)

Advanced Usage

Combining Indicators

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    # Combine multiple indicators for stronger signals
    sma_cross = data.sma(10) > data.sma(30)
    rsi_confirm = 40 < data.rsi(14) < 60
    volume_surge = data.volume > sum(data.history('volume', 10)) / 10 * 1.5
    
    if sma_cross and rsi_confirm and volume_surge:
        return {'symbol': 'AAPL', 'action': 'buy', 'quantity': 100}

Custom Calculations

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    # Bollinger Bands
    sma = data.sma(20)
    closes = data.history('close', 20)
    
    # Calculate standard deviation manually
    mean = sum(closes) / len(closes)
    variance = sum((x - mean) ** 2 for x in closes) / len(closes)
    std_dev = variance ** 0.5
    
    upper_band = sma + (2 * std_dev)
    lower_band = sma - (2 * std_dev)
    
    # Trade the bands
    if data.close <= lower_band:
        return buy('AAPL', 100)  # Buy at support
    elif data.close >= upper_band:
        return sell('AAPL', 'all')  # Sell at resistance

Handling Missing Data

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    # Always check if indicators are ready
    sma_50 = data.sma(50)
    
    # Check for NaN (indicator not ready)
    if sma_50 != sma_50:  # NaN != NaN is True
        print("Need more data for 50-day SMA")
        return None
    
    # Safe to use indicator
    if data.close > sma_50:
        return buy('AAPL', 100)

Multi-Timeframe Analysis

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    # Different timeframes using different periods
    short_trend = data.sma(5) > data.sma(10)    # Very short term
    medium_trend = data.sma(20) > data.sma(50)  # Medium term
    long_trend = data.sma(50) > data.sma(200)   # Long term
    
    # All timeframes must align
    if short_trend and medium_trend and long_trend:
        print("All timeframes bullish - strong buy signal")
        return buy('AAPL', '20%')  # Larger position

Common Patterns

Trend Following

python
# Classic moving average crossover
if data.sma(50) > data.sma(200):  # Golden cross
    return buy(symbol, 100)
elif data.sma(50) < data.sma(200):  # Death cross
    return sell(symbol, 'all')

Mean Reversion

python
# Buy oversold, sell overbought
rsi = data.rsi(14)
if rsi < 30 and portfolio.position(symbol) == 0:
    return buy(symbol, 100)
elif rsi > 70 and portfolio.position(symbol) > 0:
    return sell(symbol, 'all')

Breakout Trading

python
# Buy on 20-day high breakout
highs = data.history('high', 20)
if data.close > max(highs[:-1]):  # Exclude current bar
    return buy(symbol, 100)

Volume Analysis

python
# Trade only on high volume
avg_volume = sum(data.history('volume', 20)) / 20
if data.volume > avg_volume * 2:  # 2x average volume
    if data.close > data.open:  # Bullish bar
        return buy(symbol, 100)

Performance Tips

  1. Cache Calculations: Indicators are cached per bar automatically
  2. Check for NaN: Always verify indicators are ready before using
  3. Minimize History Calls: Store frequently used history in variables
  4. Use Appropriate Periods: Ensure enough data exists for your indicators

Error Handling

python
def safe_indicator_usage(data):
    """Example of safe indicator usage"""
    
    try:
        # Get indicator
        sma = data.sma(50)
        
        # Check if valid
        if sma != sma:  # NaN check
            return None
            
        # Use indicator
        return sma
        
    except Exception as e:
        print(f"Error calculating indicator: {e}")
        return None

Limitations

  • Historical data only (no future peeking)
  • Limited to available symbols (AAPL, GOOGL, MSFT, TSLA, AMZN)
  • Minute-bar resolution only
  • Indicators calculated on-the-fly (not pre-computed)

See also: Portfolio API | Order Functions | Strategy Examples

Test your trading strategies risk-free with professional backtesting.