In the world of algorithmic trading, implementing strategies using pre-built libraries can significantly speed up development. One such library is PyAlgoTrade, which is a Python library specifically designed for retail algorithmic traders and developers. In this article, we'll walk through how to implement a basic moving average strategy using PyAlgoTrade. This strategy involves generating buy and sell signals based on calculated moving averages of stock prices.
Setting Up PyAlgoTrade
Before we begin coding, ensure you have Python installed on your system. PyAlgoTrade can be installed using pip, the package manager for Python. Use the following command:
pip install pyalgotrade
Understanding the Moving Average Strategy
The moving average strategy is a simple technical analysis tool that helps smooth out price data by creating a constantly updated average price. The strategy involves two types of moving averages:
- Simple Moving Average (SMA): The straightforward average of a set number of the latest prices.
- Exponential Moving Average (EMA): A bit more complex, it gives more weight to recent prices, reacting more quickly to recent price fluctuations.
In this article, we'll use simple moving averages (SMA) for calculations. The strategy typically utilizes two SMAs of different periods, commonly referred to as the short-term and long-term moving averages. A buy signal is generated when the short-term SMA crosses above the long-term SMA, while a sell signal is generated when the opposite occurs.
Implementing the Strategy with PyAlgoTrade
Let's look at how we can use PyAlgoTrade to implement this basic moving average strategy.
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
class SMAStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, smaPeriodShort, smaPeriodLong):
super(SMAStrategy, self).__init__(feed)
self.__instrument = instrument
self.__smaShort = ma.SMA(feed[instrument].getCloseDataSeries(), smaPeriodShort)
self.__smaLong = ma.SMA(feed[instrument].getCloseDataSeries(), smaPeriodLong)
def onBars(self, bars):
if cross.cross_above(self.__smaShort, self.__smaLong) > 0:
self.enterLong(self.__instrument, 10)
elif cross.cross_below(self.__smaShort, self.__smaLong) > 0:
self.enterShort(self.__instrument, 10)
In this code snippet, we define a class SMAStrategy
that extends PyAlgoTrade's BacktestingStrategy
class. Our strategy initialization accepts a data feed, the stock symbol to trade, and the periods for the short and long SMAs. During every evaluation step (using onBars
), we check for crossovers. If the short SMA crosses above the long SMA, we buy; if it crosses below, we sell.
Running the Trading Strategy
To run our strategy, we need historical price data. We can use data from sources like Yahoo Finance. Here's an example on how you would set this up with PyAlgoTrade:
def run_strategy():
# Load the Yahoo feed data
feed = yahoofeed.Feed()
feed.addBarsFromCSV("aapl", "aapl-2019.csv")
# Evaluate the strategy with 10-day and 30-day SMAs
smastrategy = SMAStrategy(feed, "aapl", 10, 30)
smastrategy.run()
# You can process strategy results here
run_strategy()
In the run_strategy
function, we load historical data for Apple, with stock ticker AAPL
. You can obtain CSV data files from online APIs or manually download them from financial websites. The function run()
executes the strategy with the chosen SMA periods.
Evaluating Results and Next Steps
Once you execute the strategy, you can analyze the results to evaluate its profitability. PyAlgoTrade provides tools for further analysis, such as calculating returns, assessing risk via drawdowns, and more. This basic strategy could be expanded and integrated with others, providing a foundation for more sophisticated trading techniques.
Remember, while backtesting strategies is essential, real-time trading poses different challenges. Always consider slippage, transaction fees, and variations in fill prices when moving from backtesting to live trading.