def func0(context, data): order(symbol('AAPL UW EQUITY'), 10) print 'price: ', data[symbol('AAPL UW EQUITY')].price # order(symbol('AAPL UW EQUITY'), -10) print context.portfolio.cash print context.get_datetime().date() print "==========================="
def patch_fund(context, data): stocks = context.stocks hist = data.history(stocks, 'close', LOOKBACK_PERIOD, '1d') index = [ "HSCI.HI", "SPX.GI", "EM_BOND", "B00.IPE", "REIT", "SPTAUUSDOZ.IDC" ] index_etf = ["000071.OF","096001.OF","002401.OF","162411.OF",\ "206011.OF","000217.OF"] df_index = pd.DataFrame( data=index_etf, index=index, ) hist = hist.dropna(how='any', axis=1) for i in df_index.index: j = symbol(df_index.loc[i][0]) if j in hist.columns: #避免有指数的数据不存在的情况,TODO:指数数据缺失? try: hist = hist.drop(symbol(i), 1) except: pass else: continue return hist.columns
def initialize(context): """ Called once at the start of the algorithm. """ feature_num = 11 context.orders_submitted = False large_num = 9999999 least_num = 0 context.n_components = 6 context.security = symbol(SYMBOL) # Trade SPY set_benchmark(symbol(SYMBOL)) # Set benchmarks context.model2 = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True) # 8.05 for SVM model context.model3 = KNeighborsClassifier(n_neighbors=feature_num, p=3, metric='minkowski') # 7.05 for model context.model = DecisionTreeClassifier(criterion='entropy', max_depth=feature_num, random_state=0) context.model4 = RandomForestClassifier(criterion='entropy', n_estimators=feature_num, random_state=1, n_jobs=2) # 5.2 for randomforest context.model1 = LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial') context.modellist = {'SVM':context.model2,'KNeighbors':context.model3,'DecisionTree':context.model,'RandomForest':context.model4,'LogisticRegression':context.model1} context.lookback = 350 # Look back 62 days context.history_range = 350 # Only consider the past 400 days' history context.threshold = 4.05 context.longprices = large_num context.shortprices = least_num context.time_series = 0 context.init = 0 set_long_only() # Generate a new model every week #schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Generate a new model every week schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Trade at the start of every day schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
def handle_data(context, data): # Historical data prices = data.history(context.stocks, 'price', bar_count=20, frequency='1d') rsis = {} # Loop thru the stocks and determine when to buy and sell them for stock in context.stocks: rsi = ta.RSI(prices[stock], timeperiod=14)[-1] rsis[stock] = rsi current_position = context.portfolio.positions[stock].amount if rsi > context.high_rsi and current_position > 0 and data.can_trade(stock): order_target(stock, 0) elif rsi < context.low_rsi and current_position == 0 and data.can_trade(stock): order_target_percent(stock, context.target_pct_per_stock) record(fb_rsi=rsis[symbol('FB')], amzn_rsi=rsis[symbol('AMZN')], aapl_rsi=rsis[symbol('AAPL')], nflx_rsi=rsis[symbol('NFLX')], googl_rsi=rsis[symbol('GOOGL')])
def initialize(context): attach_pipeline(make_pipeline(), 'pipeline') #Schedule Functions if not IS_LIVE: schedule_function( trade, #date_rules.every_day(), #date_rules.week_end(days_offset=1),#0=Fri 1= Thurs date_rules.month_end(days_offset=3), time_rules.market_close(minutes=30) ) schedule_function(record_vars, date_rules.every_day(), time_rules.market_close()) schedule_function(cancel_open_orders, date_rules.week_end(days_offset=2), time_rules.market_close()) context.spy = symbol('SPY') #sid(8554) #SPY context.TF_filter = False #context.TF_lookback = 60 #Set number of securities to buy and bonds fund (when we are out of stocks) context.Target_securities_to_buy = 15 #10 #15 #2 #1 #5 #10 #5 context.bonds = symbol('IEF') #sid(23870) #IEF context.relative_momentum_lookback = 44 #66 #22 #4 #22 #22 #22 #126 #Momentum lookback context.momentum_skip_days = 1 context.top_n_relative_momentum_to_buy = 10 #15 #10 #15 #1 #5 #5 #10 #5 #Number to buy context.stock_weights = pd.Series() context.bond_weights = pd.Series() context.auto_close = {} #Initialize portfolio auto_close list. context.TRACK_ORDERS_ON = False
def initialize(context): """ A function to define things to do at the start of the strategy """ # universe selection context.securities = [symbol('NIFTY-I'), symbol('BANKNIFTY-I')] # define strategy parameters context.params = { 'indicator_lookback': 375, 'indicator_freq': '1m', 'buy_signal_threshold': 0.5, 'sell_signal_threshold': -0.5, 'ROC_period_short': 30, 'ROC_period_long': 120, 'BBands_period': 300, 'trade_freq': 5, 'leverage': 2 } # variable to control trading frequency context.bar_count = 0 # variables to track signals and target portfolio context.signals = dict((security, 0) for security in context.securities) context.target_position = dict( (security, 0) for security in context.securities) # set trading cost and slippage to zero set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00))
def handle_data(context, data): # Skip first 300 days to get full windows context.i += 1 if context.i < 300: return # Compute averages # history() has to be called with the same params # from above and returns a pandas dataframe. short_mavg = history(100, '1d', 'price').mean() long_mavg = history(300, '1d', 'price').mean() # price_history = data.history(assets=symbol('TEST'), fields="price", bar_count=5, frequency="1d") # Trading logic if short_mavg[0] > long_mavg[0]: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(symbol('AAPL'), 100) elif short_mavg[0] < long_mavg[0]: order_target(symbol('AAPL'), 0) # Save values for later inspection record(AAPL=data[symbol('AAPL')].price, short_mavg=short_mavg[0], long_mavg=long_mavg[0])
def initialize(context): context.time = 0 context.asset = symbol('SPY') context.set_commission( commission.PerShare(cost=0.001, min_trade_cost=0)) context.strategy_params_1 = ta_params set_benchmark(symbol("SPY"))
def handle_data(context, data): #trading algorithm (executed on every event) #skip first 300 days to get full windows context.i += 1 if context.i < 300: return #compute short and long moving averages: short_mavg = history(100, '1d', 'price').mean() long_mavg = history(300, '1d', 'price').mean() buy = False sell = False #trading logic if (short_mavg[0] > long_mavg[0]) and not context.invested: buy = True context.invested = True order_target(symbol('AAPL'), 100) elif (short_mavg[0] < long_mavg[0]) and context.invested: sell = True context.invested = False order_target(symbol('AAPL'), -100) #save values for plotting record(AAPL = data[symbol('AAPL')].price, short_mavg = short_mavg[0], long_mavg = long_mavg[0], buy=buy, sell=sell)
def rebalance(context, data): history = data.history(assets=context.asset, fields=['close'], bar_count=10, frequency='1d') date = history.index.values[-1] close = history['close'].values print("===============================================================") print("持仓数 amount=", context.portfolio.positions[symbol('IBM')].amount) print("每股成本 cost_basis=", context.portfolio.positions[symbol('IBM')].cost_basis) print("最新价格 last_sale_price=", context.portfolio.positions[symbol('IBM')].last_sale_price) print("能否交易 can_trade=", data.can_trade(context.asset)) print("current price=", data.current(context.asset, 'close')) print("使用现金 capital_used=", context.portfolio.capital_used) print("剩余现金 cash=", context.portfolio.cash) print("今日收益 pnl=", context.portfolio.pnl) print("收益率 returns=", context.portfolio.returns) print("起始现金 starting_cash=", context.portfolio.starting_cash) print("总市值 portfolio_value=", context.portfolio.portfolio_value) print("持仓市值 positions_value=", context.portfolio.positions_value) amount = context.portfolio.positions[symbol('IBM')].amount if amount == 0: order_id = order_target_value(context.asset, 200) else: order_id = order_target_value(context.asset, 400) print("order_id==>", order_id)
def handle_data(context, data): # context.i+=1 # if context.i<=5: # return # 循环每只股票 closeprice= history(5,'1d','close') for security in context.stocks: vwap=(closeprice[symbol(security)][-2]+closeprice[symbol(security)][-3]+closeprice[symbol(security)][-4])/3 price = closeprice[symbol(security)][-2] print get_datetime(),security,vwap,price # # 如果上一时间点价格小于三天平均价*0.995,并且持有该股票,卖出 if price < vwap * 0.995: # 下入卖出单 order(symbol(security),-300) print get_datetime(),("Selling %s" % (security)) # 记录这次卖出 #log.info("Selling %s" % (security)) # 如果上一时间点价格大于三天平均价*1.005,并且有现金余额,买入 elif price > vwap * 1.005: # 下入买入单 order(symbol(security),300) # 记录这次买入 print get_datetime(),("Buying %s" % (security))
def get_adj_w(a, w, symb_list, context, m='mb', nd=18): flag0 = m in ('mb', ) and a in symb_list # flag1 = context.bb_day_count_df.loc[ a, 'nd'] > nd # int(current_date.strftime('%m')) < 7 if flag1 and a == symbol('CB.PI'): print('jznd', a, w, flag0, context.bb_day_count_df.loc[a, 'nd'], 15) vol_threshold = 0.003 if a == symbol('BD.PI') else -1 flag2 = context.pipeline_data.loc[a, 'volatility'] < vol_threshold if flag0 and flag2: print('jfuz', vol_threshold, context.pipeline_data.loc[a, 'volatility']) ndzero_threshold = 0 if a == symbol('BD.PI') else 8 flag3 = context.bb_day_count_df.loc[ a, 'ndzero'] > ndzero_threshold #CB: 10=0.58; 20=0.6 chipinfactor = (min( 16, context.bb_day_count_df.loc[a, 'ndzero'])) / 16 #new debug if a in symb_list: print('flag3', context.bb_day_count_df.loc[a, 'ndzero']) mbflag = flag0 and (flag3 or flag2) #or flag1) if mbflag: print('mbflag=', a, 'chipinfactor=', chipinfactor, context.bb_day_count_df.loc[a, 'nd'], w) if mbflag and w > 1 and flag1: print('xyd') myvol = context.pipeline_data.loc[a, 'volatility'] adj_w = MB_HACK * chipinfactor if mbflag else ( 1 if flag0 and w > 1 and flag1 else w ) #(np.sign(w) if a == symbol('BD.PI') else w)# and w*context. last lw weight (asset) 0 else w/2 return adj_w
def handle_data(context, data): # Load historical pricing data for the stocks, using daily frequncy and a rolling 20 days prices = data.history(context.stocks, 'price', bar_count=20, frequency="1d") rsis = {} # Loop through our list of stocks for stock in context.stocks: # Get the rsi of this stock. rsi = talib.RSI(prices[stock], timeperiod=14)[-1] rsis[stock] = rsi current_position = context.portfolio.positions[stock].amount # RSI is above 70 and we own shares, time to sell if rsi > context.HIGH_RSI and current_position > 0 and data.can_trade(stock): order_target(stock, 0) # RSI is below 30 and we don't have any shares, time to buy elif rsi < context.LOW_RSI and current_position == 0 and data.can_trade(stock): order_target_percent(stock, context.target_pct_per_stock) # record the current RSI values of each stock for later ispection record(fb_rsi=rsis[symbol('FB')], amzn_rsi=rsis[symbol('AMZN')], aapl_rsi=rsis[symbol('AAPL')], nflx_rsi=rsis[symbol('NFLX')], googl_rsi=rsis[symbol('GOOGL')])
def initialize(context): context.set_commission(commission.PerShare(cost=0.0, min_trade_cost=0)) set_benchmark(symbol('SPY')) context.asset = symbol('AAPL') context.has_ordered = False schedule_function(place_order, None, time_rules.market_open())
def handle_data(context, data): curr_price = data[symbol('USCRWTIC INDEX')].price curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount cash = context.portfolio.cash print cash, curr_positions, curr_price # context.counter += 1 # if context.counter > 500: # print "Cancelou" # cancel_order(context.order_id) # else: # print 'ola' random_order = np.random.rand() if random_order > 0.5 and curr_positions == 0: order(symbol('USCRWTIC INDEX'), 100) elif random_order < 0.5 and curr_positions != 0: order(symbol('USCRWTIC INDEX'), -100)
def initialize(context): # Turn off the slippage model set_slippage(slippage.FixedSlippage(spread=0.0)) # Set the commission model set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0)) context.day = -1 # using zero-based counter for days context.set_benchmark(symbol('DIA')) context.assets = [] print('Setup investable assets...') for ticker in asset_tickers: #print(ticker) context.assets.append(symbol(ticker)) context.n_asset = len(context.assets) context.n_portfolio = 40 # num mean-variance efficient portfolios to compute context.today = None context.tau = None context.min_data_window = 756 # min of 3 yrs data for calculations context.first_rebal_date = None context.first_rebal_idx = None context.weights = None # Schedule dynamic allocation calcs to occur 1 day before month end - note that # actual trading will occur on the close on the last trading day of the month schedule_function(rebalance, date_rule=date_rules.month_end(days_offset=1), time_rule=time_rules.market_close()) # Record some stuff every day schedule_function(record_vars, date_rule=date_rules.every_day(), time_rule=time_rules.market_close())
def initialize(context): # List of Major World Indices Yahoo tickers - https://finance.yahoo.com/world-indices with open('tickers.pickle', 'rb') as handle: indices_tickers = pickle.load(handle) # load in tickers from pickle os.remove('tickers.pickle') # delete tickers pickle file context.indices = [symbol(ticker) for ticker in indices_tickers ] # create list of ticker symbols context.days_of_correction = [ 0 for _ in indices_tickers ] # create list of days since correction has begun set_benchmark(symbol('^GSPC')) '''-----------------------------PARAMETERS TO BE OPTIMISED--------------------------------''' context.correction_margin = 0.1 # the percentage drawdown considered a correction print('Drawdown percentage range from peak for correction: ' + str(round(context.correction_margin * 100)) + '%') context.upturn_coefficient = 0.22 # the ratio upturn from trough indicating end of correction - used in calculate_required_upturn function print('Upturn Coefficient: ' + str(round(context.upturn_coefficient, 2))) context.min_return = 0.26 # the minimum return required before changing positions print('Minimum return per trade: ' + str(round(context.min_return * 100)) + '%') context.min_gain = 0.07 # the highest the price can be from peak and still be considered for ordering print('Mainimum potential gain from peak to be considered: ' + str(round(context.min_gain * 100, 0)) + '%') context.stop_loss = 0.53 # lowest proportion of investment peak print('Stop loss for investments: ' + str(round(context.stop_loss * 100)) + '%')
def initialize(context): """ Called once at the start of the algorithm. """ feature_num = 11 context.orders_submitted = False large_num = 9999999 least_num = 0 context.n_components = feature_num context.security = symbol(SYMBOL) # Trade SPY set_benchmark(symbol(SYMBOL)) # Set benchmarks context.model = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True) # 8.05 for SVM model context.lookback = 350 # Look back 62 days context.history_range = 350 # Only consider the past 400 days' history context.threshold = 4.05 context.longprices = large_num context.shortprices = least_num set_long_only() # Generate a new model every week schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Generate a new model every week schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Trade at the start of every day schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
def initialize(context): """ Called once at the start of the algorithm. """ feature_num = 11 context.orders_submitted = False large_num = 9999999 least_num = 0 context.n_components = feature_num context.security = symbol(SYMBOL) # Trade SPY set_benchmark(symbol(SYMBOL)) # Set benchmarks context.model = DecisionTreeClassifier(criterion='entropy', max_depth=feature_num, random_state=0) context.lookback = 350 # Look back 62 days context.history_range = 350 # Only consider the past 400 days' history context.threshold = 4.05 context.longprices = large_num context.shortprices = least_num set_long_only() # Generate a new model every week schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Generate a new model every week schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10)) """ # Trade at the start of every day schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
def initialize(context): ''' A function to define things to do at the start of the strategy ''' # universe selection context.universe = [symbol('NIFTY-I'),symbol('BANKNIFTY-I')] # define strategy parameters context.params = {'indicator_lookback':375, 'indicator_freq':'1m', 'buy_signal_threshold':0.5, 'sell_signal_threshold':-0.5, 'SMA_period_short':15, 'SMA_period_long':60, 'RSI_period':300, 'BBands_period':300, 'ADX_period':120, 'trade_freq':15, 'leverage':1} # variable to control trading frequency context.bar_count = 0 # variables to track target portfolio context.weights = dict((security,0.0) for security in context.universe) # set trading cost and slippage to zero set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0)) set_slippage(slippage.FixedSlippage(0.00)) # create the list of experts as well as the agent controlling them context.advisor = Advisor('bbands_ea',expert_advisor, context.universe) # schedule agent weights updates pass
def validateSectorUniverse(candidate_sector_universe: Universe, zipline_data: BarData): """Function to validate a candidate sector universe. Ensures that Zipline can look up all tickers. Arguments: candidate_sector_universe {Universe} -- Candidate sector universe. zipline_data {BarData} -- Instance zipline data bundle. Raises: SymbolNotFound -- Raised when a symbol is not found. """ for ticker in candidate_sector_universe.getUniqueTickers(): try: symbol(ticker) if not zipline_data.can_trade(symbol(ticker)): raise NoDataForSid except (SymbolNotFound, NoDataForSid): # Updating invalid ticker in the universe candidate_sector_universe.removeInvalidTicker( invalid_ticker=ticker) logging.info( 'Ticker {0} in universe not in Zipline; removing'.format( ticker)) # Return 'clean' sector universe return candidate_sector_universe
def handle_data(context, data): # Skip first 90 days to get full windows if context.day < context.DAYS_CUMULATIVE: context.day += 1 return if context.day % context.REFORM_PERIOD != 0: context.day += 1 return context.day += 1 # For each stock, compute gain in last 90 days d = {} for ticker in context.tickers: # Compute averages # data.history() has to be called with the same params # from above and returns a pandas dataframe. try: df = data.history(symbol(ticker), 'close', bar_count=context.DAYS_CUMULATIVE, frequency="1d") start_price = df.iloc[:1].tolist()[0] end_price = df.iloc[-1:].tolist()[0] gain = float(end_price) / start_price if not math.isnan(gain): d[ticker] = gain except SymbolNotFound as e: # print "WARN: Unable to get data for %s" % ticker print '', # Sort all tickers by there gain in ascending order sorted_d = sorted(d.items(), key=operator.itemgetter(1)) portfolio_with_gain = sorted_d[-context.PORTFOLIO_SIZE:] portfolio = [i[0] for i in portfolio_with_gain] capital_each_share = context.STARTING_CASH / context.PORTFOLIO_SIZE # Trading logic for stock in portfolio: if stock not in context.my_portfolio_quantity.keys(): quantity = int(capital_each_share / data.current(symbol(stock), 'close')) order_percent(symbol(stock), 1.0 / context.PORTFOLIO_SIZE) context.my_portfolio_quantity[stock] = quantity for stock in context.my_portfolio_quantity.keys(): if stock not in portfolio: quantity = context.my_portfolio_quantity[stock] del context.my_portfolio_quantity[stock] order_target_percent(symbol(stock), 0.0) # Printing each portfolio print "day %d" % context.day print portfolio print '\n\n'
def initialize(context): # List of Major World Indices Yahoo tickers - https://finance.yahoo.com/world-indices with open('tickers.pickle', 'rb') as handle: indices_tickers = pickle.load(handle) # load in tickers from pickle os.remove('tickers.pickle') # delete tickers pickle file context.indices = [symbol(ticker) for ticker in indices_tickers ] # create list of ticker symbols context.days_of_correction = [ 0 for _ in indices_tickers ] # create list of days since correction has begun set_benchmark(symbol('^GSPC')) set_commission( commission.PerTrade(cost=15.0) ) # commission for IBKR, UK for Stocks, ETF's & Warrants - https://www.interactivebrokers.co.uk/en/index.php?f=39753&p=stocks1 '''-----------------------------PARAMETERS TO BE OPTIMISED--------------------------------''' context.correction_margin = 0.1 # the percentage drawdown considered a correction print('Drawdown percentage range from peak for correction: ' + str(round(context.correction_margin * 100)) + '%') context.upturn_coefficient = 0.24 # the ratio upturn from trough indicating end of correction - used in calculate_required_upturn function print('Upturn Coefficient: ' + str(round(context.upturn_coefficient, 4))) context.min_gain = 0.05 # the highest the price can be from peak and still be considered for ordering print('Mainimum potential gain from peak to be considered: ' + str(round(context.min_gain * 100, 0)) + '%') context.state_threshold = -10.0 # 0.0002 threshold between bull and bear markets print('Market state threshhold: ' + str(round(context.state_threshold, 4)) + '%')
def handle_data(context, data): # Data window window = 14 # Get NFLX prices price = data.history(symbol('NFLX'), ['close'], window, '1d') latest_close = price['close'][-1] # Calculate RSI rsi = talib.RSI(price['close'][symbol('NFLX')], timeperiod=window)[-1] # Calculate Bollinger Bands bbHigh, bbMid, bbLow = talib.BBANDS(price['close'][symbol('NFLX')], timeperiod=window, nbdevup=2, nbdevdn=2, matype=0) rsiOverbought = rsi > 70 rsiOversold = rsi < 30 bbOverbought = latest_close > bbHigh bbOversold = latest_close < bbLow context.overbought = rsiOverbought & bbOverbought context.oversold = rsiOversold & bbOversold
def handle_data(context, data): curr_price = data[symbol('USCRWTIC INDEX')].price curr_date = data[symbol('USCRWTIC INDEX')].datetime curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount cash = context.portfolio.cash local_historical_data = context.oil_historical_data local_historical_data = local_historical_data['USCRWTIC INDEX'][['price']] df_to_forecast = local_historical_data[local_historical_data.index <= curr_date] result = forecast_ts.run(df = df_to_forecast, ts_list = None, freq = 'B', forecast_horizon = 6, start_date = curr_date.strftime('%Y-%m-%d'), method = context.method, processing_params = context.processing_params, expert_params = context.expert_params) estimated_return = result.iloc[-1].values[-1] # estimated_return = np.random.rand()-1 print cash, curr_positions, curr_price, curr_date, estimated_return if estimated_return < 0 and curr_positions == 0: order(symbol('USCRWTIC INDEX'), -100) elif estimated_return > 0 and curr_positions != 0: order(symbol('USCRWTIC INDEX'), 100)
def handle_data(context, data): con0_short_avg = data.history(symbol('sh601398'), 'close', 12, '1d').mean() con0_long_avg = data.history(symbol('sh601398'), 'close', 26, '1d').mean() if con0_short_avg < con0_long_avg: order(symbol('sh601398'), 199)
def handle_data(context, data): context.i += 1 stock_name = context.panel.axes[0][0] if context.i == 60: order(symbol(stock_name), 10) if context.i == 150: order(symbol(stock_name), -10) record(Prices=data[symbol(stock_name)].price)
def initialize(context): context.trading_day_counter = 0 context.pair = [symbol('EWA'), symbol('EWC')] context.size = 10000 # Kalman filter parameters context.delta = 1e-5 context.trans_cov = context.delta / (1 - context.delta) * np.eye(2)
def handle_data(context, data): print "=================================" print "New iteration" print data order(symbol('AAPL'), 10) record(AAPL=data[symbol('AAPL')].price)
def initialize(context): context.assets = { 'a1': symbol('AAPL'), 'a2': symbol('GE'), 'a3': symbol('WMT') } schedule_function(cte_mix_handle, date_rules.every_day())
def handle_data(context, data): global n print("handle", n) print(data.history(context.asset, 'price', 1, '1d')) #close price # print history(1, '1d', 'price').mean() n += 1 order(symbol('AAPL'), 10) record(AAPL=data.current(symbol('AAPL'), 'price'))
def _handle_data(self, context, data): for movimiento in context.movimientos: clave_emisora = movimiento.emisora fecha_movimiento = movimiento.fecha fecha = data[symbol(clave_emisora)].dt delta = fecha_movimiento - fecha.replace(tzinfo=None) num_acciones = movimiento.num_acciones if (delta.days == 0): order(symbol(clave_emisora), num_acciones)
def initialize(context): print "Initialize..." context.security = symbol(settings.BACKTEST_STOCK) context.benchmark = symbol('SPY') context.strategy = settings.STRATEGY_OBJECT context.raw_data = settings.PRE_BACKTEST_DATA context.normalized_data = Manager.preprocessData(context.raw_data)[:-2] print "Backtest symbol:", context.security print "Capital Base:", context.portfolio.cash
def initialize(context): context.assets = { 'a1': symbol('AAPL'), 'a2': symbol('GE'), 'a3': symbol('WMT') } context.has_ordered = False schedule_function(buy_and_hold, date_rules.every_day())
def _handle_data(self, context, data): for movimiento in context.movimientos: clave_emisora = movimiento.emisora fecha_movimiento = movimiento.fecha fecha = data[symbol(clave_emisora)].dt delta = fecha_movimiento - fecha.replace(tzinfo=None) num_acciones = movimiento.num_acciones if(delta.days == 0): order(symbol(clave_emisora), num_acciones)
def handle_data(context, data): equities_hist = data.history(symbol("AAPL"), "close", 100, "1d") if equities_hist[-1] > equities_hist.mean(): stock_weight = 1.0 else: stock_weight = 0.0 order_target_percent(symbol("AAPL"), stock_weight)
def initialize(context): context.assets = { 'a1': symbol('AAPL'), 'a2': symbol('GE'), 'a3': symbol('WMT') } context.time_window = 20 schedule_function(volatility_handle, date_rules.every_day())
def handle_data(context, data): # check if the spot is outside CI of MPP day_option_df = context.options[context.options['date'] == get_datetime()] call_sums = call_otm(day_option_df, 'FB', get_datetime()) put_sums = put_otm(day_option_df, 'FB', get_datetime()) add_to_window(context, 10, max_pain_strike(call_sums, put_sums), 'FB') ci = CI(context.window, 1) price = history(1, '1d', 'price').iloc[0,0] if price < ci[0]: order_target_percent(symbol('FB'), 1) elif price > ci[1]: order_target_percent(symbol('FB'), 0)
def handle_data(context, data): context.panel # Here we have access to training data also. # Make solution using the result of learning: if not int(data[symbol('AAPL')].price) % context.result: order(symbol('AAPL'), 10) # Record some values for analysis in 'analyze()'. sids = context.panel.axes[0].values prices = [data[symbol(sid)].price for sid in sids] record(Prices=prices) record(Prediction=3 * data[symbol('AAPL')].price - 2.2 * context.previous) # Record current price to use it in future. context.previous = data[symbol('AAPL')].price
def handle_data(context, data): context.cur_time += 1 month = get_datetime().date().month is_january = (month == 1) new_prices = np.array([data[symbol(symbol_name)].price for symbol_name in context.symbols], dtype='float32') record(Prices=new_prices) new_prices = new_prices.reshape((context.N_STOCKS, 1)) # print context.returns_history.shape # print new_prices.shape # print context.previous_prices.shape context.returns_history = np.concatenate([context.returns_history, new_prices / context.previous_prices], axis=1) context.previous_prices = new_prices if context.month != month: # Trading in the beginning of month context.month_sizes.append(context.day_of_month) context.day_of_month = 1 context.count_month += 1 context.month_sizes.append(context.day_of_month) context.day_of_month = 1 if context.count_month > N_MONTHS: # Deleting too old returns if context.count_month > N_MONTHS + 1: context.returns_history = np.delete(context.returns_history, range(context.month_sizes[-14]), axis=1) model_input = preprocess_data_for_model(context.returns_history, context.month_sizes[-13:], context.scaler) is_january_column = np.array([is_january] * context.N_STOCKS).reshape((context.N_STOCKS, 1)) model_input = np.concatenate([is_january_column, model_input], axis=1) # print 'Input shape', model_input.shape predicted_proba = context.model.predict_proba(model_input) # print predicted_proba ''' half_trade = len(context.symbols) * 1 / 10 args_sorted = np.argsort(predicted_proba[:, 0]) buy_args = args_sorted[:half_trade] sell_args = args_sorted[-half_trade:] for arg in buy_args: order_target(symbol(context.symbols[arg]), 1) for arg in sell_args: order_target(symbol(context.symbols[arg]), -1) ''' for i in range(context.N_STOCKS): if predicted_proba[i, 0] > 0.5: order_target(symbol(context.symbols[i]), 1) else: order_target(symbol(context.symbols[i]), -1) else: context.day_of_month += 1 context.month = month
def handle_data(context, data): #On-Line Moving Average Reversal (OLMAR) context.days += 1 if context.days < context.window_length: return if context.init: rebalance_portfolio(context, data, context.b_t) context.init=False return m = context.m #num assets x_tilde = np.zeros(m) #relative mean deviation b = np.zeros(m) #weights #compute moving average price for each asset mavgs = history(context.window_length, '1d', 'price').mean() #mavgs = data.history(context.sids, 'price', context.window_length, '1d').mean() for i, stock in enumerate(context.stocks): price = data[stock]['price'] x_tilde[i] = mavgs[i] / price x_bar = x_tilde.mean() market_rel_dev = x_tilde - x_bar #relative deviation exp_return = np.dot(context.b_t, x_tilde) weight = context.eps - exp_return variability = (np.linalg.norm(market_rel_dev))**2 if variability == 0.0: step_size = 0 else: step_size = np.max((0, weight/variability)) b = context.b_t + step_size * market_rel_dev b_norm = simplex_projection(b) rebalance_portfolio(context, data, b_norm) context.b_t = b_norm #save values for plotting record(AAPL = data[symbol('AAPL')].price, MSFT = data[symbol('MSFT')].price, step_size = step_size, variability = variability )
def handle_data(self, context, data): # Implement your algorithm logic here. # data[sid(X)] holds the trade event data for that security. # context.portfolio holds the current portfolio state. # Place orders with the order(SID, amount) method. # TODO: implement your own logic here. context.trade_days += 1 if context.trade_days <> 5 : return context.trade_days = 0 ## checking the market status: ## if SPY > price one year ago, Market is in uptrend ## otherwise, market is in downtrend hist = history(bar_count = 241, frequency='1d', field='price') cash = context.portfolio.cash current_price_spy = data[symbol(self.ticker_spy)].price try: if current_price_spy > hist[symbol(self.ticker_spy)][200] : lst = self.top_rets(context.equities, 240) lst_mean = lst['zero'] count = len(lst_mean) for ticker in sector_tickers: if ticker in lst_mean: order_target_percent(symbol(ticker), 1.0/count) else : order_target_percent(symbol(ticker), 0) order_target_percent(symbol(self.ticker_gld), 0) order_target_percent(symbol(self.ticker_tlt), 0) else : for ticker in sector_tickers: order_target_percent(symbol(ticker), 0) order_target_percent(symbol(self.ticker_spy), 0) order_target_percent(symbol(self.ticker_gld), 0.5) order_target_percent(symbol(self.ticker_tlt), 0.5) except: pass
def handle_data(context, data): print context.portfolio.portfolio_value # Skip first 300 days to get full windows context.i += 1 if context.i < 300: return # Compute averages # history() has to be called with the same params # from above and returns a pandas dataframe. short_mavg = history(100, '1d', 'price').mean() long_mavg = history(300, '1d', 'price').mean() sym = symbol('AAPL') # Trading logic if short_mavg[sym] > long_mavg[sym]: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(sym, 100) elif short_mavg[sym] < long_mavg[sym]: order_target(sym, 0) # Save values for later inspection record(AAPL=data[sym].price, short_mavg=short_mavg[sym], long_mavg=long_mavg[sym])
def initialize(context): # Benchmark against the Dow Jones Industrial Average (DIA) api.set_benchmark(symbol('DIA')) # stop when trying to handle missing data api.set_nodata_policy(api.NoDataPolicy.EXCEPTION) # These are the default commission and slippage settings. Change them to fit your # brokerage fees. These settings only matter for backtesting. When you trade this # algorithm, they are moot - the brokerage and real market takes over. api.set_commission(api.commission.PerTrade(cost=0.03)) api.set_slippage(api.slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1)) # create an instance of the Dow30 class and set it within context context.dow30 = dow_constituents # next trade year context.year = 0 # set to True to trigger a rebalance context.trade = False # for tracking max leverage context.mx_lvrg = 0 # check for possible trades daily api.schedule_function(func=rebalance, date_rule=api.date_rules.every_day(), time_rule=api.time_rules.market_open(hours=1))
def top_rets(self, tickers, win) : hist = history(bar_count = 241, frequency='1d', field='price') ret = ((hist/hist.shift(win)) - 1).tail(1) mean_ret = float(np.median(ret)) max_ret = float(ret.max(axis=1)) spy_ret = float(ret[symbol(self.ticker_spy)]) lst = {} lst['mean'] = [] lst['spy'] = [] lst['zero'] = [] lst['max'] = [] for ticker in tickers : ticker_ret = float(ret[ticker]) if ticker_ret > mean_ret : lst['mean'].append(ticker) if ticker_ret > spy_ret: lst['spy'].append(ticker) if ticker_ret > 0: lst['zero'].append(ticker) if ticker_ret >= max_ret: lst['max'].append(ticker) return lst
def handle_data_macd(context, data): context.i += 1 if context.i < 60: return buy = False sell = False sym = symbol(code) count = int(100000 / data[sym].price) prices = history(40, '1d', 'price') macd = prices.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9) if context.investment == False: if macd[sym] > 0 and context.position == -1: order_target(sym, count) context.investment = True context.buy_price = data[sym].price buy = True context.position = 1 else: if (data[sym].price > context.buy_price + (context.buy_price * sell_point)): order_target(sym, -count) context.investment = False sell = True if macd[sym] < 0 : context.position = -1 if macd[sym] > 0 : context.position = 1 record(code=data[sym].price, macd=macd[sym], buy=buy, sell=sell)
def handle_data_bband(context, data): context.i += 1 if context.i < 20: return buy = False sell = False sym = symbol(code) count = int(100000 / data[sym].price) prices = history(20, '1d', 'price') upper, middle, lower = ta.BBANDS( prices[sym].values, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) if context.investment == False: if lower[-1] > data[sym].price: order_target(sym, count) context.investment = True context.buy_price = data[sym].price buy = True context.position = 1 else: if (data[sym].price > context.buy_price + (context.buy_price * sell_point)): order_target(sym, -count) context.investment = False sell = True record(code=data[sym].price, upper=upper[-1], lower=lower[-1], makeBacktestingDataFrame=middle[-1], buy=buy, sell=sell)
def handle_data_magc(context, data): context.i += 1 if context.i < 60: return ma20 = history(20, '1d', 'price').mean() ma60 = history(60, '1d', 'price').mean() buy = False sell = False sym = symbol(code) count = int(100000 / data[sym].price) if context.investment == False: if ma20[sym] > ma60[sym] : order_target(sym, count) context.investment = True context.buy_price = data[sym].price buy = True else: if (data[sym].price > context.buy_price + (context.buy_price * sell_point)): order_target(sym, -count) context.investment = False sell = True record(code=data[sym].price, ma20=ma20[sym], ma60=ma60[sym], buy=buy, sell=sell)
def positions(self): now = datetime.datetime.now() z_positions = protocol.Positions() for pos in self._client.positions(): if isinstance(pos, list): pos = TdxPosition(*pos) sid = pos.sid available = pos.available z_position = protocol.Position(symbol(sid)) z_position.amount = pos.amount z_position.cost_basis = pos.cost_basis z_position.last_sale_price = pos.last_sale_price z_position.last_sale_date = now z_positions[symbol(sid)] = z_position return z_positions
def initialize(context): # Let's set a look up date inside our backtest to ensure we grab the correct security #set_symbol_lookup_date('2015-01-01') # Use a very liquid set of stocks for quick order fills context.symbol = symbol('SPY') #context.stocks = symbols(['TWX','AIG','PSX','EMC','YHOO','MDY','TNA','CHK','FXI', # 'PEP','SBUX','VZ','VWO','TWC','HAL','MDLZ','CAT','TSLA', # 'MU','PM','WYNN','MET',NOV BRK_B SNDK ESRX YELP]) #set_universe(universe.DollarVolumeUniverse(99.5, 100)) #set_benchmark(symbol('SPY')) # set a more realistic commission for IB, remove both this and slippage when live trading in IB set_commission(commission.PerShare(cost=0.014, min_trade_cost=1.4)) # Default slippage values, but here to mess with for fun. set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1)) # Use dicts to store items for plotting or comparison context.next_pred_price = {} # Current cycles prediction #Change us! context.history_len = 500 # How many days in price history for training set context.out_of_sameple_bin_size = 2 context.score_filter = -1000.0 context.action_to_move_percent = 0.0 # Register 2 histories that track daily prices, # one with a 100 window and one with a 300 day window add_history(context.history_len, '1d', 'price') context.i = 0
def handle_data(self, data): ###################################################### # 1. Compute regression coefficients between PEP and KO params = self.ols_transform.handle_data(data, self.PEP, self.KO) if params is None: return intercept, slope = params ###################################################### # 2. Compute spread and zscore zscore = self.compute_zscore(data, slope, intercept) self.record(zscores=zscore, PEP=data[symbol("PEP")].price, KO=data[symbol("KO")].price) ###################################################### # 3. Place orders self.place_orders(data, zscore)
def initialize(context): """ Define algorithm""" print "Initialize..." global TRAINING_STOCK, BACKTEST_STOCK context.security = None #becomes symbol(BACKTEST_STOCK) context.benchmark = symbol('SPY') context.training_data = loadTrainingData(TRAINING_TIME, TRAINING_STOCK) context.training_data_length = len(context.training_data) - 2 context.normalized_data = Manager.normalize(context.training_data) # will have to redo every time step target = Manager.getTargets(context.normalized_data) context.training_data = context.training_data[:-2] # delete last data entry, because it won't be used context.normalized_data = context.normalized_data[:-2] # delete last data entry, because it won't be used #print target #plt.figure("Training Data") #for i in range(len(context.normalized_data[0])): # plt.plot([x[i] for x in context.normalized_data]) #plt.legend(['open', 'high', 'low', 'close', 'volume', 'price'], loc='upper left') #plt.show() print "Train..." #print len(context.training_data), len(context.normalized_data), len(target) context.strategy = STRATEGY_CLASS([context.normalized_data], [target], num_epochs=EPOCHS) print "Capital Base: " + str(context.portfolio.cash)
def initialize(context): context.asset = symbol('AAPL') # Explicitly set the commission to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
def initialize(context): # Register 2 histories that track daily prices, # one with a 100 window and one with a 300 day window add_history(100, "1d", "price") add_history(300, "1d", "price") context.sym = symbol("AAPL") context.i = 0
def _tdx_transaction_to_zipline(self, transaction): return ZPTransaction( asset=symbol(transaction.asset), amount=transaction.amount, dt=pd.to_datetime(transaction.dt).tz_localize('Asia/Shanghai').tz_convert('UTC'), price=transaction.price, order_id=self._tdx_to_zp_order_id(transaction.order_id), commission=transaction.commission, )
def initialize(context): # Register 2 histories that track daily prices, # one with a 100 window and one with a 300 day window add_history(100, '1d', 'price') add_history(300, '1d', 'price') context.sym = symbol('AAPL') context.i = 0