Trying to do a comparison from a purchase date

utgamer

New member
So I'm trying out a strategy where I compare the performance of a stock vs SPX as a percentage gained, enter/exit when they cross. I can manually setup the time frame for each stock individually and use the comparison tool to just look at it. But I would like to create a code where I have clouds comparing the two to see if they're converging or diverging. I'd also like to be able to setup alerts when the inflection points change as a warning to look at everything and possibly exit my swing play and alerts for when the two graphs cross. I'd like them to be candlesticks, but would settle for line graphs.

So here's an example:
I entered DG 7/30/2021 and using the compare to SPX I show it's up 10.74% and SPX is down 8.9% since 7/30.

D1PtCLV.png


What I want to do is be able to input the start date and have it calculate from there. Has anyone been able to replicate the comparison feature?

I'm not seeing how to join discord? Is that a VIP only thing?
 
Last edited:
Solution
Tried somemore today and came up with a little bit of a start... I have some more specific questions.
Here is my code thusfar:

Code:
declare lower;

input comparisonStyle = {"CANDLE", "BAR", default "LINE"};
input secondarySecurity = "SPX";
input startdate = 20210101;

def CloseonStartDate = getvalue(close, startdate);
def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);

plot Bands = close(GetSymbol()) / CloseonStartDate  - close(secondarySecurity) / SecondaryCloseonStartDate;

First question is, can you set up the time frame plotted using script?

Second question, why am I not seeing anything on the graph?

Third question is: is there a way to see what values are returned so I can trouble-shoot...
Tried somemore today and came up with a little bit of a start... I have some more specific questions.
Here is my code thusfar:

Code:
declare lower;

input comparisonStyle = {"CANDLE", "BAR", default "LINE"};
input secondarySecurity = "SPX";
input startdate = 20210101;

def CloseonStartDate = getvalue(close, startdate);
def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);

plot Bands = close(GetSymbol()) / CloseonStartDate  - close(secondarySecurity) / SecondaryCloseonStartDate;

First question is, can you set up the time frame plotted using script?

Second question, why am I not seeing anything on the graph?

Third question is: is there a way to see what values are returned so I can trouble-shoot easier?

Thanks for your help in advance.
 
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Tried somemore today and came up with a little bit of a start... I have some more specific questions.
Here is my code thusfar:

Code:
declare lower;

input comparisonStyle = {"CANDLE", "BAR", default "LINE"};
input secondarySecurity = "SPX";
input startdate = 20210101;

def CloseonStartDate = getvalue(close, startdate);
def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);

plot Bands = close(GetSymbol()) / CloseonStartDate  - close(secondarySecurity) / SecondaryCloseonStartDate;

First question is, can you set up the time frame plotted using script?

Second question, why am I not seeing anything on the graph?

Third question is: is there a way to see what values are returned so I can trouble-shoot easier?

Thanks for your help in advance.


debugging
i added a bubble to your study, to display some variables.
\n , is used in a bubble, to start a new line of characters.
the \n can be within quotes of text or on its own like this , + "\n" +

all 3 variables are NA. so something in your formulas is wrong.


Code:
declare lower;

input comparisonStyle = {"CANDLE", "BAR", default "LINE"};
input secondarySecurity = "SPX";
input startdate = 20210101;

def CloseonStartDate = getvalue(close, startdate);
def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);

plot Bands = close(GetSymbol()) / CloseonStartDate  - close(secondarySecurity) / SecondaryCloseonStartDate;

#---------------------------

# have to have at least 1 line/shpare plotted on a chart before bubbles will appear
plot z = 0;

input test1 = yes;
addchartbubble(
test1, 0,
  CloseonStartDate + " 1\n" +
  SecondaryCloseonStartDate + " 2\n" +
  Bands + " B"
, color.yellow, yes);
#

create bubbles to display variable values
all 3 variables are NA , so nothing is plotted
lMFmCce.jpg



=============================================


when things don't work, copy a code line, disable it, then make it simpler.
i always copy lines, so i have the original code line to go back to if one variation doesn't work.

example,
start with this line,
copy it,
put a # in front of it to disable it.
then make it simpler, replace a variable with a constant. does it work ?

#def CloseonStartDate = getvalue(close, startdate);
def CloseonStartDate = getvalue(close, 1);

now the bubble display a number for CloseonStartDat.
so the original formula didn't work , why?
DSld7lH.jpg



look up getvalue()
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/GetValue
Returns the value of data with the specified dynamic offset.

this function expects an offset , not a date.
an offset is a number that means, to look back (or forward) x number of bars and read a variable.

by using this as a parameter in getvalue()
startdate = 20210101;
this
getvalue( close , startdate )
is trying to read a value of close, 20 million bars back in the past.
that data doesn't exist, so it is equal to NA.

===============================


use GetYYYYMMDD() to compare each bar date to the desired date.
if they match then read the close from a bar.
if the date is not a trading day, then no match and no price will be found.
20210101 is a friday, but it is a holiday, so no trading, no price data.
20210104 is a trading day.
if the date is not visible on the chart, then no match and no price will be found.

change this,
#def CloseonStartDate = getvalue(close, startdate);

