SMAStrategy - alex-ruperto/Stock-Predictor GitHub Wiki
Simple Moving Average (SMA) Strategy
Overview
The Simple Moving Average (SMA) Strategy is one of the most widely recognized technical analysis tools. This strategy utilizes two SMA indicators, one with a shorter period and another with a longer period, to generate trading signals based on crossovers. Note: This is currently not being used.
Implementation and Libraries Used
backtrader library
Used to calculate two SMA indicators, a long and a short one based on short_period and long_period parameters, and a crossover indicator to signify when the two crossover. Also provides the engine for backtesting, which is called cerebro. The strategy is implemented in a backtrader strategy class. The engine performs the backtest on whatever yfinance library it is fed.
yfinance library
Fetches data from a chosen stock at a chosen date range. Currently only used to provide day-to-day price movement, not intraday.
plotly library
Used to create the figure that visualizes the data. Separates it into three subplots. The data is transformed from what backtrader calculated to data that plotly can read.
numpy
Used for list/array conversions.
Parameters
short_period
: Number of periods used for the short SMA. Default is set to 50.long_period
: Number of periods used for the long SMA. Default is set to 200.
Indicators
sma_short
: Represents the short period SMA.sma_long
: Represents the long period SMA.crossover
: This indicator signals when a crossover occurs betweensma_short
andsma_long
.
Trading Logic
- Golden Cross: When the
sma_short
crosses above thesma_long
, it signifies a potential bullish trend. The strategy sets a "buy" pending order. - Death Cross: Conversely, when the
sma_short
goes below thesma_long
, it indicates a potential bearish trend. The strategy sets a "sell" pending order.
For added precision, the strategy uses a confirmation window (denoted as confirmation_days
). Only when the crossover is consistent throughout this confirmation period does the strategy act on the pending order.
Order Execution
The strategy, upon a confirmed signal, invests 10% of the available cash into the asset, with a minimum investment size of 1 unit of the asset.
Key Features
- Uses a
confirmation_days
parameter to add robustness to the trading signals. - Maintains a history of crossovers to validate against the confirmation window.
- Dynamically calculates the size to buy based on available cash.
- Ensures that the strategy does not short-sell.
Further Improvements
While the SMA strategy provides a solid foundation for trading based on historical price data, like all strategies, it has its limitations. Traders can consider combining it with other technical indicators or implementing risk management techniques to optimize returns.
Feel free to customize the provided content to better fit the specifics of your implementation or to add/remove sections as needed!