Issue with debugging code

Hi,



I am unable to print anything on the blueshift platform. The code freezes after all the backtest is done at 100% but doesnt show up anything after that. Any one else experienced that ?



I am trying to execute a simple strategy based on moviing average but the way it looks no order is getting executed. Sharing the code below



What i want to do is, buy if the price is higher than 3,5 and 13 bar average; sell if the price is lower than 3,5 and 13 bar average and square off at the end of the day.

 


from blueshift_library.technicals.indicators import bollinger_band, ema

from blueshift.finance import commission, slippage
from blueshift.api import(  symbol,
                            order_target_percent,
                            set_commission,
                            set_slippage,
                            get_datetime,
                            schedule_function,
                            date_rules,
                            time_rules
                       )

def initialize(context):
    """
        A function to define things to do at the start of the strategy
    """

    # universe selection
    context.securities = [symbol('RELIANCE'), 
                               symbol('DIVISLAB'),
                               symbol('SUNPHARMA'),
                               symbol('MARUTI'),
                               symbol('AMARAJABAT'),
                               symbol('BPCL'),                               
                               symbol('BAJFINANCE'),
                               symbol('HDFCBANK'),
                               symbol('ASIANPAINT'),
                               symbol('TCS')]

    # define strategy parameters
    context.params = {'indicator_lookback':15,
                      'indicator_freq':'1m',
                      'buy_signal_threshold':0.5,
                      'sell_signal_threshold':-0.5,
                      'SMA_period_short':5,
                      'SMA_period_mid':8,
                      'SMA_period_long':13,
                      'BBands_period':300,
                      'trade_freq':1,
                      'leverage':.7}

    # 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=20.0, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(2.00))
    # if the day closes quare off
    schedule_function(square_off, date_rules.every_day(), time_rules.market_close(hours=0,minutes = 5))

    
def handle_data(context, data):
    """
        A function to define things to do at every bar
    """
    # Compute 5,8.13 bar moving average
    # if the current price higher than 5,8,13 then buy, if it goes lower than 5, sell
    print(get_datetime())
    run_strategy(context, data)


def run_strategy(context, data):
    """
        A function to define core strategy steps
    """
    generate_signals(context, data)
    generate_target_position(context, data)
    rebalance(context, data)

def generate_signals(context, data):
    """
        A function to define define the signal generation
    """
    try:
        price_data = data.history(context.securities, 'close',
            context.params['indicator_lookback'],
            context.params['indicator_freq'])
    except:
        return

    for security in context.securities:
        px = price_data.loc[:,security].values
        context.signals[security] = signal_function(px, context.params)


def generate_target_position(context, data):
    """
        A function to define target portfolio
    """
    num_secs = len(context.securities)
    weight = round(1.0/num_secs,2)*context.params['leverage']

    for security in context.securities:
       
        if context.signals[security] > context.params['buy_signal_threshold']:
            context.target_position[security] = weight

        elif context.signals[security] < context.params['sell_signal_threshold']:
            context.target_position[security] = -weight




def signal_function(px, params):
    """
        The main trading logic goes here, called by generate_signals above
    """
    ind5 = ema(px, params['SMA_period_short'])
    ind8 = ema(px, params['SMA_period_mid'])    
    ind13 = ema(px, params['SMA_period_long'])
    last_px = px[-1]

    
    if (last_px>=ind5) &  (last_px>=ind8) &  (last_px>=ind13):
        return 1
    elif (last_px<ind5) &  (last_px<=ind8) &  (last_px<=ind13):
        return -1
    else:
        return 0


def rebalance(context,data):
    """
        A function to rebalance - all execution logic goes here
    """
    for security in context.securities:
        order_target_percent(security, context.target_position[security])



def square_off(context,data):
    for sec in context.securities:
        order_target_percent(sec,0)








Hi Abhishek,



It looks like the print statement is flooding the logs and hence causing the strategy to freeze. Instead of printing the entire thing in the handle data function, you can try using the print statement selectively. Also there can be multiple reasons for orders not getting placed. You can initially try working on a single stock over a daily timeframe to debug the issue and then scale it for a smaller timeframe and multiple stocks. If you still face any issues with this, please drop a mail at blueshift support.



Hope this helps!



Thanks,

Akshay