@ David
The 'as_matrix' method simply turns the output of the 'data.history' method from a Pandas dataframe to a Numpy array (not a matrix which is a bit misleading). See http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.as_matrix.html. Anyway, I'm not sure why this is needed. It would seem to be easier to just leave it as a pandas dataframe.
The bigger picture is this code is way bloated for what you are trying to accomplish. No wonder you may not understand it. Would you be open to starting fresh from a simpler version? I could maybe help.
One question. When you say "stocks that have gaped up 8% or more for the day" what exactly do you mean? It appears in your algorithm that you get 31 days worth of data but only use the current day. Is that correct? Do you want the gap to be the difference between high and low for the current day, or from the previous day (remember if you trade at market open there will only be 1 minute of data to get highs and lows).