def run_strategy(context, data): # Get the data for the previous 900 minutes stock_data = data.history(context.stock, ["close"], 900, "1m") for stock in context.stock: # aggregate 15 minutes, all OHLCV columns stock_data["close"][stock] = (stock_data["close"][stock]).resample("15T", label="right", closed="right").last() stock_data["close"].dropna(inplace=True) # Calculate the SMAs for stock in context.stock: # Get the last 20 close prices last_20_prices = stock_data["close"][stock].iloc[-context.length_small_sma:] # Calculate the 20 SMA sma_20 = last_20_prices.mean() # Get the last 50 close prices last_50_prices = stock_data["close"][stock].iloc[-context.length_long_sma:] # Calculate the 50 SMA sma_50 = last_50_prices.mean() # Placing orders # Long Entry if ((sma_20 > sma_50) & (context.portfolio.positions[stock].amount == 0)): print("{} Going long on {}".format(get_datetime(), stock)) order_target_percent(stock, 0.5) # Exiting Long entry elif ((sma_20 < sma_50) & (context.portfolio.positions[stock].amount != 0)): print("{} Exiting {}".format(get_datetime(), stock)) order_target_percent(stock, 0)
def handle_data(context, data): print context #raw_input() #输出每天持仓情况 if not context.has_ordered: for stock in data: #openprice=history(3, '1d', 'open') closeprice = history(5, '1d', 'close') #-2:昨天,-3 前天.-4 大前天 print get_datetime(), closeprice[sid(stock)][0], closeprice[sid( stock)][1], closeprice[sid(stock)][2], closeprice[sid( stock)][3], closeprice[sid(stock)][4] #print closeprice,closeprice[sid(stock)][1] if closeprice[sid(stock)][-2] > closeprice[sid( stock)][-3] and closeprice[sid(stock)][-3] > closeprice[ sid(stock)][-4]: print "buy", get_datetime() order(stock, 300) elif closeprice[sid(stock)][-2] < closeprice[sid( stock)][-3] and closeprice[sid(stock)][-3] < closeprice[ sid(stock)][-4]: print "sell", get_datetime() order(stock, -300)
def _update_portfolio_metrics(self, context, data, s): strategy_price = 0 for p_no, p in enumerate(s.portfolios): price = np.sum([ context.portfolio.positions[a].amount * data.current(a, 'price') for a in p.all_assets ]) * s.weights[p_no] p.metrics.prices[get_datetime()] = price strategy_price += price try: calculate_SR = context.calculate_SR nominal_price = np.sum([ p.allocation_model.weights[i] * data.current(security, 'price') for i, security in enumerate(p.securities) ]) p.metrics.nominal_prices[get_datetime()] = nominal_price except: calculate_SR = False if calculate_SR: try: context.SR_lookback = context.SR_lookback context.SD_factor = context.SD_factor except: raise ValueError( 'context.SR_lookback and/or context.SR_factor missing') return p.metrics.rolling_n_day_SR[ get_datetime()] = self._calculate_SR(context, data, p) return strategy_price
def get_sea(context, data): largecap_ret1w = context.pipeline_data.loc[symbol('000016.SH'), 'wrets'] smallcap_ret1w = context.pipeline_data.loc[symbol('000905.SH'), 'wrets'] vol = get_atr(context, data) print('atr', vol, context.seavol) dispersion = largecap_ret1w - smallcap_ret1w first_w_of_m = testday(context, data) last_week_return = context.pipeline_data.loc[symbol('000300.SH'), 'wrets'] last_3m_return = context.pipeline_data.loc[symbol('000300.SH'), 'returns_5M'] eq_idx_dret = context.pipeline_data.loc[symbol('000300.SH'), 'drets'] eq_idx_wvol = context.pipeline_data.loc[symbol('000300.SH'), 'volatility'] / sqrt( 242) #beat context.seavol bondid = 'H11077.SH' #'H00140.SH' ` yld_wvol = context.pipeline_data.loc[symbol(bondid), 'volatility'] / sqrt(242) * sqrt(5) yld_wret = context.pipeline_data.loc[symbol(bondid), 'wrets'] rb_wret = context.pipeline_data.loc[symbol('CFRBPA.JZ'), 'wrets'] au_wret = context.pipeline_data.loc[symbol('CFAUPA.JZ'), 'wrets'] print('seatest', get_datetime()) for asset in context.pipeline_data.index: context.seadf.loc[ asset, 'vol'] = 1 if vol > context.seavol else -1 # .22 (a11), .88(1+0), context.seadf.loc[asset, 'bond'] = np.sign(yld_wret) #0.2sr context.seadf.loc[ asset, 'mom'] = 1 if last_3m_return > 0 else -1 # .88 (a11), context.seadf.loc[asset, 'sea'] = first_w_of_m #.26sr context.seadf.loc[asset, 'com'] = 1 if rb_wret < au_wret else -1 context.seadf.loc[ asset, 'dis'] = 1 if dispersion > .005 else -1 # 0. 87(000300), 1.4(+1) -0.08 (-1) context.seadf.loc[asset, 'check'] = ( np.sign(eq_idx_dret) ) if abs(eq_idx_dret) > eq_idx_wvol else 0 # -1 120180814 • sea_score = context.seadf.sum(axis=1) print('vol:', vol, context.seavol) print('bond:', yld_wret, yld_wvol) print('mom:', last_3m_return) print('com:', rb_wret, au_wret) print('dis1D:', context.pipeline_data.loc[symbol('000016.SH'), 'drets'], context.pipeline_data.loc[symbol('000905.SH'), 'drets']) print('dis6D:', context.pipeline_data.loc[symbol('000016.SH'), 'returns_6D'], context.pipeline_data.loc[symbol('000905.SH'), 'returns_6D']) print('dis1W:', context.pipeline_data.loc[symbol('000016.SH'), 'wrets'], context.pipeline_data.loc[symbol('000905.SH'), 'wrets']) print('get_returns', largecap_ret1w, smallcap_ret1w) print('seaoverall:', get_datetime().strftime('%Y-%m-%d'), ',', sea_score.loc[symbol('000300.SH')], '\n', context.seadf.loc[symbol('000300.SH')]) #test_dis = context.seadf.loc[symbol('000300.SH'), 'dis' ] toggle = 1 #if (sea score. loc[symbol('000300.SH')) - test_dis)*test_dis > 0 else .5 return (np.sign(sea_score), toggle)
def generate_signals(context, data): try: results = pipeline_output('strategy_pipeline') except NoFurtherDataError: print('no data for {}'.format(get_datetime())) # use other columns to print other indicators scanning results rsi = results.rsi.sort_values(ascending=True) print('{}{}'.format(get_datetime(),'-'*30)) print(rsi[:5]) print(rsi[-5:])
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): # 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 trade(context, data): if not context.fired: context.rebalance_date = get_datetime() #print("build portfolio at " + str(context.rebalance_date)) init_portfolio(context, data) context.fired = True else: now = get_datetime() if (need_rebalance(context, now)): #print("new rebalance arrivid:" + str(now)) context.rebalance_date = now rebalance(context, data)
def handle_data(context, data): context.save2mysql = 0 context.i += 1 print str(get_datetime()) record(weights=None) # 按照最大回撤值止损 context.adjust_date += 1 context.stop_date += 1 weight = get_weight(context) # print weight stocks = weight.keys() stop_loss_flag = True # 记录本次是否 # 更新最大净值 for stock in stocks: current_price = data[stock]["price"] try: current_price > context.init_value[stock] except: assert (False) if current_price > context.init_value[stock]: context.init_value[stock] = current_price # 判断是否需要止损 if context.adjust_date > 5 and context.adjust_date < 55 and \ context.stop_date > 5: ben_loss = -0.05 for stock in stocks: current_price = data[stock]["price"] returns = (current_price - context.init_value[stock]) / context.init_value[stock] if returns < 0: # 分风险类别进行止损,激进组合止损不同 if context.mdd < 0.07: a = returns else: a = returns * weight[stock] / (1 + returns) if a < ben_loss: stop_loss(context, stock, data) print "!!紧急调仓: " + str(get_datetime()) print stock, current_price, context.init_value[stock] stop_loss_flag = False else: continue if stop_loss_flag: record(weights=None) record(rebalance_reason=None) else: context.stop_date = 0 context.old_value = context.portfolio.portfolio_value
def testday(context, data): from zipline.utils.tradingcalendar import trading_day from pandas import date_range tdate = get_datetime() tdate_mon = tdate.strftime('%m') week_later = tdate + relativedelta(weeks=+1) week_before = tdate + relativedelta(weeks=-1) print('week_later', week_later.strftime('%Y-%m'), context.last_reb_month) sdate = week_later.strftime('%Y-%m') + '-01' edate = week_later.strftime('%Y-%m') + '-15' next_month_days = date_range(sdate, edate, freq=trading_day, tz='Asia/Shanghai') d1 = pd.to_datetime(tdate.strftime("%Y-%m-%d")) d2 = pd.to_datetime(datetime.strftime(next_month_days[0], "%Y-%m-%d")) d_diff = pd.Timedelta(d2 - d1).days first_w_of_m = 0 if (d_diff < 5 and d_diff > 0) or (context.last_reb_month != tdate.strftime('%Y-%m')): print('mend', tdate, next_month_days[0]) print('mdiff', type(week_later), (next_month_days[0])) first_w_of_m = 1 print('first_w_of_m', first_w_of_m, d_diff, d1, d2) return np.sign(first_w_of_m)
def initialize(context): """ use our factors to add our pipes and screens. """ pipe = Pipeline() attach_pipeline(pipe, 'ff_example') mkt_cap = MarketEquity() pipe.add(mkt_cap, 'market_cap') book_equity = BookEquity() # book equity over market equity bm = book_equity/mkt_cap pipe.add(bm, 'bm') # 营运能力 op = OP() pipe.add(op, 'op') # 投资因子 inv = INV() pipe.add(inv, 'inv') returns = Returns(window_length=2) pipe.add(returns, 'returns') dt = get_datetime().normalize() start_ = dt if dt > START_DATE else START_DATE context.result = result.loc[start_: , :]
def wrapper(context, data): dt = get_datetime() if dt.date() != context.current_date: context.warmup -= 1 context.mins_for_days.append(1) context.current_date = dt.date() else: context.mins_for_days[-1] += 1 hist = context.history(2, '1d', 'close_price') for n in (1, 2, 3): if n in data: if data[n].dt == dt: context.vol_bars[n].append(data[n].volume) else: context.vol_bars[n].append(0) context.price_bars[n].append(data[n].price) else: context.price_bars[n].append(np.nan) context.vol_bars[n].append(0) context.last_close_prices[n] = hist[n][0] if context.warmup < 0: return f(context, data)
def rebalance(context, data): # Wait for 756 trading days (3 yrs) of historical prices before trading if context.day < context.min_data_window - 1: return # Get expanding window of past prices and compute returns context.today = get_datetime().date() prices = data.history(context.assets, "price", context.day, "1d") if context.first_rebal_date is None: context.first_rebal_date = context.today context.first_rebal_idx = context.day print('Starting dynamic allocation simulation...') # Get investment horizon in days ie number of trading days next month context.tau = rnr.get_num_days_nxt_month(context.today.month, context.today.year) # Calculate HFP distribution asset_rets = np.array(prices.pct_change(context.tau).iloc[context.tau:, :]) num_scenarios = len(asset_rets) # Set Flexible Probabilities Using Exponential Smoothing half_life_prjn = 252 * 2 # in days lambda_prjn = np.log(2) / half_life_prjn probs_prjn = np.exp(-lambda_prjn * (np.arange(0, num_scenarios)[::-1])) probs_prjn = probs_prjn / sum(probs_prjn) mu_pc, sigma2_pc = rnr.fp_mean_cov(asset_rets.T, probs_prjn) # Perform shrinkage to mitigate estimation risk mu_shrk, sigma2_shrk = rnr.simple_shrinkage(mu_pc, sigma2_pc) weights, _, _ = rnr.efficient_frontier_qp_rets(context.n_portfolio, sigma2_shrk, mu_shrk) print('Optimal weights calculated 1 day before month end on %s (day=%s)' \ % (context.today, context.day)) #print(weights) min_var_weights = weights[0,:] # Rebalance portfolio accordingly for stock, weight in zip(prices.columns, min_var_weights): order_target_percent(stock, np.asscalar(weight)) context.weights = min_var_weights
def rebalance(self, context, data): # make sure there's algo data if not isinstance(context.algo_data, dict): return elif not self.first_time: if self.rebalance_count != context.rebalance_interval: self.rebalance_count += 1 return self.first_time = False self.rebalance_count = 1 log.info('----------------------------------------------------------------------------') log.debug(get_datetime()) self.allocations = pd.Series(0., index=self.all_assets) self.elligible = pd.Index(self.strategy_IDs) self.allocation_model.caller = self if self.regime == None: self._get_strategy_and_portfolio_allocations(context) else: self._check_for_regime_change_and_set_active(context) self.weights = self.allocation_model.get_weights(context) self.allocations = self._allocate_assets(context) self._execute_orders(context, data) return self.allocations
def wrapper(context, data): dt = get_datetime() if dt.date() != context.current_date: context.warmup -= 1 context.mins_for_days.append(1) context.current_date = dt.date() else: context.mins_for_days[-1] += 1 hist = context.history(2, "1d", "close_price") for n in (1, 2, 3): if n in data: if data[n].dt == dt: context.vol_bars[n].append(data[n].volume) else: context.vol_bars[n].append(0) context.price_bars[n].append(data[n].price) else: context.price_bars[n].append(np.nan) context.vol_bars[n].append(0) context.last_close_prices[n] = hist[n][0] if context.warmup < 0: return f(context, data)
def generate_signals(context, data): try: pipeline_results = pipeline_output('strategy_pipeline') except NoFurtherDataError: context.long_securities = [] context.short_securities = [] return p = context.params['percentile'] pipeline_results = pipeline_results[pipeline_results.vol > 0].dropna() vol_threshold_hi = pipeline_results.vol.quantile(0.75) vol_threshold_lo = pipeline_results.vol.quantile(0.25) high_vol = pipeline_results[pipeline_results.vol > vol_threshold_hi] low_vol = pipeline_results[pipeline_results.vol < vol_threshold_lo] short_candidates = high_vol.sort_values('skew', ascending=False) long_candidates = low_vol.sort_values('skew', ascending=False) available = min(len(long_candidates), len(short_candidates)) n = int(available * p) print('total candidates {}'.format(n)) if n == 0: print("{}, no signals".format(get_datetime())) context.long_securities = [] context.short_securities = [] context.long_securities = long_candidates.index[:n] context.short_securities = short_candidates.index[:n]
def rebalance(context, data): log.info("rebalance) " + str(normalize_date(get_datetime()))) # Pipeline data will be a dataframe with boolean columns named 'longs' and # 'shorts'. pipeline_data = context.pipeline_data.dropna() log.info(pipeline_data.head()) all_assets = pipeline_data.index longs = all_assets[pipeline_data.longs] shorts = all_assets[pipeline_data.shorts] record(universe_size=len(all_assets)) # Build a 2x-leveraged, equal-weight, long-short portfolio. one_third = 1.0 / 3.0 for asset in longs: order_target_percent(asset, one_third) for asset in shorts: order_target_percent(asset, -one_third) # Remove any assets that should no longer be in our portfolio. portfolio_assets = longs | shorts positions = context.portfolio.positions for asset in viewkeys(positions) - set(portfolio_assets): # This will fail if the asset was removed from our portfolio because it # was delisted. if data.can_trade(asset): order_target_percent(asset, 0)
def handle_data(context, data): # 去除时间,保留日期 dt = get_datetime().normalize() context.result.loc[dt, 'SMB'] = context.smb context.result.loc[dt, 'HML'] = context.hml context.result.loc[dt, 'RMW'] = context.rmw context.result.loc[dt, 'CMA'] = context.cma
def handle_data(context, data): # Skip first 300 days to get full windows date = get_datetime() context.i += 1 if context.i < 10: return prices = history(25, '1d', 'price') for sym in data: upper, middle, lower = talib.BBANDS( np.array(prices[sym]), timeperiod=20, nbdevup=2, nbdevdn=2, matype=0 ) potential_buy = [] buy = False sell = False if data[sym].price > upper[-1] and context.portfolio.positions[sym].amount == 0: # log.info('buy') # log.info(get_datetime()) # log.info(data[sym].price) # log.info(upper[-1]) order_target_percent(sym, 1.0, limit_price=data[sym].price) elif data[sym].price < middle[-1] and context.portfolio.positions[sym].amount > 0: # log.info('sell') # log.info(get_datetime()) # log.info(data[sym].price) # log.info(middle[-1]) order_target(sym, 0, limit_price=data[sym].price)
def rebalance(context, data): #print context.pipeline_data print("today 0 :", type(get_datetime()), get_datetime(), type(context.sim_params.end_session), context.sim_params.end_session.day) if (context.sim_params.end_session.day != get_datetime().day): return print("today 1 :", get_datetime()) pipeline_data = context.pipeline_data pipeline_data.index = [index.symbol for index in pipeline_data.index] shorts, longs = context.strategy.compute_allocation(data, pipeline_data) print("to trade:", shorts, longs) context.strategy.trade(shorts, longs) pass
def before_trading_start(context, data): dt = api.get_datetime() # rebalance at the beginning or at the beginning of a new year if context.year == 0 or context.year == dt.year or len(context.portfolio) != 10: context.trade = True context.year = dt.year + 1 # get our dow 30 stocks members = get_dow(context.dow30) sids = [m.sid for m in members] # get fundamentals, save, and update universe # PROBLEM: this does not always sync up with Dow30 # PROBLEM: example, returns "CAT"/1267 and "CAT_WI"/11740 fundamentals_df = api.get_fundamentals( api .query( api.fundamentals.valuation_ratios.pe_ratio, api.fundamentals.valuation_ratios.dividend_yield, ) .filter(api.fundamentals.share_class_reference.sid.in_(sids)) .order_by( api.fundamentals.valuation_ratios.dividend_yield.desc() # sort by highest to lowest dividend yield ) .limit(10) # take the top 10 highest paying dividend ) context.fundamentals_df = fundamentals_df # save to context to use during rebalance() api.update_universe(fundamentals_df.columns.values)
def n_period_momentum(self, context): # percentage increase over n periods # arg[0] = no of periods # arg[1] = period : 'D'|'W'|'M' (day|week||month) h = context.dp[self.inputs[0]] lookback = self.kwargs['lookback'] period = self.kwargs['period'] if period in ['W', 'M']: if h.index[-1].date() == get_datetime().date(): ds = h.resample('M', how='last').pct_change(lookback).iloc[-1] else: ds = h.resample('M', how='last').pct_change(lookback).iloc[-2] else: ds = h.pct_change(lookback).iloc[-1] df = pd.DataFrame(0, index=h.index, columns=h.columns) df.iloc[-1] = ds context.dp[self.outputs[0]] = df return context.dp
def handle_data(context, data): now = get_datetime() today = datetime(now.year, now.month, now.day, 0, 0) # Get current day's headlines current_headlines = [] for i in range(0, len(context.headlines)): if (today == context.headlines.iloc[i]['date']): current_headlines.append((context.headlines.iloc[i]['ticker'], context.headlines.iloc[i]['text'])) print current_headlines # Calculate sentiment sentiment = dict() for headline in current_headlines: ticker = headline[0] text = headline[1] #TODO: Get score from classifier score = -1 if ticker in sentiment.keys(): sentiment[ticker] += score else: sentiment[ticker] = score # Long/Short stocks based on sentiment for ticker in sentiment.keys(): #TODO: Order stocks if sentiment[ticker] > context.long_thresh: #long stocks print "long " + ticker if sentiment[ticker] < context.short_thresh: #short stocks print "short " + ticker return
def scheduled_rebalance(context, data): month = get_datetime().month if month == scheduled_month: stocks = patch_fund(context, data) print(stocks) # print stocks rebalance(context, data, stocks)
def rebalance(context, data): if not interval_countdown(context, data, rebalance): return #generate_strat_data(context, data) print ('\nREBALANCE {}'.format(get_datetime())) context.new_weights = pd.Series(0., index=context.stocks) for strategy in context.strategies : for portfolio_no, assets in enumerate(context.strategies[strategy]['portfolios']): # rank portfolio assets according to zscore parameters ranks = rank_assets (context, strategy, assets, portfolio_no) #elligible_pre portfolio assets are those with rank <= n_top elligible_pre = ranks.index[ranks<=context.strategies[strategy]['n_top']] # apply asset filter elligible_post = filter_assets(context, strategy, elligible_pre, context.strategies[strategy]['filter']) # asset allocation new_weights = allocate_assets(context, strategy, portfolio_no, elligible_pre, elligible_post) context.new_weights = context.new_weights + new_weights return
def show_positions (context, data): if context.order_placed == True : print ('\n{}'.format(get_datetime().date())) print ('\nPOSITIONS\n\n') for asset in context.stocks : if context.portfolio.positions[asset].amount > 0 : print ( '{0} : QTY = {1}, COST BASIS {2:3.2f}, CASH = {3:7.2f}, POSITIONS VALUE = {4:7.2f}, TOTAL = {5:7.2f}' .format(asset, context.portfolio.positions[asset].amount, context.portfolio.positions[asset].cost_basis, context.portfolio.cash, context.portfolio.positions[asset].amount * data[asset].price, context.portfolio.portfolio_value)) # retrieve all the open orders and log the total open amount # for each order open_orders = get_open_orders() # open_orders is a dictionary keyed by sid, with values that are lists of orders. if open_orders: # iterate over the dictionary for security, orders in open_orders.iteritems(): # iterate over the orders for oo in orders: message = '\nOutstanding open order for {amount} shares in {stock}' message = message.format(amount=oo.amount, stock=security) print(message) return else: # wait until all orders filled before resetting this flag context.order_placed = False return
def process_record(self, record): """ use the date of the trading day for log purposes """ super().process_record(record) if self.arena == 'live': send_mail(record.channel + " " + record.level_name, record.message) record.time = get_datetime()
def initialize(context): print("{}:inside initialize".format(get_datetime())) schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open()) context.frequency = 120 context.loop_count = 0
def handle_data(context, data): sentiment = dict() now = get_datetime() today = datetime(now.year, now.month, now.day, 0, 0) print list(context.headlines['date'])[0] print today for headline in list( context.headlines[context.headlines['date'] == today]): print headline
def handle_data(context, data): context.i += 1 print(get_datetime()) record(weights=None) record(TRC=None) record(MRC=None) record(rebalance_reason=None)
def handle_data(context, data): day_option_df = context.options[context.options['date'] == get_datetime()] call_options = day_option_df[day_option_df['type'] == 'C'] ################################## classifier stuff happens somewhere here call_options_good = call_options # call_options_good is the classified call_options ################################## # purchase the options that we think will end up in the money (could also modify this to give weight to it) for index, row in call_options_good.iterrows(): context.bought_options = rbind(context.bought_options, row) cash -= row['price'] # exercise expiring options that we've bought (assuming strike price is lower than expiration price) expiring_calls = context.bought_options[context.bought_options['expiration'] == get_datetime()] for index, row in expiring_calls.iterrows(): price = history(symbol(row['ticker']), '1d', 'price').iloc[0,0] cash += 100*max(price - row['strike'], 0) # assuming 100:1 ratio equity:option
def handle_data(context, data): contract = data.current(context.my_cf, 'contract') log.info(contract) log.info(get_datetime()) x = data.current(contract, 'price') log.info(x) # order_target(contract, 10) #order_target_value(contract, 100000) order_target_percent(contract, 1.0)
def handle_data(context, data): """This function will be executed every minute to check if an order should be placed now, and place the order if so.""" # quant = 0 if timestamp of now is not in context.trades quant = context.trades.get(get_datetime(), 0) if quant != 0: order(context.asset, quant) # place an order # use "_asset" as a temporary placeholder col name for actual trading pair record(_asset=data.current(context.asset, 'price'))
def handle_data(context, data): # Get current date now = str(get_datetime('US/Eastern'))[0:11] + "00:00:00+0000" # Get current state state = gv.TP_matrixs.ix[now].values # Epsilon-greedy Algorithm # Choose an action to execute according to current state probab = random.random() if probab <= gv.epsilon: # Epsilon # Take random action action = gv.action_set[random.randint(0, 2)] else: # 1 - epsilon # Take the action of the highest Q-Value action_values = [gv.Q_function(state, gv.action_set[0]), gv.Q_function(state, gv.action_set[1]), gv.Q_function(state, gv.action_set[2])] action = gv.action_set[action_values.index(max(action_values))] # Execute chosen action if action == gv.action_set[0]: # Sell order(context.security, -gv.mu) elif action == gv.action_set[1]: # Buy order(context.security, gv.mu) elif action == gv.action_set[2]: # Hold pass # Construct labeled data global Q_data, Q_labels # Juage if it's the first day if context.action_prev != "": y = context.portfolio.portfolio_value - \ context.portfolio_prev + gama * gv.Q_function(state, action) # Add new data if Q_data[context.action_prev].size == 0: Q_data[context.action_prev] = np.array( [gv.TP_matrixs.ix[context.date_prev].values.tolist()], dtype=np.float32) else: Q_data[context.action_prev] = np.vstack(( Q_data[context.action_prev], [gv.TP_matrixs.ix[context.date_prev].values.tolist()])) # Add new label Q_labels[context.action_prev] = np.append( Q_labels[context.action_prev], y) # Update saved previous information context.date_prev = now context.action_prev = action context.portfolio_prev = context.portfolio.portfolio_value
def view_status(self, context, data): if not self.actions is None: start_cash = float(self.param_dict["cash"]) / float( self.n_portfolios) today = str(get_datetime())[:-15] value = float(self.cash) returns = float(float(self.cash - start_cash) / start_cash * 100) #confidence = float(self.actions.confidence) n_long = int(len(self.longs)) n_short = int(len(self.shorts)) leverage = context.account.leverage date_str = "[{!s}]\t" ret_str = "total returns: {:03.2f}%\t" value_str = "value: ${:03,.2f}\t" s_str = "n short: {:n}\t" l_str = "n long: {:n}\t" conf_str = "confidence: {:03.2f}%" lev_str = "leverage: {:03.2f}" template = date_str + ret_str + value_str + s_str + l_str + lev_str #+ conf_str template = template.format(today, returns, value, n_short, n_long, leverage) #, confidence) # template = "[{!s}]\ttotal returns: {:03.2f}%\tvalue: ${:03,.2f}\tn short:{:n}\n long: {:n}\tconfidence:{:03.2f}%"\ # .format(today, returns, value, n_short, n_long, float(confidence)) log.info(template) stocks_template = "" n_held = len(context.portfolio.positions) net_gain = 0 for eq, pos in context.portfolio.positions.iteritems(): ticker = eq.symbol n_shares = pos.amount current_val = pos.last_sale_price * n_shares paid_val = pos.cost_basis * n_shares net_gain += current_val - paid_val # stock_template = "stock {!s}:\tnet gain: {:03.2f}\t".format(ticker, net_gain) # stocks_template += stock_template # log.info(stocks_template) sign = "$" if net_gain >= 0 else "-$" log.info("n held: {:n}\t net gain: {!s}{:03.2f}\t".format( n_held, sign, abs(net_gain))) tickers = "" eqs = self.market.index.values.tolist() for i in xrange(min(len(eqs), 10)): tickers += "{!s} ".format(eqs[i].symbol) log.info("Market: " + tickers) return self.cash
def handle_data(context, data): today = get_datetime() factors = data.factors for length, key in iteritems(vwap_keys): for asset in assets: computed = factors.loc[asset, key] expected = vwaps[length][asset].loc[today] # Only having two places of precision here is a bit # unfortunate. assert_almost_equal(computed, expected, decimal=2)
def handle_data(context, data): # 获取股票的收盘价 close_data = history(12,'1d','close') # 取得过去五天的平均价格 ma5 = close_data[-6:-2].mean() # 取得过去10天的平均价格 ma10 = close_data[-11:-2].mean() # 取得当前的现金 print get_datetime(),ma5,ma10 cash = context.portfolio.cash #print ma5[sid(symbol(context.security))],ma10[sid(stock)],cash,symbol(context.security) #如果当前有余额,并且五日均线大于十日均线 if ma5[sid(symbol(context.security))] > ma10[sid(symbol(context.security))]: order_value(symbol(context.security), cash) # 如果五日均线小于十日均线,并且目前有头寸 elif ma5[sid(symbol(context.security))] < ma10[sid(symbol(context.security))]: # 全部卖出 order_target(symbol(context.security), 0)
def handle_orders(context, data): if (context.new_weights == context.current_weights).all() : print ('\n{} ALLOCATION UNCHANGED\n'.format(get_datetime().date())) return for asset in context.new_weights.index: if abs(context.new_weights[asset] - context.current_weights[asset]) > context.threshold : print ('\n{} ORDER {} of {} @ {}'.format(get_datetime(), context.new_weights[asset], asset, data[asset].close_price)) order_target_percent(asset, context.new_weights[asset]) context.current_weights = context.new_weights context.order_placed = True # print (context.strat_data['price'].ix[-1]) # print ('\n\n', get_open_orders()) return
def handle_data(context, data): factors = data.factors date = get_datetime().normalize() for asset in self.assets: # Assets should appear iff they exist today and yesterday. exists_today = self.exists(date, asset) existed_yesterday = self.exists(date - trading_day, asset) if exists_today and existed_yesterday: latest = factors.loc[asset, 'close'] self.assertEqual(latest, self.expected_close(date, asset)) else: self.assertNotIn(asset, factors.index)
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): results = pipeline_output("test") date = get_datetime().normalize() for asset in self.assets: # Assets should appear iff they exist today and yesterday. exists_today = self.exists(date, asset) existed_yesterday = self.exists(date - self.trading_day, asset) if exists_today and existed_yesterday: latest = results.loc[asset, "close"] self.assertEqual(latest, self.expected_close(date, asset)) else: self.assertNotIn(asset, results.index)
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 wait_for_data (context, data): if context.waiting_for_data : print ('\n{} WAITING FOR DATA...'.format(get_datetime().date())) # wait for history to fill max_lookback = context.max_lookback highs = history (max_lookback, '1d', 'high') if not highs.ix[0].sum() > 0 : return else: context.waiting_for_data = False return
def handle_data(context, data): today = normalize_date(get_datetime()) results = pipeline_output("test") expect_over_300 = {AAPL: today < self.AAPL_split_date, MSFT: False, BRK_A: True} for asset in assets: should_pass_filter = expect_over_300[asset] if set_screen and not should_pass_filter: self.assertNotIn(asset, results.index) continue asset_results = results.loc[asset] self.assertEqual(asset_results["filter"], should_pass_filter) for length in vwaps: computed = results.loc[asset, vwap_key(length)] expected = vwaps[length][asset].loc[today] # Only having two places of precision here is a bit # unfortunate. assert_almost_equal(computed, expected, decimal=2)
def handle_data(context, data): closes = pipeline_output('test_close') volumes = pipeline_output('test_volume') date = get_datetime().normalize() for asset in self.assets: # Assets should appear iff they exist today and yesterday. exists_today = self.exists(date, asset) existed_yesterday = self.exists(date - self.trading_day, asset) if exists_today and existed_yesterday: self.assertEqual( closes.loc[asset, 'close'], self.expected_close(date, asset) ) self.assertEqual( volumes.loc[asset, 'volume'], self.expected_volume(date, asset) ) else: self.assertNotIn(asset, closes.index) self.assertNotIn(asset, volumes.index)
def generate_strat_data (context, data) : print ('\n{} GENERATING STRAT_DATA...'.format(get_datetime().date())) # if ENVIRONMENT != 'IDE': # wait_for_data(context, data) # if context.waiting_for_data : # return for item in ['high', 'open_price', 'low', 'close_price', 'volume', 'price']: context.strat_data[item] = history(context.max_lookback, '1d', item) # need to do this to keep talib happy context.strat_data['open'] = context.strat_data['open_price'] context.strat_data['close'] = context.strat_data['close_price'] # return a dataframe for each transform for transform in context.algo_transforms : panel = apply_transform(context, transform) context.strat_data = {i: panel[i] for i in panel.items}
def rebalance(context, data): if context.trade == True: log.info('REBALANCING...') context.trade = False dt = get_datetime() members = context.dow30.get(dt) for s in members: if s not in data: log.error("NoTradeDataAvailableEvent for %s" % s.symbol) for s in data: if s in members and s in context.fundamentals_df.columns: log.info('ordering %s, price = %.2f, yield = %.2f' % (s.symbol, data[s].price, 100 * context.fundamentals_df[s].dividend_yield)) order_target_percent(s, .1) else: order_target_percent(s, 0) log.info('\n')