Search code examples
pine-scriptpine-script-v5pine-script-v4

Simple Pine-script code to chart a pair price of two equities (code included)


So, I would like to monitor some pairs I trade on trading view and am completely new to coding and pine-script . I am actually learning python at this time but ventured off the beaten path to figure out this simple bit of pine script code .

//@version=4
study("My Script")

// this is my pair
//objective is to plot a pair price of stock 1(bns_1) and stock 2(yelp_2) 
//pair price == stock 1 - (stock 2 * hedge ratio)

bns_1 = security("NYSE:BNS", "1", close)
yelp_1 = security("NYSE:YELP", "1", close)


hedge_ratio = bns_1/yelp_1

pair_price = bns_1-(yelp_1*hedge_ratio)

plot(pair_price)

So , It seems like the problem here is when I try to get pine script to use my "hedge_ratio" variable in the plot() parameter's. I have tried all sorts of ways to restructure the code to do the same thing but ask it in slightly differnt ways to no success.

using that code I can do the following succesfully :

plot(bns_1-yelp_2)
plot(bns_1*yelp_2)  

....or I even manually entered the hedge_ratio as a float and it charted a perfect pair price(below) ...

plot(bns_1-yelp_2*1.88) 

SO~ I am pretty sure I am doing something wrong when it comes to the hedge_ratio variable.

Any takers ? Your help would be VERY appreciated :) Thanks in advance.

Here is todays BNS and YELP Values plugged in to show that the formula seems to work with a link that shows what the pair price should look like when I chart it in pine script that just has a manual hedge ratio inserted to make it work .

//Todays BNS and yelp value below: 

bns_1 = $44.40 
Yelp_1= $23.35

formula to plug in stock value's below 

pair_price = bns_1-(yelp_1*bns_1/yelp_1)
pair_price = 44.4-(23.35*44.4/23.35)
pair_price = 44.4-(23.35*1.9)
pair_price = 44.4-44.36
pair_price = 0.035

https://www.tradingview.com/chart/BNS/ddcMA52L-Good-statistical-arbitrage-to-justify-long-position-in-YELP/


Solution

  • Ok, there is a logic problem, not with the code.

    Lets take a closer look:

    hedge_ratio = bns_1/yelp_1
    pair_price = bns_1-(yelp_1*hedge_ratio)
    

    substitute hedge_ratio in the pair_price formula:

    pair_price = bns_1 - (yelp_1 * bns_1 / yelp_1) = bns_1 - bns_1 = 0
    

    The result of the pair_price variable will always be 0.