to this,
def CloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close else CloseonStartDate[1];

i use if bn == 1 then na to initialize the variable, to NA, so it won't plot.
some people use compoundvalue(), i like to do it this way.

the last part,
else CloseonStartDate[1];
will keep the previous value, so after the date, the close price will exist in the variable.

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYYYYMMDD


set chart to day 3 year
change date to 1/4/2021 , a valid trading day.
comparing a date number to GetYYYYMMDD() has found a price
taijNVb.jpg


=====================


change the secondary price formula

from this,
#def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);

to this,
def SecondaryCloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close(symbol = secondarySecurity) else SecondaryCloseonStartDate[1];

now , after the desired date, we have a 3 numbers in the bubble and a line drawn on the lower chart.

change the 5th parameter for the bubble,
from ,yes) to , no),
so it will plot below the price level of 0, so it won't cover up the line.


Code:
declare lower;

def bn = barnumber();
def na = double.nan;

input comparisonStyle = {"CANDLE", "BAR", default "LINE"};
input secondarySecurity = "SPX";
#input startdate = 20210101;
input startdate = 20210104;

#def CloseonStartDate = getvalue(close, startdate);
#def CloseonStartDate = getvalue(close, 1);
def CloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close else CloseonStartDate[1];


#def SecondaryCloseonStartDate = getvalue(close(symbol = secondarySecurity), startdate);
def SecondaryCloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close(symbol = secondarySecurity) else SecondaryCloseonStartDate[1];


plot Bands = close(GetSymbol()) / CloseonStartDate  - close(secondarySecurity) / SecondaryCloseonStartDate;


#---------------------------

# have to have at least 1 line/shpare plotted on a chart before bubbles will appear
plot z = 0;

input test1 = yes;
addchartbubble(
test1, 0,
  CloseonStartDate + " 1\n" +
  SecondaryCloseonStartDate + " 2\n" +
  Bands + " B"
, color.yellow, no);
#

1AGAGw4.jpg



============================

turn off the bubble by changing the code, so the default for test1 is no instead of yes

stock is EMR
chart is day 3 year
r4uXyYC.jpg

hal_debug
 
Last edited:
Solution
hal_debug
Very much appreciated!!! I do code in SQL, have some C, C++, VB experience from college courses at UT Austin. But I was not seeing anyway to output results. Bubbles are now added to my repertoire!
Rereading your stuff, everything makes sense to me except the double.nan part... what is the nan? I know double is a data type, what's the nan?
 
Very much appreciated!!! I do code in SQL, have some C, C++, VB experience from college courses at UT Austin. But I was not seeing anyway to output results. Bubbles are now added to my repertoire!
Rereading your stuff, everything makes sense to me except the double.nan part... what is the nan? I know double is a data type, what's the nan?

i use double.nan for a value, when i don't want to plot anything.
if i used 0 as a default , then plotted the variable, there would be a line at 0 for awhile, then up to the desired value.

---------------------
i usually use 0 in the variable.
(sometimes assigning na in a formula can have unwanted results, causing it to cascade to all bars.)

then in the plot formula, i check for 0, and set the plot to na.
def abc = if something then close else 0;
plot x = if abc == 0 then na else abc;

https://tlc.thinkorswim.com/center/reference/thinkScript/Constants/Double
 
Very much appreciated!!! I do code in SQL, have some C, C++, VB experience from college courses at UT Austin. But I was not seeing anyway to output results. Bubbles are now added to my repertoire!
Rereading your stuff, everything makes sense to me except the double.nan part... what is the nan? I know double is a data type, what's the nan?

side note,
addlabel() can be used also display values. but the default configuration will display values from the last bar on the chart
 
debugging
i added a bubble to your study, to display some variables.
\n , is used in a bubble, to start a new line of characters.
the \n can be within quotes of text or on its own like this , + "\n" +

when things don't work, copy a code line, disable it, then make it simpler.
i always copy lines, so i have the original code line to go back to if one variation doesn't work.

I like that we debug the same way. I use a lot of comments and select statements (SQL) equivalent of cout in c++ to test things... I just had no clue of how to do that here looking through that learning center you linked. Keep my TI 84 nearby :)
Going to input that code and see what I can do with that.
 
Some interesting tidbits of notes that maybe you can expand on...
So when I put in the code it wasn't working for me... so I did some trouble shooting and did it using your example and it worked after I took off all my other studies....

So then I figured out that my comparison study was putting the graph in % price mode, so it wasn't working. I like the % price mode comparing to the graph of SPX for this purpose. Wondering if I can get the code to work in that mode. Hmm now it's working in % price mode, nice :)
Oh I set up the start date to 1/4/2021 and it didn't work... then to get it to work I put start date to 12/31/2020... interesting. I'm guessing that has to do with the
def CloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close else CloseonStartDate[1];

and secondarysecurity equivalent. Since the closeonstartdate if offsetting by 1?

So I got it working in regular mode, but I can't setup an alert using the study. So now that's going to lead me to some research on if it's possible to set alerts in studies or the lower/volume sections or if alerts are only available in the price. Imma do the research first, but if I can't find it, I'll ask again.------------------Found some scripts with alerts! Ignore this. I'll play with this tomorrow.

