Hello,
I already posted about this subject here:
https://www.quantopian.com/posts/introducing-the-pipeline-api#561bc7b2e2fd0e7b2f0004d3
and here:
https://www.quantopian.com/posts/fundamental-history-based-algo#561e759a0c3c281910000259
but now I decided to start a new post in order to better define the scope of the problem.
The question is, how could one get different time horizons for the fundamentals data, given that the Quantopian fundamentals data always attain to the most recent quarter?
For example, how can I write a factor that takes care of the Total Revenue of the last 12 months?
I implemented the following solution, but it's to slow and a Timeoutexception occurs:
days_in_quarter = 70
num_of_quarters = 4
def retrieve_ttm(array):
# Differences between the next and the current value, after havind convertet NaN and Inf to numbers
diff = np.diff(np.nan_to_num(array))
# Track the indexes where the difference isn't zero: a change has occurred. Shift the indexes by one.
idx = np.where(diff != 0)[0] + 1
# Add zero as the first index (by definition)
idx = np.insert(idx, 0, 0)
# Look for periods without changes longer than 'days_in_quarter'
dup = np.diff(idx) > days_in_quarter
# Add an index in order to duplicate the previous value
idx = np.append(idx, idx[dup] + days_in_quarter)
# Sort the index for consistence
idx = np.sort(idx)
return array[idx[-num_of_quarters:]]