The ipo_date is a numpy.datetime64 type object. Best to use it as is or maybe covert to a pandas Timestamp object. The pandas Timestamp objects can easily be subtracted to produce a Pandas Timedelta object. The Timedelta object has a 'days' attribute to easily get the delta days between two Timestamps.
That all said. The code above DOES work however, it doesn't handle exceptions well in the case that the IPO date doesn't exist. You were probably getting an error similar to "'NaTType' object has no attribute 'days'"? Below is basically the same code but with handling for that error and using the numpy apply_along_axis method in place of a for loop. It returns a real number indicating the days since the IPO. MAybe divide by 365 to get close to the years since the IPO.
import pandas as pd
class StockAge(CustomFactor):
inputs = [Fundamentals.ipo_date]
window_length = 1
def compute(self, today, assets, out, ipo_dates):
def get_delta_days(ipo_dates):
# Convert last known (ie -1) ipo_date to Timestamps
# Subtract ipo date from current date
# Return delta days
ipo = pd.Timestamp(ipo_dates[-1], tz='UTC', offset='C')
delta = today - ipo
return None if pd.isnull(delta) else float(delta.days)
# Apply the above function across each column and output the values
out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)
Note that one can get the ipo date without a custom factor by just using the '.latest' attribute
Fundamentals.ipo_date.latest
That value can be used outside of the pipeline and compared to the current date. See attached notebook.