Back to Community
How to manually adjust stored stock price after a split?

My algorithm is performing buys when it should not, and it is suspiciously right at the time of a stock split.

In my handle_data function I have the following code:

elif context.ACTIVE_INVESTMENT == 1 and ((current_price/context.LAST_BUY_IN) < context.REBUY_TARGET_PERCENTAGE):  

The ratio of (current_price / LAST_BUY_IN) is getting thrown off because of the split.

I understand that I am not supposed to be using global (context) variables for this very reason, but I don't know how else to do it.
I need to decide whether to buy based on what the purchase price of the stock was at the time of the last purchase (which is in a previous loop of the simulation.)
I have recorded that, but the split causes it to no longer be accurate.
It doesn't appear that the Position object has a last_purchase_price property, which I think would solve my problem.

Two possible solutions, neither of which I know how to do:

  1. Keep the LAST_BUY_IN variable inside the handle_data function, and have it automatically "normalize" the previous buy price.
  2. Manually normalize the previous buy price by specifying the previous date of purchase (don't know how to record), and then calling a function to adjust the price at that date to the current date (don't know if this is possible.)

Any advice on the best way to handle this?

3 responses


Cost basis in this context refers to the average entry price and is adjusted for splits and dividends.

Yes, that is close but not exactly what I need.
I am interested in the ‘last purchase price’, not the average price of the stock across multiple buys.

You could count minutes since the last purchase, and then just use:
data.history(stock, 'price', minutes_since_last_purchase[stock], '1m')[0]

I'm not sure if there's a better way on Quantopian to look up the price for an asset at a specific time in history, but if you find out, I'd be curious to know.