def handle_data(context, data): current_time = get_datetime().time() # When model is empty if len(context.model.get_renko_prices()) == 0: context.model = pyrenko.renko() history = data.history(context.asset, 'price', bar_count=context.n_history, frequency=context.tf) # Get daily absolute returns diffs = history.diff(context.diff_lag).abs() diffs = diffs[~np.isnan(diffs)] # Calculate IQR of daily returns iqr_diffs = np.percentile(diffs, [25, 75]) # Find the optimal brick size opt_bs = opt.fminbound(lambda x: -evaluate_renko( brick=x, history=history, column_name='score'), iqr_diffs[0], iqr_diffs[1], disp=0) # Build the model context.last_brick_size = opt_bs context.model.set_brick_size(brick_size=opt_bs, auto=False) context.model.build_history(prices=history) # Open a position order_target_percent( context.asset, context.leverage * context.model.get_renko_directions()[-1]) else: last_price = data.history( context.asset, 'price', bar_count=1, frequency='1440T', ) # Just for output and debug prev = context.model.get_renko_prices()[-1] prev_dir = context.model.get_renko_directions()[-1] num_created_bars = context.model.do_next(last_price) # If the last price moves in the backward direction we should rebuild the model if np.sign(context.portfolio.positions[context.asset].amount * context.model.get_renko_directions()[-1]) == -1: order_target_percent(context.asset, 0.0) context.model = pyrenko.renko() # or we cover the part of the position elif context.part_cover_ratio > 0.0 and num_created_bars != 0: order_target( context.asset, context.portfolio.positions[context.asset].amount * (1.0 - context.part_cover_ratio))
def handle_data(self, data): from catalyst.api import ( order_percent, order_target, order_target_percent, order_target_value, order_value, ) for style in [MarketOrder(), LimitOrder(10), StopOrder(10), StopLimitOrder(10, 10)]: with assert_raises(UnsupportedOrderParameters): order(self.asset, 10, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order(self.asset, 10, stop_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_value(self.asset, 300, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_value(self.asset, 300, stop_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_percent(self.asset, .1, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_percent(self.asset, .1, stop_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target(self.asset, 100, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target(self.asset, 100, stop_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target_value(self.asset, 100, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target_value(self.asset, 100, stop_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target_percent(self.asset, .2, limit_price=10, style=style) with assert_raises(UnsupportedOrderParameters): order_target_percent(self.asset, .2, stop_price=10, style=style)
def handle_data(context, data): if not context.blotter.open_orders: if context.portfolio.positions and context.portfolio.positions[ context.asset].amount > 0.5: order_target(context.asset, 0, limit_price=(data.current(context.asset, 'price') + 0.00013)) else: order_target(context.asset, 1, limit_price=(data.current(context.asset, 'price') + 0.00003)) record(btc=data.current(context.asset, 'price'))
def handle_data(context, data): if not context.blotter.open_orders: if (context.portfolio.positions and context.portfolio.positions[context.asset].amount >= 2): order(context.asset, -2, limit_price=(data.current(context.asset, 'price') - 0.00000002)) else: order_target(context.asset, 3, limit_price=(data.current(context.asset, 'price') + 0.00000002)) record(btc=data.current(context.asset, 'price'))
def weAreShort(context, analysis): s1 = context.asset TP = context.cost_basis - context.lower SL = context.cost_basis + context.upper Crit = context.cost_basis position = context.portfolio.positions[context.asset] log.info( "We are Short. Holdings: {amount} @ {cost_basis}".format( amount=position.amount, cost_basis=context.cost_basis ) ) if context.price > Crit: order(s1, amount=(context.ORDER_SIZE * context.multiplyBy * context.level)) context.in_long = True context.in_short = False context.level += 1 log.info( "Kill Short! GO LONG! Sold {amount} @ {price}".format( amount=position.amount, price=context.price ) ) elif context.price < TP: context.in_long = False context.in_short = False context.level = 1 order_target(s1, 0) log.info( "We made it! Sold {amount} @ {price}".format( amount=position.amount, price=context.price ) ) elif context.price > SL: context.in_long = False context.in_short = False context.level = 1 order_target(s1, 0) log.info( "We lost it all! Sold {amount} @ {price}".format( amount=position.amount, price=context.price ) ) else: log.info("no buy or sell opportunity found")
def weAreLong(context, analysis): s1 = context.asset TP = context.cost_basis + context.upper SL = context.cost_basis - context.lower Crit = context.cost_basis - context.distance position = context.portfolio.positions[context.asset] log.info('We Are Long. Holdings: {amount} @ {cost_basis}'.format( amount=position.amount, cost_basis=context.cost_basis)) if context.price < Crit: order( s1, amount=-(context.ORDER_SIZE * context.multiplyBy * context.level)) context.in_long = False context.in_short = True context.level += 1 log.info('Kill Long! GO SHORT! Sold {amount} @ {price}'.format( amount=position.amount, price=context.price)) elif context.price > TP: context.in_long = False context.in_short = False context.level = 1 order_target(s1, 0) log.info('We made it! Sold {amount} @ {price}'.format( amount=position.amount, price=context.price)) elif context.price < SL: context.in_long = False context.in_short = False context.level = 1 order_target(s1, 0) log.info('We lost it all! Sold {amount} @ {price}'.format( amount=position.amount, price=context.price)) else: log.info('no buy or sell opportunity found')
def handle_data(context, data): """ 在每个交易周期上运行的策略 """ context.i += 1 # 记录交易周期 if context.i < LONG_WIN + 1: # 如果交易周期过短,无法计算均线,则跳过循环 log.warning('交易周期过短,无法计算指标') return if context.i % TRADE_WIN != 0: return # 获取当前周期内有效的加密货币 context.available_asset_pool = [asset for asset in context.asset_pool if asset.start_date <= data.current_dt] context.up_cross_signaled = set() # 初始化金叉的交易对集合 context.down_cross_signaled = set() # 初始化死叉的交易对集合 for asset in context.available_asset_pool: # 遍历每一个加密货币对 # 获得历史价格 frequency = '{}T'.format(TRADE_WIN) # '5T' hitory_data = data.history(asset, 'close', bar_count=LONG_WIN + 1, frequency=frequency, ) if len(hitory_data) >= LONG_WIN + 1: # 保证新的货币有足够的时间计算均线 # 计算双均线 short_avgs = hitory_data.rolling(window=SHORT_WIN).mean() long_avgs = hitory_data.rolling(window=LONG_WIN).mean() # 双均线策略 # 短期均线上穿长期均线 if (short_avgs[-2] < long_avgs[-2]) and (short_avgs[-1] >= long_avgs[-1]): # 形成金叉 context.up_cross_signaled.add(asset) # 短期均线下穿长期均线 if (short_avgs[-2] > long_avgs[-2]) and (short_avgs[-1] <= long_avgs[-1]): # 形成死叉 context.down_cross_signaled.add(asset) # 卖出均线死叉信号的持仓交易对 for asset in context.portfolio.positions: if asset in context.down_cross_signaled: order_target(asset, 0) # 买入均线金叉信号的持仓股 for asset in context.up_cross_signaled: if asset not in context.portfolio.positions: close_price = data.current(asset, 'close') available_cash = get_available_cash(context) if available_cash > 0: # 如果有可用现金 # 每个交易对平均分配现金 cash_for_each_asset = available_cash / len(context.available_asset_pool) amount_to_buy = cash_for_each_asset / close_price # 计算购买的数量 if amount_to_buy >= asset.min_trade_size: # 购买的数量大于最小购买数量 order(asset, amount_to_buy) # 持仓比例 pos_level = context.portfolio.positions_value / context.portfolio.portfolio_value # 记录每个交易周期的现金 record(cash=context.portfolio.cash, pos_level=pos_level) # 输出信息 log.info('日期:{},资产:{:.2f},持仓比例:{:.6f}%,持仓产品:{}'.format( data.current_dt, context.portfolio.portfolio_value, pos_level * 100, ', '.join([asset.asset_name for asset in context.portfolio.positions])) )
def handle_data(context, data): current_time = get_datetime().time() if current_time.hour == 0 and current_time.minute == 0: print("Current date is " + str(get_datetime().date())) # we check if the model is empty we should get the data, # calculate IQR, optimize the brick size, build the Renko chart, and open the order. if len(context.model.get_renko_prices()) == 0: context.model = renko() history = data.history(context.asset, "price", bar_count=context.n_history, frequency=context.tf) # Get daily absolute returns diffs = history.diff(1).abs() diffs = diffs[~np.isnan(diffs)] # Calculate Interquartile range of daily returns iqr_diffs = np.percentile(diffs, [25, 75]) # Find the optimal brick size opt_bs = opt.fminbound( lambda x: -evaluate_renko( brick=x, history=history, column_name="score"), iqr_diffs[0], iqr_diffs[1], disp=0, ) # Build the model print("REBUILDING RENKO: " + str(opt_bs)) context.last_brick_size = opt_bs context.model.set_brick_size(brick_size=opt_bs, auto=False) context.model.build_history(prices=history) # Open a position if context.model.get_renko_directions()[-1] == 1: order_target_percent(context.asset, 1) elif context.model.get_renko_directions()[-1] == -1: order_target_percent(context.asset, 0) # Open a position order_target_percent( context.asset, context.leverage * context.model.get_renko_directions()[-1]) # Store some information record( rebuilding_status=1, brick_size=context.last_brick_size, price=history[-1], renko_price=context.model.get_renko_prices()[-1], num_created_bars=0, amount=context.portfolio.positions[context.asset].amount, ) else: last_price = data.history( context.asset, "price", bar_count=1, frequency="1440T", ) # Just for output and debug prev = context.model.get_renko_prices()[-1] prev_dir = context.model.get_renko_directions()[-1] num_created_bars = context.model.do_next(last_price) if num_created_bars != 0: print("New Renko bars created") print("last price: " + str(last_price)) print("previous Renko price: " + str(prev)) print("current Renko price: " + str(context.model.get_renko_prices()[-1])) print("direction: " + str(prev_dir)) print("brick size: " + str(context.model.brick_size)) # Store some information record( rebuilding_status=0, brick_size=context.last_brick_size, price=last_price, renko_price=context.model.get_renko_prices()[-1], num_created_bars=num_created_bars, amount=context.portfolio.positions[context.asset].amount, ) # If the last price moves in the backward direction we should rebuild the model if (np.sign(context.portfolio.positions[context.asset].amount * context.model.get_renko_directions()[-1]) == -1): order_target_percent(context.asset, 0.0) context.model = renko() # or we cover the part of the position elif context.part_cover_ratio > 0.0 and num_created_bars != 0: order_target( context.asset, context.portfolio.positions[context.asset].amount * (1.0 - context.part_cover_ratio), )
def handle_data(context, data): current_time = get_datetime().time() if current_time.hour == 0 and current_time.minute == 0: print('Current date is ' + str(get_datetime().date())) # When model is empty if len(context.model.get_renko_prices()) == 0: context.model = pyrenko.renko() history = data.history(context.asset, 'price', bar_count = context.n_history, frequency = context.tf ) # Get daily absolute returns diffs = history.diff(24).abs() diffs = diffs[~np.isnan(diffs)] # Calculate IQR of daily returns iqr_diffs = np.percentile(diffs, [25, 75]) # Find the optimal brick size opt_bs = opt.fminbound(lambda x: -evaluate_renko(brick = x, history = history, column_name = 'score'), iqr_diffs[0], iqr_diffs[1], disp=0) # Build the model print('REBUILDING RENKO: ' + str(opt_bs)) context.last_brick_size = opt_bs context.model.set_brick_size(brick_size = opt_bs, auto = False) context.model.build_history(prices = history) # Open a position order_target_percent(context.asset, context.leverage * context.model.get_renko_directions()[-1]) # Store some information record( rebuilding_status = 1, brick_size = context.last_brick_size, price = history[-1], renko_price = context.model.get_renko_prices()[-1], num_created_bars = 0, amount = context.portfolio.positions[context.asset].amount ) else: last_price = data.history(context.asset, 'price', bar_count = 1, frequency = '1440T', ) # Just for output and debug prev = context.model.get_renko_prices()[-1] prev_dir = context.model.get_renko_directions()[-1] num_created_bars = context.model.do_next(last_price) if num_created_bars != 0: print('New Renko bars created') print('last price: ' + str(last_price)) print('previous Renko price: ' + str(prev)) print('current Renko price: ' + str(context.model.get_renko_prices()[-1])) print('direction: ' + str(prev_dir)) print('brick size: ' + str(context.model.brick_size)) # Store some information record( rebuilding_status = 0, brick_size = context.last_brick_size, price = last_price, renko_price = context.model.get_renko_prices()[-1], num_created_bars = num_created_bars, amount = context.portfolio.positions[context.asset].amount ) # If the last price moves in the backward direction we should rebuild the model if np.sign(context.portfolio.positions[context.asset].amount * context.model.get_renko_directions()[-1]) == -1: order_target_percent(context.asset, 0.0) context.model = pyrenko.renko() # or we cover the part of the position elif context.part_cover_ratio > 0.0 and num_created_bars != 0: order_target(context.asset, context.portfolio.positions[context.asset].amount * (1.0 - context.part_cover_ratio))