def initialization(universe): # general setting, required for all algo's universe.algo_name='SMA_RSI2' universe.start=datetime(2012,1,1) universe.end =datetime.today() #universe.symbols = ['AAPL','VOO','SPY','TQQQ','CVTI'] universe.symbols = ['AMZN'] universe.save_data='True' universe.data_source='web' universe.account.starting_cash=len(universe.symbols)*10000 # algo dependent setting # load data if universe.data_source=='web': universe.data=load_eod(universe.symbols, universe.start, universe.end, universe.save_data) elif universe.data_source=='csv': universe.data=load_csv(universe.symbols) if 'TQQQ' in universe.symbols: universe.data['TQQQ'][:datetime(2014,1,23)]/=2 # compute indicators indicator={sym:DataFrame(index=universe.data[sym].index) for sym in universe.symbols} for sym in universe.symbols: close=universe.data[sym].Close.values indicator[sym]['SMA10'] =ta.SMA(close, timeperiod=10) indicator[sym]['SMA200']=ta.SMA(close, timeperiod=200) indicator[sym]['EMA10'] =ta.EMA(close, timeperiod=10) indicator[sym]['RSI2'] =ta.RSI(close, timeperiod=2) indicator[sym]['MOM1'] =ta.MOM(close, timeperiod=1) universe.indicator=indicator return universe
def backtest(algo_name=universe.algo_name): global universe # import trading algorithm algo=import_module(algo_name) # initialize universe universe=algo.initialization(universe) universe.account.portfolio_value=universe.account.starting_cash universe.account.cash=universe.account.starting_cash # load data if it is not done in algo.initialization if universe.data=={}: if universe.data_source=='web': universe.data=load_eod(universe.symbols, universe.start, universe.end, universe.save_data) elif universe.data_source=='csv': universe.data=load_csv(universe.symbols) # backtest trading universe._complete_data=universe.data date_index=universe.data[universe.symbols[0]].index date_index=date_index[date_index>=universe.start] date_index=date_index[date_index<=universe.end] for dtitr in date_index: universe.now=dtitr # use up-to-today data universe.data={sym:universe._complete_data[sym][:dtitr] \ for sym in universe.symbols} # apply trade algo record=algo.trading(universe) # save recorded data universe.record=universe.record.append(DataFrame(record), ignore_index=True) # update account values with current day close proce today_data ={sym:universe._complete_data[sym][:dtitr][dtitr:] \ for sym in universe.symbols} today_close={sym:today_data[sym].Close[0] \ for sym in universe.symbols\ if len(today_data[sym])>0} universe.account.refresh_portfolio(dtitr,today_close) # finalize trading algo.finalize_trading(universe) print '\nbacktest finished'