losing all funds immediately in backtest

Hello all, I'm fairly new to quantopian and to coding in general.
For some reason whenever I go to backtest, my cash will fall off to -95.5% total returns extremely rapidly, and by that I mean that my algorithm experiences zero gains. Any idea what could be causing this to happen?

Edit: re-ran my test with daily data and I'm not getting an exponential drop-off like with the minute data. I've attached a sample of my minute data.... and I guess my code too.

7
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.

import datetime
import pytz
import numpy as np

three_tick_list = []
five_tick_list = []
three_list = [0, 1, 2]
five_list = [0, 1, 2, 3, 4]
three_regression_result = []
five_regression_result = []

def initialize(context):
#S&P stock
context.SnP = sid(24)

def handle_data(context, data):
SandP = context.SnP
SandP_data = data[SandP]
current_price = SandP_data.price
cash = context.portfolio.cash

#if the length of three tick list is less than 3,
#curate the lists
if len(three_tick_list) < 3:
three_tick_setup(current_price)

else:
#curate lists, then find three regression
three_tick_setup(current_price)
three_regression = np.polyfit(three_tick_list, three_list, 1)

if get_open_orders():
return

#if the slope is less than zero,
elif int(three_regression[0]) < 0:
#set up number of shares to sell
number_of_shares = context.portfolio.positions[SandP.sid].amount
order(SandP, -number_of_shares)
#I don't know why it doesn't work, just print stuff.
print(three_regression[0],  " False")

#else if the first number is greater than zero,
elif int(three_regression[0]) > 0:
#find the number of shares hurry up and do it
number_of_shares = int(cash/current_price)
order(SandP, number_of_shares)
#print some things I'm losing my mind...
print(three_regression[0], " True")

print('\n=======================\n')
#=====================================================================
def three_tick_setup(pricedata):
#add the nowprice to the three tick list
three_tick_list.append(pricedata)
#curate the three tick list: if length is longer than 3, delete the first entry
if len(three_tick_list) > 3:
del three_tick_list[0]
#    else:
#        return (three_tick_list)
#=====================================================================
def five_tick_setup(pricedata):
#add nowprice to the five tick list
five_tick_list.append(pricedata)
#if length of the five tick list is longer than 5, delete the first entry
if len(five_tick_list) > 5:
del five_tick_list[0]
#=====================================================================
def three_tick_regression(xdata, ydata):
pass
#=====================================================================
def sell_position(context, data):
pass
#=====================================================================
def check_mean(context, data):
pass
#    get_datetime('US/Eastern')
#    log.info(get_datetime())
#    for stock in data:
#        log.info('price for %s: %.2f' %(stock.symbol, data[stock].price))
#    log.info('\n')
There was a runtime error.
5 responses

One AM was a bad time to post my question. It's my first algorithm so I'm open to any feedback.

Hello John,
This is a fairly common mistake. Ctrl+f the keywords: "slippage" and "commission" in the Help and API docs. When you don't specify a slippage or commission the default will set one for you. In your case, the algo is making a tremendous amount of trades, and your principal is only 1k, so the trading commission fees and slippage are eating up your profits AND principal. Add this code to the initialize function and you should be ok, but realize that you will have to deal with slippage and commissions IRL.

Thanks a ton! Will this affect my algorithm if submitted for a contest or used for trades on quantopian, since they utilize free trades?

John,
You will not be able to submit the algo to the contest including those 2 lines. The contest rules stipulate that you MUST use the default commission and slippage which means your first algo would be acceptable in the contest and your second with my added suggestions would not be. Conflicts will arise often if you try to make an algo suitable for your own investing purposes and for the contest at the same time. Volume liquidity, slippage, commissions, desirable beta, drawdown and optimal returns to name a few, are some of the areas where goals will conflict.

Hi John,

I think I figured out what was going on with your algorithm. It seems that you commission per trade was nonzero, and your algorithm was executing a large volume of trades, bringing down your returns by a significant percentage every tick. I added a line that sets commissions to zero, and I used the "order_target_percent" method to make sure that shorting never occurs.

-Lota

3
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.

import datetime
import pytz
import numpy as np

three_tick_list = []
five_tick_list = []
three_list = [0, 1, 2]
five_list = [0, 1, 2, 3, 4]
three_regression_result = []
five_regression_result = []

def initialize(context):
#S&P stock
context.SnP = sid(24)

def handle_data(context, data):
SandP = context.SnP
SandP_data = data[SandP]
current_price = SandP_data.price
cash = context.portfolio.cash

#if the length of three tick list is less than 3,
#curate the lists
if len(three_tick_list) < 3:
three_tick_setup(current_price)

else:
#curate lists, then find three regression
three_tick_setup(current_price)
three_regression = np.polyfit(three_tick_list, three_list, 1)

if get_open_orders():
return

#if the slope is less than zero,
elif int(three_regression[0]) < 0:
#set up number of shares to sell
number_of_shares = context.portfolio.positions[SandP.sid].amount
order_target_percent(SandP, 0)
#I don't know why it doesn't work, just print stuff.
print(three_regression[0],  " False")

#else if the first number is greater than zero,
elif int(three_regression[0]) > 0:
#find the number of shares hurry up and do it
number_of_shares = int(cash/current_price)
order(SandP, number_of_shares)
record("positions",len(context.portfolio.positions))
#print some things I'm losing my mind...
print(three_regression[0], " True")

print('\n=======================\n')
#=====================================================================
def three_tick_setup(pricedata):
#add the nowprice to the three tick list
three_tick_list.append(pricedata)
#curate the three tick list: if length is longer than 3, delete the first entry
if len(three_tick_list) > 3:
del three_tick_list[0]
#    else:
#        return (three_tick_list)
#=====================================================================
def five_tick_setup(pricedata):
#add nowprice to the five tick list
five_tick_list.append(pricedata)
#if length of the five tick list is longer than 5, delete the first entry
if len(five_tick_list) > 5:
del five_tick_list[0]
#=====================================================================
def three_tick_regression(xdata, ydata):
pass
#=====================================================================
def sell_position(context, data):
pass
#=====================================================================
def check_mean(context, data):
pass
#    get_datetime('US/Eastern')
#    log.info(get_datetime())
#    for stock in data:
#        log.info('price for %s: %.2f' %(stock.symbol, data[stock].price))
#    log.info('\n')
There was a runtime error.
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.