I have following deap and zipline zode for optimzing. But I got some errors.Could anyone can help me

61 views
Skip to first unread message

ee EasyTrader

unread,
Apr 18, 2015, 9:36:53 AM4/18/15
to zip...@googlegroups.com
Dear All,
I have following deap and zipline zode for optimzing.
But I got some errors.
Could anyone can help me?

Thank you very much.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-acf0d03cf386> in <module>()
    163     hof = tools.HallOfFame(1)
    164     stats = tools.Statistics(lambda ind: ind.fitness.values)
--> 165     stats.register("avg", tools.mean)
    166     stats.register("std", tools.std)
    167     stats.register("min", min)

AttributeError: 'module' object has no attribute 'mean'



#!/usr/bin/env python
#
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import matplotlib.pyplot as plt


from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_from_yahoo


# Import exponential moving average from talib wrapper
from zipline.transforms.ta import EMA


from datetime import datetime
import pytz


#---------------------------------------------------------
import random


from deap import base
from deap import algorithms
from deap import creator
from deap import tools
from scoop import futures


import random
import array
import random
from math import sin, cos, pi, exp, e, sqrt


import glob
import os
import csv
from subprocess import Popen
import subprocess
# import datetime
import time
import shutil


import logging
#---------------------------------------------------------
logging
.basicConfig(level=logging.INFO)
logger
= logging.getLogger(__name__)
# logger.setLevel(logging.INFO)
handler
= logging.FileHandler('optimization.log')
formatter
= logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler
.setFormatter(formatter)
logger
.addHandler(handler)
#---------------------------------------------------------


class DualEMATaLib(TradingAlgorithm):
   
"""Dual Moving Average Crossover algorithm.


    This algorithm buys apple once its short moving average crosses
    its long moving average (indicating upwards momentum) and sells
    its shares once the averages cross again (indicating downwards
    momentum).


    """

   
def initialize(self, short_window=90, long_window=180):
       
# Add 2 mavg transforms, one with a long window, one
       
# with a short window.
       
self.short_ema_trans = EMA(timeperiod=short_window)
       
self.long_ema_trans = EMA(timeperiod=long_window)


       
# To keep track of whether we invested in the stock or not
       
self.invested = False


   
def handle_data(self, data):
       
self.short_ema = self.short_ema_trans.handle_data(data)
       
self.long_ema = self.long_ema_trans.handle_data(data)
       
if self.short_ema is None or self.long_ema is None:
           
return


       
self.buy = False
       
self.sell = False


       
if self.short_ema > self.long_ema and not self.invested:
           
self.order('AAPL', 100)
           
self.invested = True
           
self.buy = True
       
elif self.short_ema < self.long_ema and self.invested:
           
self.order('AAPL', -100)
           
self.invested = False
           
self.sell = True


       
# self.record(AAPL=data['AAPL'].price,
       
#             short_ema=self.short_ema['AAPL'],
       
#             long_ema=self.long_ema['AAPL'],
       
#             buy=self.buy,
       
#             sell=self.sell)


def portfolioPerformance(individual):
    logger
.info("Individual: %s" % individual)
    profits
= runBacktest(individual)
   
return profits,


def runBacktest(p):
    short_window
=int(p[0])
    long_window
=int(p[1])
   
if long_window > short_window:
        logging
.info("Running backtest evaluation")
        logging
.info("short_window: %i" % short_window)
        logging
.info("long_window: %i" % long_window)
        dma
= DualEMATaLib(short_window,long_window)
        results
= dma.run(data).dropna()
        objective
=results.portfolio_value.tail(1).values[0]
        logging
.info("Objective: %f" % objective)
   
else:
        objective
=0




   
return objective




#================================================================================
# Problem dimension
NDIM
= 2


creator
.create("FitnessMax", base.Fitness, weights=(1.0,))
creator
.create("Individual", array.array, typecode='d', fitness=creator.FitnessMax)


toolbox
= base.Toolbox()
toolbox
.register("short_ma", random.randint, 10, 100)
toolbox
.register("long_ma", random.randint, 101, 300)
func_seq
= [toolbox.short_ma, toolbox.long_ma]


toolbox
.register("individual", tools.initCycle, creator.Individual, func_seq, n=1)
toolbox
.register("population", tools.initRepeat, list, toolbox.individual)


toolbox
.register("evaluate", portfolioPerformance)


# Operator registering
toolbox
.register("mate", tools.cxTwoPoints)
# toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox
.register("mutate", tools.mutShuffleIndexes, indpb=0.05)
toolbox
.register("select", tools.selTournament, tournsize=3)
# toolbox.register("map", futures.map)


#================================================================================




if __name__ == '__main__':
    start
= datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
   
end = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    data
= load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
                           
end=end)


    random
.seed(64)


    pop
= toolbox.population(n=3)
    hof
= tools.HallOfFame(1)
    stats
= tools.Statistics(lambda ind: ind.fitness.values)
    stats
.register("avg", tools.mean)
    stats
.register("std", tools.std)
    stats
.register("min", min)
    stats
.register("max", max)


    algorithms
.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=3, stats=stats,
                        halloffame
=hof, verbose=True)


    logging
.info("Best individual is %s, %s", hof[0], hof[0].fitness.values)



Fabian Braennstroem

unread,
Apr 18, 2015, 1:14:22 PM4/18/15
to zip...@googlegroups.com
Hello,

for me it works. Do you have the latest version of deap?
In general I think that zipline is with the standard version too slow for optimization, but deap is great :-)

Best Regards
Fabian
--
You received this message because you are subscribed to the Google Groups "Zipline Python Opensource Backtester" group.
To unsubscribe from this group and stop receiving emails from it, send an email to zipline+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages