Another bit of practice in python...
I've built a number of S&R type indicators/pattern detectors over the years, never in python though, not very easy that. But here's a variation. The below code looks for isolated lows which then get added to a list for each security. In the backtest you'll see that it looks back 200 periods (everyday) and identifies lows that are the lowest low to 30 periods to either side. A significant low. It rounds the price and adds that low to the support list.
def BuildSupportLevels(context, data):
result = {}
l = IsolationPeriods
lowAll = history(LookbackPeriods, "1d", "low")
for stock in data:
result[stock] = []
lows = lowAll[stock]
try:
for i in xrange(IsolationPeriods + 1, LookbackPeriods - (IsolationPeriods + 1)):
if (lows[i] < min(lows[i+1:i+l])):
if (lows[i] < min(lows[(i-l):i])):
#print("Lowest low {0} {1:.2f}".format(lows.index[i], lows[i]))
level = round(lows[i], 0)
if (level not in result[stock]):
result[stock].append(level)
except:
continue
return result
In the trading test it looks for a rounded current price that matches any of the lowest lows (and highest highs for resistance). If so it buys them.
The sell short code is commented out. I may readdress this code in the future and fix issues I as I mull over the technique. There are lots of holes in this approach but I'm not gonna get into them right now.
SupportLevels = BuildSupportLevels(context, data)
for stock in data:
if (round(data[stock].close_price, 0) in SupportLevels[stock] and data[stock].mavg(7) > data[stock].close_price):
eligibleLong.append(stock)