@Saleem
To understand custom factors one first needs to understand what the parameters to the 'compute' method are - especially the inputs. Look this over from the Q documentation https://www.quantopian.com/help#quantopian_pipeline_CustomFactor . Basically the inputs are 2D numpy arrays. The rows (axis 0) represent trading days. The last row is the last trading day. The number of rows is determined by the value of 'window_length'. The columns (axis 1) represents each of the securities.
'volume[-1]' returns the last row of data from the numpy array 'volume'. Maybe look at some tutorials on python and numpy array indexing and slicing like https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
The following works too without an index. However, I included the index [-1] in case the window_length was ever changed from 1. In that case this will average across all stocks AND all days.
class Average_Universe_Volume(CustomFactor):
'''
Returns the average volume of the securities passed in mask (or ALL securities if no mask is provided)
The average is returned as the same factor value for all securities
'''
inputs = [USEquityPricing.volume]
window_length = 1
def compute(self, today, assets, out, volume):
# get the average of the latest volumes
average_volume = np.nanmean(volume)
out[:] = average_volume
To return the volume for QQQ as a factor for all stocks, one would do something like this.
class QQQ_Volume(CustomFactor):
'''
This is a factor to return the volume of QQQ for all securities.
Just make sure that QQQ is in the universe of assets passed to the factor (ie don't mask QQQ out)
'''
inputs = [USEquityPricing.volume]
window_length = 1
def compute(self, today, assets, out, volume):
qqq_index = np.where(assets == 19920) # 19920 is the SID of QQQ
out[:] = close[-1, qqq_index]