def pair_trading_strategy(context,data):
    """
        function to define Pairs Trading strategy logic.
    """

    try:
        # Get the historic data for the stocks pair
        prices = data.history(  assets = [context.x, context.y],
                                fields = "price",
                                bar_count = context.lookback,
                                frequency = "1d"
                             )
    except:
        return

    # Take log of the prices
    prices = np.log(prices)

    # Store the price data in y and x
    y = prices[context.y]
    x = prices[context.x]

    # Calculate the hedge ratio and z_score
    _, context.hedge_ratio, resids = hedge_ratio(y, x)
    context.z_score = z_score(resids, lookback=context.z_window)
    # Compute the trading signal
    context.signal = trading_signal(context, data)

    # Place the order to trade the pair
    place_order(context)
def pair_trading_strategy(context, data):
    """
        function to define Pairs Trading strategy logic.
    """
    if context.trading_hours == False:
        return

    try:
        # Get the historic data for the stocks pair
        prices = data.history(assets=[context.x, context.y],
                              fields="close",
                              nbars=context.lookback,
                              frequency="1m")
    except:
        return

    # drop nan values
    prices = prices.dropna()
    if len(prices) < 5:
        print(f'too few data points for z-score:{len(prices)}.')
        return

    # Take log of the prices
    prices = np.log(prices)

    # Store the price data in y and x
    y = prices[context.y]
    x = prices[context.x]

    # Calculate the hedge ratio and z_score
    _, context.hedge_ratio, resids = hedge_ratio(y, x)
    context.z_score = z_score(resids, lookback=context.z_window)
    # Compute the trading signal
    context.signal = trading_signal(context, data)

    # Place the order to trade the pair
    place_order(context)