In the Quantopian emails that I send out, I've added a new section that we refer to as the "weekly spark." The intent is to give you a general algorithmic idea, walk you through it, and help spark your imagination for new ideas and variations.
This week's concept is to watch the recent maximum and minimum prices, and then trade when the price hits one of them. You have choices in how to implement this. If you think that the stock is momentum-driven, you can use a short time frame, and then go long when it hits the max and go short when it hits the minimum. That's essentially riding the momentum. Or you can use max and min to work a contrarian play: use a longer window, sell when it hits the high, and buy when it hits the low. Here's what the contrarian version looks like in a bit of code, and a bit of explanation of the code:
def minmax(datapanel, sid):
prices_df = datapanel['price']
min_price = prices_df[sid].min()
max_price = prices_df[sid].max()
if data[sid].price < min_price :
if data[sid].price > min_price :
The first line creates a datapanel for our stock. That datapanel is the last 10 days of data (defined by window_length). The datapanel is reloaded once per day (defined by refresh_period). The minmax function queries that datapanel to find the highest and lowest prices in those 10 days of data. Then, if we go over that max price, we sell. If we go lower than the min price, we buy. The theory is that the price of the stock is reasonably stable, and you're betting that any movement to an extreme will later return to the mean.
Below is a full implementation of the momentum version of a min/max algorithm. When you dig into this example, you'll see that the order management gets a bit tricky. It's not enough to just buy and sell in this case; you also have to close out your position at the right times, too. You should clone that algorithm and create your own version. You can try it on different stocks and see which ones are momentum and which ones are more stable. You can try different window lengths. You can change the order management.
(This example is the same example that is in the help docs - so if you already used the batch transform example, then you've seen this one before!)
Have any comments or questions?