I was debugging your code because I found it interesting, and after I fixed the first 3 I realized that the algorithm didn't work, and no trades were executed. Looks like there are some logical bugs too. I suggest you rewrite the whole thing from scratch, and test as you go along. If you want I can give you the code I fixed, but I gave up after debugging and seeing that your top_returners array remained totally empty throughout.
import random
from collections import deque
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.security = symbol('AAPL') #security being bought
set_commission(commission.PerTrade(cost=0)) #commission prices
context.target_duration = 365 # number of days to test individual
context.num_parents = 2 # number of parents each new individual HAS
context.generation_size = 3
context.counter = 0 #stores prices here
context.individuals = [] # all individuals are stored here
parents = [] # parents stored here
new_generation(context) # call new generation
#creates a new generation based off of size context.generation_size
def new_generation(context):
possible_parents = []
for indi in context.individuals:
log.info(context.individuals[indi])
if indi['run_duration'] >= context.target_duration:
possible_parents.append(indi)
parents = sorted(possible_parents, key = lambda k: k['value'])[-context.num_parents:]
for i in range(context.generation_size):
# create new individual with one gene from parent and a new random gene
sma1 = random.randint(1,200)
if len(parents) == 0:
sma2 = random.randint(1,200)
else:
sma2 = parents[random.randrange(len(context.num_parents))]['sma2']
# parents[len(parents - i)]['sma2']
#store each individuals genes, run_duration, its value, and position
context.individuals.append({'sma1':sma1, 'sma2':sma2, 'run_duration':0, 'value':100,'current_longs':[]})
return None
#run the two crossovers against the stock price
def run_strategy(key, context, data):
####################replace line 67 with "sma1 > sma2"
strat = context.individuals[key]
# prices = history(300, '1d', 'price')
# sma1 = prices.tail(strat['sma1']).mean()
# sma2 = prices.tail(strat['sma2']).mean()
sma1prices = history(strat['sma1'], '1d', 'price')
sma2prices = history(strat['sma2'], '1d', 'price')
for sid in data:
sma1 = sma1prices[sid].mean()
sma2 = sma2prices[sid].mean()
if (sma1 < sma2) and not(sid in strat['current_longs']):
strat['current_longs'].append(sid)
elif (sma2 < sma1) and (sid in strat['current_longs']):
strat['current_longs'].remove(sid)
#for sid in data:
#if SMA'S are equal and price is above and no shares have been bought
#if data[sid].mavg(strat['sma1']) == data[sid].mavg(strat['sma2']) and strat['current_longs'] == 0:
# if data[sid].mavg(strat['sma1']) < data[sid].price:
# strat['current_longs'].append(sid)
# elif data[sid].mavg(strat['sma1']) == data[sid].mavg(strat['sma2']) and strat['current_longs'] == 1: strat['current_longs'].remove(sid)
return None
def update_returns(key,context,data):
strat = context.individuals[key]
daily_total_returns = 0
for sid in data:
if sid in strat['current_longs']:
daily_total_returns += data[sid].returns()
return None
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
#prices = history(300, '1d', 'price')
#sma1 = prices.tail(context.individuals['sma1']).mean()
#sma2 = prices.tail(smas['sma2']).mean()
context.counter += 1
top_returner =[] #fix error
if context.counter >= 70:
new_gen = 1
#find top performer
tested_strats = []
for strat in context.individuals:
if strat['run_duration'] >= context.target_duration:
tested_strats.append(strat)
top_returners = sorted(tested_strats, key =lambda k: k['value'])
if top_returners:
top_returner = top_returners[-1]
#check each individual to see if it needs to be run again
for i in range(len(context.individuals)):
if context.individuals[i]['run_duration'] < context.target_duration or context.individuals[i] == top_returner:
#update returns
if context.individuals[i] != top_returner:
update_returns(i, context, data)
context.individuals[i]['run_duration'] += 1
new_gen = 0
run_strategy(i, context, data)
if new_gen == 1:
log.info('sma1: '+ str(top_returner['sma1']))
log.info('sma2: '+ str(top_returner['sma2']))
new_generation(context) # Create new generation
longs = []
context.portfolio.portfolio_value
# Make trades based on the top performer
# Buy and sell shares in 2:1 leverage with amount proportional to our starting cash
if top_returner:
for sid in data:
if sid in top_returner['current_longs']:
longs.append(sid)
for sid in data:
if sid in longs:
order_target_percent(sid, 1.0)
else:
order_target(sid, 0)
try: top_returner['value']
except: top_returner['value'] = 0
record(num_individuals=len(context.individuals), top_value=top_returner['value'])