Supported Indicators
Simple Moving Average
Introduction
This indicator represents the traditional simple moving average indicator (SMA)
To view the implementation of this indicator, see the LEAN GitHub repository.
Using SMA Indicator
To create an automatic indicators for SimpleMovingAverage
, call the SMA
helper method from the QCAlgorithm
class. The SMA
method creates a SimpleMovingAverage
object, hooks it up for automatic updates, and returns it so you can used it in your algorithm. In most cases, you should call the helper method in the Initialize
initialize
method.
public class SimpleMovingAverageAlgorithm : QCAlgorithm { private Symbol _symbol; private SimpleMovingAverage _sma; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _sma = SMA(_symbol, 20); } public override void OnData(Slice data) { if (_sma.IsReady) { // The current value of _sma is represented by itself (_sma) // or _sma.Current.Value Plot("SimpleMovingAverage", "sma", _sma); // Plot all properties of sma Plot("SimpleMovingAverage", "rollingsum", _sma.RollingSum); } } }
class SimpleMovingAverageAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._sma = self.sma(self._symbol, 20) def on_data(self, slice: Slice) -> None: if self._sma.is_ready: # The current value of self._sma is represented by self._sma.current.value self.plot("SimpleMovingAverage", "sma", self._sma.current.value) # Plot all attributes of self._sma self.plot("SimpleMovingAverage", "rolling_sum", self._sma.rolling_sum.current.value)
The following reference table describes the SMA
method:
sma(symbol, period, resolution=None, selector=None)
[source]Creates an SimpleMovingAverage indicator for the symbol. The indicator will be automatically updated on the given resolution.
- symbol (Symbol) — The symbol whose SMA we want
- period (int) — The period of the SMA
- resolution (Resolution, optional) — The resolution
- selector (Callable[IBaseData, float], optional) — x.Value)
The SimpleMovingAverage for the given parameters
SMA(symbol, period, resolution=None, selector=None)
[source]Creates an SimpleMovingAverage indicator for the symbol. The indicator will be automatically updated on the given resolution.
- symbol (Symbol) — The symbol whose SMA we want
- period (Int32) — The period of the SMA
- resolution (Resolution, optional) — The resolution
- selector (Func<IBaseData, Decimal>, optional) — x.Value)
The SimpleMovingAverage for the given parameters
If you don't provide a resolution, it defaults to the security resolution. If you provide a resolution, it must be greater than or equal to the resolution of the security. For instance, if you subscribe to hourly data for a security, you should update its indicator with data that spans 1 hour or longer.
For more information about the selector argument, see Alternative Price Fields.
For more information about plotting indicators, see Plotting Indicators.
You can manually create a SimpleMovingAverage
indicator, so it doesn't automatically update. Manual indicators let you update their values with any data you choose.
Updating your indicator manually enables you to control when the indicator is updated and what data you use to update it. To manually update the indicator, call the Update
update
method with time/number pair or an IndicatorDataPoint
. The indicator will only be ready after you prime it with enough data.
public class SimpleMovingAverageAlgorithm : QCAlgorithm { private Symbol _symbol; private SimpleMovingAverage _sma; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _sma = new SimpleMovingAverage(20); } public override void OnData(Slice data) { if (data.Bars.TryGetValue(_symbol, out var bar)) { _sma.Update(bar.EndTime, bar.Close); } if (_sma.IsReady) { // The current value of _sma is represented by itself (_sma) // or _sma.Current.Value Plot("SimpleMovingAverage", "sma", _sma); // Plot all properties of sma Plot("SimpleMovingAverage", "rollingsum", _sma.RollingSum); } } }
class SimpleMovingAverageAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._sma = SimpleMovingAverage(20) def on_data(self, slice: Slice) -> None: bar = slice.bars.get(self._symbol) if bar: self._sma.update(bar.EndTime, bar.Close) if self._sma.is_ready: # The current value of self._sma is represented by self._sma.current.value self.plot("SimpleMovingAverage", "sma", self._sma.current.value) # Plot all attributes of self._sma self.plot("SimpleMovingAverage", "rolling_sum", self._sma.rolling_sum.current.value)
To register a manual indicator for automatic updates with the security data, call the RegisterIndicator
register_indicator
method.
public class SimpleMovingAverageAlgorithm : QCAlgorithm { private Symbol _symbol; private SimpleMovingAverage _sma; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _sma = new SimpleMovingAverage(20); RegisterIndicator(_symbol, _sma, Resolution.Daily); } public override void OnData(Slice data) { if (_sma.IsReady) { // The current value of _sma is represented by itself (_sma) // or _sma.Current.Value Plot("SimpleMovingAverage", "sma", _sma); // Plot all properties of sma Plot("SimpleMovingAverage", "rollingsum", _sma.RollingSum); } } }
class SimpleMovingAverageAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._sma = SimpleMovingAverage(20) self.register_indicator(self._symbol, self._sma, Resolution.DAILY) def on_data(self, slice: Slice) -> None: if self._sma.is_ready: # The current value of self._sma is represented by self._sma.current.value self.plot("SimpleMovingAverage", "sma", self._sma.current.value) # Plot all attributes of self._sma self.plot("SimpleMovingAverage", "rolling_sum", self._sma.rolling_sum.current.value)
The following reference table describes the SimpleMovingAverage
constructor:
SimpleMovingAverage
Represents the traditional simple moving average indicator (SMA)
get_enumerator()
Returns an enumerator that iterates through the history window.
IEnumerator[IndicatorDataPoint]
reset()
Resets this indicator to its initial state
to_detailed_string()
Provides a more detailed string of this indicator in the form of {Name} - {Value}
str
update(time, value)
Updates the state of this indicator with the given value and returns true if this indicator is ready, false otherwise
- time (datetime)
- value (float)
bool
update(input)
Updates the state of this indicator with the given value and returns true if this indicator is ready, false otherwise
- input (IBaseData)
bool
consolidators
The data consolidators associated with this indicator if any
The data consolidators associated with this indicator if any
ISet[IDataConsolidator]
current
Gets the current state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
Gets the current state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
IndicatorDataPoint
is_ready
Gets a flag indicating when this indicator is ready and fully initialized
Gets a flag indicating when this indicator is ready and fully initialized
bool
item
Indexes the history windows, where index 0 is the most recent indicator value. If index is greater or equal than the current count, it returns null. If the index is greater or equal than the window size, it returns null and resizes the windows to i + 1.
Indexes the history windows, where index 0 is the most recent indicator value. If index is greater or equal than the current count, it returns null. If the index is greater or equal than the window size, it returns null and resizes the windows to i + 1.
IndicatorDataPoint
name
Gets a name for this indicator
Gets a name for this indicator
str
period
Gets the period of this window indicator
Gets the period of this window indicator
int
previous
Gets the previous state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
Gets the previous state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
IndicatorDataPoint
rolling_sum
A rolling sum for computing the average for the given period
A rolling sum for computing the average for the given period
IndicatorBase[IndicatorDataPoint]
samples
Gets the number of samples processed by this indicator
Gets the number of samples processed by this indicator
int
warm_up_period
Required period, in data points, for the indicator to be ready and fully initialized.
Required period, in data points, for the indicator to be ready and fully initialized.
int
window
A rolling window keeping a history of the indicator values of a given period
A rolling window keeping a history of the indicator values of a given period
RollingWindow[IndicatorDataPoint]
SimpleMovingAverage
Represents the traditional simple moving average indicator (SMA)
GetEnumerator()
Returns an enumerator that iterates through the history window.
IEnumerator[IndicatorDataPoint]
Reset()
Resets this indicator to its initial state
ToDetailedString()
Provides a more detailed string of this indicator in the form of {Name} - {Value}
String
Update(time, value)
Updates the state of this indicator with the given value and returns true if this indicator is ready, false otherwise
- time (DateTime)
- value (decimal)
Boolean
Update(input)
Updates the state of this indicator with the given value and returns true if this indicator is ready, false otherwise
- input (IBaseData)
Boolean
Consolidators
The data consolidators associated with this indicator if any
The data consolidators associated with this indicator if any
ISet<IDataConsolidator>
Current
Gets the current state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
Gets the current state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
IndicatorDataPoint
IsReady
Gets a flag indicating when this indicator is ready and fully initialized
Gets a flag indicating when this indicator is ready and fully initialized
bool
Name
Gets a name for this indicator
Gets a name for this indicator
string
Period
Gets the period of this window indicator
Gets the period of this window indicator
Int32
Previous
Gets the previous state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
Gets the previous state of this indicator. If the state has not been updated then the time on the value will equal DateTime.MinValue.
IndicatorDataPoint
RollingSum
A rolling sum for computing the average for the given period
A rolling sum for computing the average for the given period
IndicatorBase<IndicatorDataPoint>
Samples
Gets the number of samples processed by this indicator
Gets the number of samples processed by this indicator
int
WarmUpPeriod
Required period, in data points, for the indicator to be ready and fully initialized.
Required period, in data points, for the indicator to be ready and fully initialized.
Int32
Window
A rolling window keeping a history of the indicator values of a given period
A rolling window keeping a history of the indicator values of a given period
RollingWindow<IndicatorDataPoint>
[System.Int32]
Indexes the history windows, where index 0 is the most recent indicator value. If index is greater or equal than the current count, it returns null. If the index is greater or equal than the window size, it returns null and resizes the windows to i + 1.
Indexes the history windows, where index 0 is the most recent indicator value. If index is greater or equal than the current count, it returns null. If the index is greater or equal than the window size, it returns null and resizes the windows to i + 1.
IndicatorDataPoint
Visualization
The following image shows plot values of selected properties of SimpleMovingAverage
using the plotly library.
Indicator History
To get the historical data of the SimpleMovingAverage
indicator, call the IndicatorHistory
self.indicator_history
method.
This method resets your indicator, makes a history request, and updates the indicator with the historical data.
Just like with regular history requests, the IndicatorHistory
indicator_history
method supports time periods based on a trailing number of bars, a trailing period of time, or a defined period of time.
If you don't provide a resolution
argument, it defaults to match the resolution of the security subscription.
public class SimpleMovingAverageAlgorithm : QCAlgorithm { private Symbol _symbol; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; var sma = SMA(_symbol, 20); var countIndicatorHistory = IndicatorHistory(sma, _symbol, 100, Resolution.Minute); var timeSpanIndicatorHistory = IndicatorHistory(sma, _symbol, TimeSpan.FromDays(10), Resolution.Minute); var timePeriodIndicatorHistory = IndicatorHistory(sma, _symbol, new DateTime(2024, 7, 1), new DateTime(2024, 7, 5), Resolution.Minute); } }
class SimpleMovingAverageAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol sma = self.sma(self._symbol, 20) count_indicator_history = self.indicator_history(sma, self._symbol, 100, Resolution.MINUTE) timedelta_indicator_history = self.indicator_history(sma, self._symbol, timedelta(days=10), Resolution.MINUTE) time_period_indicator_history = self.indicator_history(sma, self._symbol, datetime(2024, 7, 1), datetime(2024, 7, 5), Resolution.MINUTE)
To make the IndicatorHistory
indicator_history
method update the indicator with an alternative price field instead of the close (or mid-price) of each bar, pass a selector
argument.
var indicatorHistory = IndicatorHistory(sma, 100, Resolution.Minute, (bar) => ((TradeBar)bar).High);
indicator_history = self.indicator_history(sma, 100, Resolution.MINUTE, lambda bar: bar.high) indicator_history_df = indicator_history.data_frame
If you already have a list of Slice objects, you can pass them to the IndicatorHistory
indicator_history
method to avoid the internal history request.
var history = History(_symbol, 100, Resolution.Minute); var historyIndicatorHistory = IndicatorHistory(sma, history);
To access the properties of the indicator history, invoke the property of each IndicatorDataPoint
object.index the DataFrame with the property name.
var rollingsum = indicatorHistory.Select(x => ((dynamic)x).RollingSum).ToList(); // Alternative way // var rollingsum = indicatorHistory.Select(x => x["rollingsum"]).ToList();
rolling_sum = indicator_history_df["rolling_sum"] # Alternative way # rolling_sum = indicator_history_df.rolling_sum