book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Indicators

Trade Bar Indicators

Introduction

This page explains how to create, update, and visualize LEAN TradeBar indicators.

Create Subscriptions

You need to subscribe to some market data in order to calculate indicator values.

Select Language:
qb = QuantBook()
symbol = qb.add_equity("SPY").symbol

Create Indicator Timeseries

You need to subscribe to some market data and create an indicator in order to calculate a timeseries of indicator values. In this example, use a 20-period VolumeWeightedAveragePriceIndicator indicator.

Select Language:
vwap = VolumeWeightedAveragePriceIndicator(20)

You can create the indicator timeseries with the Indicator helper method or you can manually create the timeseries.

Indicator Helper Method

To create an indicator timeseries with the helper method, call the Indicator method.

Select Language:
# Create a dataframe with a date index, and columns are indicator values.
vwap_dataframe = qb.indicator(vwap, symbol, 50, Resolution.DAILY)
Historical VWAP data

Manually Create the Indicator Timeseries

Follow these steps to manually create the indicator timeseries:

  1. Get some historical data.
  2. Select Language:
    # Request historical trading data with the daily resolution.
    history = qb.history[TradeBar](symbol, 70, Resolution.DAILY)
  3. Set the indicator window.size for each attribute of the indicator to hold their values.
  4. Select Language:
    # Set the window.size to the desired timeseries length
    vwap.window.size = 50
  5. Iterate through the historical market data and update the indicator.
  6. Select Language:
    for bar in history:
        vwap.update(bar)
  7. Populate a DataFrame with the data in the Indicator object.
  8. vwap_dataframe = pd.DataFrame({
        "current": pd.Series({x.end_time: x.value for x in vwap}))
    }).sort_index()
    Historical VWAP data

Plot Indicators

Follow these steps to plot the indicator values:

  1. Call the plot method.
  2. vwap_indicator.plot(title="SPY VWAP(20)", figsize=(15, 10))
  3. Show the plots.
  4. plt.show()
    Line plot of VWAP

Examples

The following examples demonstrate some common practices for researching with trade bar indicators.

Example 1: Quick Backtest On MoneyFlowIndex

The following example demonstrates a quick backtest to testify the effectiveness of a Money Flow Index mean-reversal under the research enviornment.

Select Language:
# Instantiate the QuantBook instance for researching.
qb = QuantBook()
# Request SPY data to work with the indicator.
symbol = qb.add_equity("SPY").symbol

# Get the historical data for trading.
history = qb.history(symbol, 252, Resolution.DAILY).close.unstack(0).iloc[:, 0]
history = history.groupby(history.index.date).sum()

# Create the Money Flow Index with parameters to be studied.
indicator = MoneyFlowIndex(10)

# Get the indicator history of the indicator.
indicator_dataframe = qb.indicator(indicator, symbol, 252, Resolution.DAILY)
indicator_dataframe = indicator_dataframe.groupby(indicator_dataframe.index.date).sum()

# Match index.
common_ix = sorted(set(indicator_dataframe.index).intersection(set(history.index)))
history = history.loc[common_ix]
indicator_dataframe = indicator_dataframe.loc[common_ix]

# Create a order record and return column.
# Buy if the asset is underprice (below 20), sell if overpriced (above 80)
indicator_dataframe["position"] = indicator_dataframe.apply(lambda x: 1 if x.current < 20 else -1 if x.current > 80 else 0, axis=1)
# Get the 1-day forward return.
indicator_dataframe["return"] = history.pct_change().shift(-1).fillna(0)
indicator_dataframe["return"] = indicator_dataframe["position"] * indicator_dataframe["return"]

# Obtain the cumulative return curve as a mini-backtest.
equity_curve = (indicator_dataframe["return"] + 1).cumprod()
equity_curve.plot(title="Equity Curve", ylabel="Equity", xlabel="time")

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: