Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to sell short?

I'm trying to get a feel for algorithms so I'm trying to build a simple "buy bear, sell bull" algorithm.

but when i try to add sell short functions, my algo goes crazy. it ends up with my cash somewhere around 1 trillion though my pnl is -1.5 trillion

could someone post an example showing how to properly code a (sane) short sell algo?

my code is basically like this:

def sell_short(context, sec, data, day, state):
spend = context.portfolio.cash / 10
amount = spend / data[sec].price
state.orderAmount-=amount

i guess i shouldn't use cash on hand for short selling....

9 responses
order_target_percent(sec,-0.10)  

Hi Jason,

Take a look at the attached example. It computes a fast (20 day) and slow (60 day) trailing moving average of the price of SPY and then goes long (100% long) or short (100% short) depending on whether the fast MA is above or below the slow MA.

I used order_target_percent() as Brian suggested. That method will allow you to allocate any fraction of your portfolio's total value to a given position, passing in -0.10 will take a 10% short position, in my example for simplicity I use order_target_percent(stock, -1) to go 100% short when my short condition is met. This method will also keep you from unwittingly using leverage, which it sounds like was a problem you ran into initially. We don't currently have a built-in margin model in the backtester, so there is nothing to stop you from using the order() method to buy (or sell) more than your total portfolio value.

Best regards, Jess

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.

Jessica,
your algo is very good both in terms of performance and risk.
What is surprising is that, contrary to what is written in the comments of the coding, the position taken is short when the fastMA >= slowMA and
long when fastMA < slowMA: the opposite of the "normal" rule...
This is not a problem given that the coding is here just to demonstrate the short selling, but it is fun to see for people (like me) that do not trust very much the technical analysis stuff!

Oh yeah, oops, I was monkeying around with the signs and I left it inconsistent between comments and code. I've corrected this version to adhere to the standard orientation I believe. I also had the % allocation mis-commented. Thanks for catching that and pointing it out!

Cheers,
Jess
p.s. I also ran this backtest for a full year so it will be a little more meaningful, though the +100% and -100% allocations aren't realistic, just as you said meant to be illustrative of the correct syntax.

Wow Jess, thanks for that great example. that's perfect. (both the before and after fixes)

I am not able to understand why isn't the position getting covered at once. When I see the order list that has been generated it has weird order quantity numbers. It would be really great if someone can help me out!

average_price = data[context.security].mavg(5)
current_price = data[context.security].price

if current_price > 1.01*average_price:  
    order_target_percent(context.security, +1)  
    log.info("Buying %s" % (context.security.symbol))  

if current_price < 0.99*average_price:  
    order_target_percent(context.security, -1)  
    log.info("Selling %s" % (context.security.symbol))  

The position doesn't get covered immediately because of slippage: https://www.quantopian.com/help#ide-slippage

This helps simulate your order in real-wold conditions. If you submit a large market order, such as $1,000,000 worth of AAPL shares, it can't be filled immediately because it will impact the market price. By default, up to 25% of the security's trade volume will be filled per bar. Depending on your order size, it may take several bars to fill completely. You can change this setting to another percentage that's more relevant to your strategy, write your own custom slippage model, or turn it off completely for development. In live trading, the slippage (and commissions) get ignored and the orders are filled directly by the broker. Hope that helps!

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.

Hi Alisa,

Thanks for the help!

I had tried back-testing the default algo provided by Quantopian which was a buy-only algorithm without any short orders. The backtest results in that case show that all orders(including orders worth $1 Million were filled immediately. Why is that so?

Hey Anurag,

Great question. Are you referring to "Sample Algorithm for Live Trading"? If so, I believe the confusion is stemming from the initial portfolio that each algorithm starts out with. "Sample Algorithm for Live Trading" starts with $50,000 meaning that the number of shares that could be bought with that amount falls well under the 25% of trade volume threshold that Alisa mentioned while the other sample algorithm starts out with $1,000,000. In other words, the initial order size is small enough that all orders can be filled at the start.

For example, in my attached backtest, the algorithm is able to purchase all 651 shares of AAPL (50,000/price of AAPL) at the very start because of the portfolio value's initial size.

Feel free to ask any more questions you might have!

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.