Indicators
Bar Indicators
Create Subscriptions
You need to subscribe to some market data in order to calculate indicator values.
var qb = new QuantBook(); var symbol = qb.AddEquity("SPY").Symbol;
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 AverageTrueRange
indicator.
var atr = new AverageTrueRange(20);
atr = AverageTrueRange(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.
// Create a dataframe with a date index, and columns are indicator values. var atrIndicator = qb.Indicator(atr, symbol, 50, Resolution.Daily);
# Create a dataframe with a date index, and columns are indicator values. atr_dataframe = qb.indicator(atr, symbol, 50, Resolution.DAILY)
Manually Create the Indicator Timeseries
Follow these steps to manually create the indicator timeseries:
- Get some historical data.
- Set the indicator
Window.Size
window.size
for each attribute of the indicator to hold their values. - Iterate through the historical market data and update the indicator.
- Display the data.
- Populate a
DataFrame
with the data in theIndicator
object.
// Request historical trading data with the daily resolution. var history = qb.History(symbol, 70, Resolution.Daily);
# Request historical trading data with the daily resolution. history = qb.history[TradeBar](symbol, 70, Resolution.DAILY)
// Set the window.size to the desired timeseries length atr.Window.Size = 50; atr.TrueRange.Window.Size = 50;
# Set the window.size to the desired timeseries length atr.window.size = 50 atr.true_range.window.size = 50
foreach (var bar in history) { atr.Update(bar); }
for bar in history: atr.update(bar)
foreach (var i in Enumerable.Range(0, 5).Reverse()) { Console.WriteLine($"{atr[i].EndTime:yyyyMMdd} {atr[i].Value:f4} {atr.TrueRange[i].Value:f4}"); }
atr_dataframe = pd.DataFrame({ "current": pd.Series({x.end_time: x.value for x in atr}), "truerange": pd.Series({x.end_time: x.value for x in atr.true_range}) }).sort_index()
Plot Indicators
Jupyter Notebooks don't currently support libraries to plot historical data, but we are working on adding the functionality. Until the functionality is added, use Python to plot bar indicators.
You need to create an indicator timeseries to plot the indicator values.
Follow these steps to plot the indicator values:
- Call the
plot
method. - Show the plots.
atr_indicator.plot(title="SPY ATR(20)", figsize=(15, 10))
plt.show()