Two ways to get the ran of the last close price compared to the previous n close prices. The window length is the 'n'.
#Import things we'll need
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
import numpy as np
import pandas as pd
# Class using a Pandas dataframe
class RankOfLastPrice_pd(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 1
def compute(self, today, assets, out, prices):
# first change the numpy array into a dataframe then use rank method
prices_df = pd.DataFrame(prices)
out[:] = prices_df.rank(axis=0).tail(1)
# Class using Numpy methods
class RankOfLastPrice_np(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 2
def compute(self, today, assets, out, prices):
# This doesn't handle duplicates, NaNs, and special case of n=1 well
out[:] = prices.argsort(axis=0).argsort(axis=0)[-1] + 1
# Create a pipeline showing our two versions of ranking
p = Pipeline()
p.add(RankOfLastPrice_pd(window_length = 3), 'rank_pd')
p.add(RankOfLastPrice_np(window_length = 3), 'rank_np')
results = run_pipeline(p, '2016-03-01', '2016-03-01')
results