Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to sell only if current price is higher than previous purchase price

Hi guys,

Newbie here. I have searched the Help docs extensively, particularly in the area of portfolio.positions_value etc. however, I have not found any option for me to feed in the VALUE of my most RECENT BUY price (whether that was a year ago or a day ago).

The task at hand is extremely simple, here's a pseudo code to clarify:

Buy at price X
Sell when price is > X

(Obviously I have a whole algorithm with various conditions but it's just this very SIMPLE bit that I haven't cracked yet)

Your help would be massively appreciated!

10 responses

cost basis is what you are looking for -> costBasis = context.portfolio.positions[context.security].cost_basis

Make a If Loop:

#Buys you target stock in integer increments up to your cash position until you run out of money.  Could be modified to be any amount.  
 if cash > current_price:  
        num_shares_to_buy = cash//current_price  
        order(context.security, +num_shares_to_buy)  
        log.info("Buying %s" % (context.security.symbol))

#Sell if the current price is higher than the cost basis.  You could also say "1.2*costBasis" if you want to sell 20% higher or "costBasis + x" if you want to define a discrete number.

    elif current_price > costBasis :  
        order_target(context.security, 0)  
        log.info("Selling %s" % (context.security.symbol))  

Reed,

Thank you very much for your response. I did come across cost_basis however, after I read its description, I excluded it as an option because it is defined as "The volume-weighted average price paid (price and commission) per share in this position".

After a few backtests with "price > costBasis" I was getting very strange inflated buy and sell values - I don't think cost basis is what I'm looking for, unless of course the error is from how I've define the code....

Again, what I'm looking for is something like "latest_order_price" and the description to it would be: "The value in dollars for the most recent order (buy or sell)"

Thanks

@Adam S
Yes cost_basis is now what you asked since it's the average price.
If you want to really have the last price you'll have to handle it by hand. This means placing storing an order's id into a persistent list in context, then at the start of loop check the list for filled orders and update the list for the latest price.

While debugging here and there I noticed a few objects in context that could be useful, I noticed a list of all orders, open and closed for the whole simulation, IIRC it was a "Blotter" object.

That said with the simple strategy you outlined I think cost_basis is what you really want to use, it's the actual price of your position including expenses so you cannot go wrong selling a long position higher than cost_basis or buying a short position lower than it.

@Reed Jessen
What's with the huge text formatting?

@Andrea, Markdown is not that intuitive. Rather a fabrication of someone's attempts at being textually clever. I've made the same mistake myself a few times.

@Adam S., cost_basis is not VWAP. it's SWAP. Share weighted average price. It's a common financial metric. Buy 100 at 100 and then buy 100 at 200, what's your SWAP? (100 x 100 + 100 x 200) / 200 = (raw) cost basis = $150.00.

Maeket Tech: can you make an example in which VWAP and SWAP would have different values?
I didn't know both definitions so I looked for them, I wasn't able to find SWAP's definition at all, while VWAP's one appears to be the very same as what you described.

Adam S: the main point in cost_basis is that it's evaluated after the order fills, so fees and slippage are included. It's an actual price and IMHO the proper one to be used for what you asked so you'll be sure to be in profit when the closing orders are filled.

@Andrea, from your link, yes, VWAP is SWAP. From my experience however, one doesn't necessarily have to trade to calculate VWAP. To me, the word volume does not equate to the quantity of shares I traded. Volume is the quantity of all trades, not just mine. That's why I like to use the shares word. But it's just semantics. "Did your mutual fund get the daily VWAP price?" "What was the 12:30 half hour VWAP and how did it compare to the average 30 minute VWAP over the last month?" Those are the thoughts I think when the word VWAP comes to mind. Cost_basis = VWAP? Well, OK. I think SWAP fits better though.

@Adam S.
I think that I am working on the same code as you. I want to create a simple algo that creates a trailing/moving line that buys/sells shares depending on curr_price. Is this what you are working on?

@Jonathan,

I'm working on a more or less High Frequency strategy - I need it to buy when certain conditions are met, hold the stock until it passes a certain point, (but another condition is that EVEN IF it passes a certain point, it must be HIGHER than the original purchase price).

@Everyone

Thanks for your help everyone - I've actually ended up using Cost_Basis and setting up Set_Commission and Set_Slippage to all zeros (I'm just interested in proving the theory to begin with) - I have been advised also to record order IDs into a dictionary and consult it for the last purchase price.

@Adam S,
What would those conditions be? I've tried to create an algo that buys stock at open_price, with a trailing stop loss of "open_price - .05". If the stock goes below stop loss I sell, but if the stock goes above the trailing stop loss then I buy again, and reset a trailing stop loss.
If this is what you are working on then maybe we could help each other out. Tell me if my algo is similar to yours.
Thanks

@Adam S

Would you mind providing the piece of code for all commissions and slippage to 0 ? I tried this on my own here with this cost and still end up with a cost basis different that the price

set_slippage(slippage.FixedSlippage(spread=0.00))  
set_slippage(slippage.VolumeShareSlippage(volume_limit=10000000000000000, price_impact=0))

set_commission(commission.PerShare(cost=0))  
set_commission(commission.PerTrade(cost=0))  
set_commission(commission.PerDollar(cost=0))

Basically, I expect to pay the market price exactly (working on the theory for now)... How can I do that ?

thanks !