One needs to apply the linear regression function to each asset separately. The data (close prices in this case) are passed to the custom factor's compute method as a 2D numpy array. There is a row for each date and a column for each asset. One needs to apply the linear regression function to each column to get a slope for each asset. The best way to apply a function to each asset is to use the numpy apply_along_axis
method (https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html).
So your (slightly modified) code works with the addition of this method in the last line
class SlopeAdj(CustomFactor):
# Default inputs
inputs = [USEquityPricing.close]
window_length = 100
# Compute SLope Adj
def compute(self, today, assets, out, close):
window_length = 100
def linreg(y):
# define X - just index on X axis
x = len(y)
X = range(1, (x + 1), 1)
X = sm.add_constant(X) # aparently needed. adds column of ones to array
# define Y
Y = y.tolist()
flat_list_prices = []
for item in Y:
flat_list_prices.append(item) # don't need the [0]
Y = [math.log(i) for i in flat_list_prices]
# do lin reg
model = regression.linear_model.OLS(Y, X).fit()
slope = model.params[1] # this is how to access b slope parameter in the model object
return slope
out[:] = np.apply_along_axis(linreg, 0, close)
However, this can be simplified a bit. Since the inputs are numpy arrays it's fast and easy to use numpy methods rather than straight python. Both creating the X array and then getting the log prices can each be done efficiently with numpy methods. Here's an equivalent custom factor using numpy
class Slope_Using_Numpy(CustomFactor):
# Default inputs
inputs = [USEquityPricing.close]
window_length = 100
def compute(self, today, asset_ids, out, close_prices):
# Define the function one would like to apply for each asset
# The function will be passed a 1D numpy array of values
# In this case the close prices for past 100 days
def slope_of_log_prices(prices):
# create an array to regress against having a length equal to the price data length
X = np.arange(self.window_length)
X = sm.add_constant(X) # Adds column of ones to array for intercept
# Want to get the slope of the log prices so find the log values
log_prices = np.log(prices)
# do linear regression using statsmodels OLS
model = regression.linear_model.OLS(log_prices, X).fit()
slope = model.params[1] # this is how to access b slope parameter in the model object
return slope
# Apply the above function across each column and output the values
# The zero means axis 0 which passes columns of the ndarray 'close_prices'
out[:] = np.apply_along_axis(slope_of_log_prices, 0, close_prices)
See the attached notebook. You may also want to check out this post for more info on the apply_along_axis
method. https://www.quantopian.com/posts/custom-factor-1
Disclaimer
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.