def trade(mega_config): ''' One function to rule them all ''' from neuronquant.gears.engine import Simulation from neuronquant.utils.logger import get_nestedlog # General simulation behavior #NOTE Portfolio server setup in Setup() object, #if needed, create it manually here configuration = mega_config['configuration'] strategie = mega_config['strategie'] # Remote: ZMQ based messaging, route logs on the network # (catched by server's broker) log_setup = get_nestedlog(level=configuration['loglevel'], file=configuration['logfile']) with log_setup.applicationbound(): # Backtest or live engine engine = Simulation(configuration) # Setup quotes data and financial context (location, market, ...) # simulation from user parameters Wrap _configure_data() and # _configure_context() you can use directly for better understanding data, trading_context = engine.configure() # See neuronquant/gears/engine.py for details of results which is an # analyzes object analyzes = engine.run(data, configuration, strategie, trading_context) assert analyzes
def __init__(self): # General backtest behavior configuration self.configuration = {'algorithm' : 'DualMA', 'frequency' : 'daily', 'manager' : 'Constant', 'database' : 'test', 'tickers' : ['google', 'apple'], 'start' : pytz.utc.localize(datetime(2008, 1, 11)), 'end' : pytz.utc.localize(datetime(2010, 7, 3)), 'live' : False, 'port' : '5570', 'cash' : 100000, 'exchange' : 'nasdaq', 'remote' : False} # Object use to run zipline backtest self.engine = Simulation() # Configure and return data used during backtest, and the TradingEnvironement self.data, self.context = self.engine.configure(self.configuration)
class Metric(object): ''' Evaluate error of a solution in optimization ''' def __init__(self): # General backtest behavior configuration self.configuration = { 'algorithm': 'DualMA', 'frequency': 'daily', 'manager': 'Constant', 'database': 'test', 'tickers': ['google', 'apple'], 'start': pytz.utc.localize(datetime(2008, 1, 11)), 'end': pytz.utc.localize(datetime(2010, 7, 3)), 'live': False, 'port': '5570', 'cash': 100000, 'exchange': 'nasdaq', 'remote': False } # Object use to run zipline backtest self.engine = Simulation() # Configure and return data used during backtest, and the TradingEnvironement self.data, self.context = self.engine.configure(self.configuration) def fitness(self, genes): ''' Cost function in the optimization process _________________________________________ Parameters genes: list Parameters to optimize _________________________________________ Return score: float Error of the cost function ran with this solution So the algo tries to minimize it (i.e. 0 is the best score) ''' # No evoluation in manager (Constant) configuration # We try here to optimize the algorithm parameters strategie = { 'manager': { 'name': 'Xavier Bruhiere', 'load_backup': 0, 'max_weight': 0.4, 'buy_amount': 200, 'sell_amount': 100, 'connected': 0 }, 'algorithm': { 'long_window': int(genes[0]), 'ma_rate': float(genes[1] / 10.0), 'threshold': genes[2] } } try: # Run backtest with all configuration dictionnaries analyzes = self.engine.run(self.data, self.configuration, strategie, self.context) # Get back summary performance dictionnary risk_metrics = analyzes.overall_metrics() except: import ipdb ipdb.set_trace() log.error('Exception caught while running cost function') # Return worst result possible return 1 return self.evaluate(risk_metrics) def evaluate(self, risks): ''' Define score from raw cost function results ''' score = [ risks['Returns'], risks['Sharpe.Ratio'], risks['Max.Drawdown'], risks['Volatility'] ] # Debug purpose if score[0]: log.notice(risks) # Compute score from cummulative returns, return 1 - score[0]
class Metric(object): ''' Evaluate error of a solution in optimization ''' def __init__(self): # General backtest behavior configuration self.configuration = {'algorithm' : 'DualMA', 'frequency' : 'daily', 'manager' : 'Constant', 'database' : 'test', 'tickers' : ['google', 'apple'], 'start' : pytz.utc.localize(datetime(2008, 1, 11)), 'end' : pytz.utc.localize(datetime(2010, 7, 3)), 'live' : False, 'port' : '5570', 'cash' : 100000, 'exchange' : 'nasdaq', 'remote' : False} # Object use to run zipline backtest self.engine = Simulation() # Configure and return data used during backtest, and the TradingEnvironement self.data, self.context = self.engine.configure(self.configuration) def fitness(self, genes): ''' Cost function in the optimization process _________________________________________ Parameters genes: list Parameters to optimize _________________________________________ Return score: float Error of the cost function ran with this solution So the algo tries to minimize it (i.e. 0 is the best score) ''' # No evoluation in manager (Constant) configuration # We try here to optimize the algorithm parameters strategie = {'manager': {'name': 'Xavier Bruhiere', 'load_backup': 0, 'max_weight': 0.4, 'buy_amount': 200, 'sell_amount': 100, 'connected': 0}, 'algorithm': {'long_window': int(genes[0]), 'ma_rate': float(genes[1] / 10.0), 'threshold': genes[2]} } try: # Run backtest with all configuration dictionnaries analyzes = self.engine.run(self.data, self.configuration, strategie, self.context) # Get back summary performance dictionnary risk_metrics = analyzes.overall_metrics() except: import ipdb; ipdb.set_trace() log.error('Exception caught while running cost function') # Return worst result possible return 1 return self.evaluate(risk_metrics) def evaluate(self, risks): ''' Define score from raw cost function results ''' score = [risks['Returns'], risks['Sharpe.Ratio'], risks['Max.Drawdown'], risks['Volatility']] # Debug purpose if score[0]: log.notice(risks) # Compute score from cummulative returns, return 1 - score[0]
for sophisticated multiple strategies strategy - Available capital allocation import ipdb; ipdb.set_trace() # XXX BREAKPOINT - Strategies repartition - Use of each-other signals behavior - Global monitoring and evaluation ''' # Fill strategie and manager parameters # Localy, reading configuration file # Remotely, listening gor messages through zmq socket strategie = setup.get_strategie_configuration(remote=configuration['remote']) '''_________________________________________________________ Backtest ____''' # Backtest or live engine engine = Simulation(configuration) # Setup quotes data and financial context (location, market, ...) # simulation from user parameters Wrap _configure_data() and # _configure_context() you can use directly for better understanding data, trading_context = engine.configure() # See neuronquant/gears/engine.py for details of results #which is an Analyzes object analyzes = engine.run(data, configuration, strategie, trading_context) if analyzes is None: log.error('** Backtest failed.') sys.exit(1) '''___________________________________________________________ Results ____'''
for sophisticated multiple strategies strategy - Available capital allocation import ipdb; ipdb.set_trace() # XXX BREAKPOINT - Strategies repartition - Use of each-other signals behavior - Global monitoring and evaluation ''' # Fill strategie and manager parameters # Localy, reading configuration file # Remotely, listening gor messages through zmq socket strategie = setup.get_strategie_configuration( remote=configuration['remote']) '''_________________________________________________________ Backtest ____''' # Backtest or live engine engine = Simulation(configuration) # Setup quotes data and financial context (location, market, ...) # simulation from user parameters Wrap _configure_data() and # _configure_context() you can use directly for better understanding data, trading_context = engine.configure() # See neuronquant/gears/engine.py for details of results #which is an Analyzes object analyzes = engine.run(data, configuration, strategie, trading_context) if analyzes is None: log.error('** Backtest failed.') sys.exit(1) '''___________________________________________________________ Results ____''' #analyzes.run_dashboard(portfolio=strategie['manager']['name'])
# Color_setup : Pretty print of errors, warning, and so on Remote_setup: # ZMQ based messaging, route logs on the network (catched by server's # broker) log_setup = (utils.remote_setup if configuration['remote'] else utils.color_setup) with log_setup.applicationbound(): # Fill algorithm and manager parameters # Localy, reading configuration file # Remotely, listening gor messages through zmq socket strategie = setup.get_strategie_configuration(remote=configuration['remote']) '''____________________________________________________________________________________ Backtest ____''' # Backtest or live engine engine = Simulation() # Setup quotes data and financial context (location, market, ...) # simulation from user parameters Wrap _configure_data() and # _configure_context() you can use directly for better understanding data, context = engine.configure(configuration) # See neuronquant/calculus/engine.py for details of results which is an # analyzes object analyzes = engine.run(data, configuration, strategie, context) if analyzes is None: utils.log.error('** Backtest failed, exiting') sys.exit(1) '''_______________________________________________________________________________________ Results ____'''