Pretty sure I have messed something up

Either I have a bug or I'm the greatest trader ever

21
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.

# Use a random forest classifier. More here: http://scikit-learn.org/stable/user_guide.html
from sklearn.ensemble import RandomForestClassifier
from collections import deque
import numpy as np

# https://www.quantopian.com/posts/simple-machine-learning-example

def initialize(context):
context.stocks = [sid(8554), sid(22908), sid(2174), sid(24), sid(19656)]
# Set a dictionary for different closes for each position
context.position_closed = {sid(8554) : True,
sid(22908): True,
sid(2174): True,
sid(24): True,
sid(19656): True}

# need a way to know how much my bankroll is
context.order_size = 0.05
# context.position_cost = 0

# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
close_threshold = 1.05 # Ratio threshold at which to close buy position

for stock in context.stocks:
# Variables
price = data[stock].close_price # The price of the stock
moving_average = data[stock].mavg(20) # The stocks 20 day moving average
moving_average100 = data[stock].mavg(100)
moving_average200 = data[stock].mavg(200)
ratio = price/moving_average200 # The price:moving average "ratio"

# The current value of the position in  amounts
current_position_value = context.order_size*price
cash = context.portfolio.cash # tracks cash

# Functions that take in the current context and stock as parameters
order_percent(stock, context.order_size)
context.position_closed[stock] = False #order is open

# sell all stocks
order(stock, -context.portfolio.positions[stock].amount * -1)
context.position_closed[stock] = True
log.info("selling: %s" % (context.portfolio.positions[stock].amount))

# Conditions // Note that context.position_closed[stock]
# gets the boolean for each sid

# Need a way to determine if there are any open orders at all

if context.position_closed[stock] == True: # no stock
context.position_cost = context.order_size*price

if context.position_closed[stock] == False: # currently own stock
if ratio > close_threshold:
# Close if ratio is greater than close threshold

if current_position_value < context.position_cost*0.98:
# 2% stock loss- make this dynamic based off of the index (SPY)
# Close if unrealised loss exceeds 2%

There was a runtime error.
8 responses

That's a lot.

Try adding these two lines before order_percent():

            if context.portfolio.cash < 200:
return
order_percent(stock, context.order_size)


People who include apple in their code will always show great returns as past performance however, removing this security results in a -702% downturn. It isn't a sustainable algorithm in my opinion and the risk is high. I would suggest moving to an index portfolio.

Yeah I'm not trying to develop an Apple trading strategy, just trying to get something to run right now. A closer look based on the suggestion of Gary and looking at my daily positions and gains, is that I'm buying on margin consistently. His proposal to check my cash before ordering should fix it. Is there a margin rate that is applied if cash is negative?

Results are much more reasonable now. Thanks Gary!

21
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.

# Use a random forest classifier. More here: http://scikit-learn.org/stable/user_guide.html
from sklearn.ensemble import RandomForestClassifier
from collections import deque
import numpy as np

# https://www.quantopian.com/posts/simple-machine-learning-example

def initialize(context):
context.stocks = [sid(8554),
sid(22908),
sid(2174),
sid(24),
sid(19656)]
# Set a dictionary for different closes for each position
context.position_closed = {sid(8554) : True,
sid(22908): True,
sid(2174): True,
sid(24): True,
sid(19656): True}

# need a way to know how much my bankroll is
context.order_size = 0.05
# context.position_cost = 0

# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
close_threshold = 1.05 # Ratio threshold at which to close buy position

for stock in context.stocks:
# Variables
price = data[stock].close_price # The price of the stock
moving_average = data[stock].mavg(20) # The stocks 20 day moving average
moving_average100 = data[stock].mavg(100)
moving_average200 = data[stock].mavg(200)
ratio = price/moving_average200 # The price:moving average "ratio"

# The current value of the position in  amounts
current_position_value = context.order_size*price
cash = context.portfolio.cash # tracks cash

# Functions that take in the current context and stock as parameters

if context.portfolio.cash < 200:
return
else:
order_percent(stock, context.order_size)
context.position_closed[stock] = False #order is open

# sell all stocks
order(stock, -context.portfolio.positions[stock].amount * -1)
context.position_closed[stock] = True
log.info("selling: %s" % (context.portfolio.positions[stock].amount))

# Conditions // Note that context.position_closed[stock]
# gets the boolean for each sid

# Need a way to determine if there are any open orders at all

if context.position_closed[stock] == True: # no stock
context.position_cost = context.order_size*price

if context.position_closed[stock] == False: # currently own stock
if ratio > close_threshold:
# Close if ratio is greater than close threshold

if current_position_value < context.position_cost*0.98:
# 2% stock loss- make this dynamic based off of the index (SPY)
# Close if unrealised loss exceeds 2%

There was a runtime error.

order(stock, -context.portfolio.positions[stock].amount * -1)


Isn't this doubling your position instead of closing? Why did you have * -1 there?

Obviously the best trading strategy is constantly double down instead of getting out

See Martingale betting strategy.

Misplaced leading negative (-) sign now fixed. No more doubling down each time on Apple and no margin in the account. My returns look pretty stellar now.

21
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.

# Use a random forest classifier. More here: http://scikit-learn.org/stable/user_guide.html
from sklearn.ensemble import RandomForestClassifier
from collections import deque
import numpy as np

# https://www.quantopian.com/posts/simple-machine-learning-example

def initialize(context):
context.stocks = [sid(8554),
sid(22908),
sid(2174),
sid(24),
sid(19656)]

# Set a dictionary for different closes for each position
context.position_closed = {sid(8554) : True,
sid(22908): True,
sid(2174): True,
sid(24): True,
sid(19656): True}

# need a way to know how much my bankroll is
context.order_size = 0.05
# context.position_cost = 0

# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
close_threshold = 1.05 # Ratio threshold at which to close buy position

for stock in context.stocks:
# Variables
price = data[stock].close_price # The price of the stock
moving_average = data[stock].mavg(20) # The stocks 20 day moving average
moving_average100 = data[stock].mavg(100)
moving_average200 = data[stock].mavg(200)
ratio = price/moving_average200 # The price:moving average "ratio"

# The current value of the position in  amounts
current_position_value = context.order_size*price
cash = context.portfolio.cash # tracks cash

# Functions that take in the current context and stock as parameters

if context.portfolio.cash < 1000:
return
else:
order_percent(stock, context.order_size)
context.position_closed[stock] = False #order is open

# sell all stocks
order(stock, context.portfolio.positions[stock].amount * -1)
context.position_closed[stock] = True
log.info("selling: %s" % (context.portfolio.positions[stock].amount))

# Conditions // Note that context.position_closed[stock]
# gets the boolean for each sid

# Need a way to determine if there are any open orders at all

if context.position_closed[stock] == True: # no stock
context.position_cost = context.order_size*price