I wanted to demo a simple way to develop and test an algorithm with one stock, and then abstract the idea to several stocks in a way that minimizes the risk of breaking what you have already done.
It's easier to know that something works when you only use one stock to test it, but a lot of the time, you don't want to just use one stock. The majority of the algorithms I have seen in Quantopian use some type of for loop to apply the same logic to several stocks, which is fine, but you run the risk of breaking something in the process of adding the extra logic.
Here's a different way apply the same logic to several stocks, but with minimal change to the existing code that you already know works. This is also demos some of the beauty of object oriented programming.
- Write an algo using 1 stock, and make sure it works.
- Indent the handle_data function and make it a class.
- Give the class an appropriate initialize function (init) and change all of the context variables to "self."
- Create several instances of the new class, each with its own single stock.
- Have the Quantopian handle_data function call the handle_data function of each instance.
This backtest is the first example algo from the help docs with the comments stripped out and a 20 day moving average instead of 5. The next reply is the same algorithm but with multiple stocks using the method described above.
If you aren't familiar with object oriented programming, it can be tough to wrap your head around at first, but I promise that once you get the hang of it, it will become indispensable.
I hope some of you find this helpful.