Ok question for ya... is there a way to watch from a certain day to current day and have it update each day? All I'm seeing is custom time frame from/to... but the to tomorrow will be today's date and I'd like it to update to tomorrows date tomorrow.

Anyways thanks for the start and very thorough explanation. I learned a bunch from this. Highly considering the $200 sub, but want to see if I can find out more info on it. Maybe later this week.
 
Last edited:
Some interesting tidbits of notes that maybe you can expand on...
So when I put in the code it wasn't working for me... so I did some trouble shooting and did it using your example and it worked after I took off all my other studies....

So then I figured out that my comparison study was putting the graph in % price mode, so it wasn't working. I like the % price mode comparing to the graph of SPX for this purpose. Wondering if I can get the code to work in that mode. Hmm now it's working in % price mode, nice :)
Oh I set up the start date to 1/4/2021 and it didn't work... then to get it to work I put start date to 12/31/2020... interesting. I'm guessing that has to do with the
def CloseonStartDate = if bn == 1 then na else if GetYYYYMMDD() == startdate then close else CloseonStartDate[1];

and secondarysecurity equivalent. Since the closeonstartdate if offsetting by 1?

So I got it working in regular mode, but I can't setup an alert using the study. So now that's going to lead me to some research on if it's possible to set alerts in studies or the lower/volume sections or if alerts are only available in the price. Imma do the research first, but if I can't find it, I'll ask again.------------------Found some scripts with alerts! Ignore this. I'll play with this tomorrow.

Ok question for ya... is there a way to watch from a certain day to current day and have it update each day? All I'm seeing is custom time frame from/to... but the to tomorrow will be today's date and I'd like it to update to tomorrows date tomorrow.

Anyways thanks for the start and very thorough explanation. I learned a bunch from this. Highly considering the $200 sub, but want to see if I can find out more info on it. Maybe later this week.

this will set x to be true, when the date of a bar is >= to some date.

this will test for bars with valid price data, (up to the last bar on the chart)
!isnan(close).

add x to some formula,
and x,
to enable some action when the current bars are in the desired date range.

Code:
# true after sept 1
input date1 = 20220901;
def x = if GetYYYYMMDD() >= date1 and !isnan(close) then 1 else 0;


-----------------------

alt...
check if a bar is on the current day,

def today = if GetDay() == GetLastDay() then 1 else 0;
 
Hey there,
Is there any way to work this into a scan? Like it crossed over the spy comparison within 5 bars?

not sure,
what is 'it' ?

scans need 1 plot formula, that is 0 or 1. all other plots in a study would need to be changed to def.

there is a 'within' code word that could be used,
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/within



define a condition,
def c = if stka crosses above stkb then 1 else 0;
def barz = 5;
plot z = c within barz bars;


or check it another way,

def c = if stka crosses above stkb then 1 else 0;
def barz = 5;
# has c been true at least once, in the past 5 bars?
plot t = sum(c, barz) > 0;
 
Thank you kindly for your prompt response! The within is definitely what I'm after. I got a scan to work comparing to ATR levels that i'm using for swing trades and can use the within code to scan for crossovers there too! I'm having too much fun coming up with these things :)
 
I do have a question... the buttons for like selecting in the drop downs and the cells to type the numbers in, is that coded by ToS for the available scans already? If so, is that possible for us to code in as well, or are we stuck with editing the script and changing to what we'd like?

XLCmlFt.png
 
Last edited:
OK so i'm trying to work the comparison into a scan and this is the script that I have:
Code:
input secondarySecurity = "SPX";
input AboveBelowBetween = "Above";
input betweenlow = 0.05;
input betweenhigh = 0.15;

def Result;
if AboveBelowBetween == "Above" {
Result = (close(GetSymbol())/close(GetSymbol())[61]) >= (close(secondarySecurity)/ close(secondarySecurity)[61]); }
else {Result = 0;}
#if AboveBelowBetween == "Below" {
#Result = (close(GetSymbol())/CloseonStartDate) <= #(close(secondarySecurity)/secondaryCloseonStartDate);}
#else if AboveBelowBetween == "Between" {
#Result = (close(GetSymbol()) / CloseonStartDate)  - (close(secondarySecurity) / SecondaryCloseonStartDate) > betweenlow and (close(GetSymbol()) / CloseonStartDate)  - (close(secondarySecurity) / SecondaryCloseonStartDate) < betweenhigh;} else {Result = 0;}

plot scan = Result;

I'm currently trouble shooting (hence all of the # and trying different ways of getting this to work) I use to have the close on start date and secondary close on start date as a pre-defined thing then was like eh... just put it into the if statement to shorten it up... still didn't work... so for the most part it works... but then I get some cases like this screenshot:

xl3pSDD.png


where SPX (blue) is clearly above the graph of ASTC... Looking at the custom comparison 3months indicator at the bottom it's a - number indicating it's below. So why is it showing above?
I'm also not sure how to troubleshoot scans as it only returns true/false values.
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
308 Online
Create Post

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top