IPO stocks

I have a situation where I'm trying to average a stock over 252 days but the stocks that have not traded for 252 days are returning isNaN. Anyone have any ideas on how to structure the code to return the appropriate average in that scenerio?

i've been experimenting with variations of this, but not getting it to work as i think it should. maybe someone can see what i am missing.

i can find the smallest bar on the chart, where an average of x length will produce a valid number.
for each bar before that bar, i wanted to add up the previous values, then divide by the quantity of bars, to get an average.

test on WRBY , 30D 30min chart

in this version, in the 2nd half of this section
if (bn >= cnt2chg5) then {
doesn't seem to ever trigger , so no line at 48. if this could work, then i could change it to add up the values to calc an average.


nasdaq ipo calendar
https://www.nasdaq.com/market-activity/ipos

Code:
# lessthan252_00c2

# test on WRBY ,  30D  30min chart

# nasdaq ipo calendar
# https://www.nasdaq.com/market-activity/ipos

# WRBY 9/29/21
# BROS 9/15/21
# SQL 8/27/21
# OBT 8/5/21
# TNYA 7/30/21
# DOLE 7/30/21
# HEPS 7/1/21

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

addlabel(1, "252avglen" , color.white);

def na = double.nan;
def bn = barnumber();
def lastbarbn = highestall( if( !isnan(close), bn, 0));
def lastbar = if lastbarbn == bn then 1 else 0;


input avg_len = 252;
addlabel(1, "Len: " + avg_len , color.green);

#input maxnum = 1999;
input maxnum = 501;
# if bar1, then check if there are enough valid bars before chart bar #1, for an average
def beforecnt;
if bn == 1 then {
#  beforecnt = fold f = 1 to (avg_len + 1)
  beforecnt = fold f = 1 to maxnum
  with g
  do g + (if !isnan( getvalue( close, f)) then 1 else 0);
} else {
  beforecnt = beforecnt[1];
};

addlabel(1, "at least " + beforecnt + " data bars before the chart", color.yellow);


# ========================================


# do a average on every bar,  average(close, end)
#  if an err then 0 , else 1
#   will start being 1 when there are enough prev data bars
def cnt2 = if !isnan(average(close, (avg_len+1))) then 1 else 0;

# find 1st bar that the average has a valid #
def big = 99999;
def lx = lowestall(if cnt2 then bn else big);
def chgbn2 = lx;

input test6 = no;
addchartbubble(test6, low, bn + "\n" + lx, (if lx == bn then color.yellow else color.gray), no);

def cnt2chg5 = if (bn == 1 and cnt2) then bn
 else if bn == 1 then 0
 else if (cnt2[1] == 0 and cnt2 == 1) then bn
 else cnt2chg5[1];

def chartbars = if bn == 1 then 0 else if chgbn2 > 0 then chgbn2 else lastbarbn;

addlabel(1, "after bar # " + chartbars + ", there will be enough previous bars for an avg with len " + avg_len , (if beforecnt >= avg_len then color.gray else color.yellow));

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

def t = if ( chartbars <> 1 and chartbars <> lastbar and chartbars == bn) then 1 else 0;
addverticalline(t, "BAR #  " + bn + ". bars past this will have " + avg_len + " valid data bars", color.yellow);

input test2_tz_3bubbles = no;
addchartbubble(test2_tz_3bubbles and t, low, avg_len + "\n" + getvalue(close, avg_len), color.cyan, no);

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

def a1 = average(close, avg_len);
def a1b = round(a1,2);
plot a1z = a1b;
a1z.setdefaultcolor(color.cyan);
#a1z.SetStyle(Curve.MEDIUM_DASH);

#plot c = a1b +0.5;
#a1z.setdefaultcolor(color.white);
#a1z.SetStyle(Curve.MEDIUM_DASH);


input avg1_type =  AverageType.simple;
def ma1 = MovingAverage(avg1_type, close, avg_len);
def ma1b = round(ma1,2);

plot ma1z = ma1b;
ma1z.setdefaultcolor(color.magenta);
#ma1z.SetStyle(Curve.MEDIUM_DASH);

def diff1 = a1 - ma1;


input test3_ma = no;
def vert2 = 0.98;
addchartbubble(test3_ma, low*vert2, bn + "\n" + avg_len + "\nA " + a1b + "\nMA " + ma1b + "\nD " + diff1, color.cyan, no);

# ??? avg() line starts 11 bars after the min bar for avg( x , end)

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

#  test stuff
input test4_bn = no;
addchartbubble( test4_bn, high, bn, color.yellow, yes);

def endnum = chgbn2;

def total2;
def pastav;
# if (endnum > 1 and bn <= endnum) then {
# if (bn > 1 and bn <= endnum) then {
# if ( bn <= endnum) then {
#cnt2chg5
if (bn >= cnt2chg5) then {
# if ( bn <= 100) then {
# if (bn > 1 and bn <= 66) then {
  total2 = 0;
#  total2 = fold q = 0 to bn+1
#  with r
##  do r + getvalue(close, q);
#  do r + 53;
#  pastav = total2/bn;
 # pastav = ( getvalue(close, 0) + getvalue(close, 1))/2;
  pastav = 50;
} else {
  total2 = 0;
  pastav = 48;
}


# (bn > 1 and bn <= endnum)
addchartbubble(test6, high, "IF " + (bn <= endnum) + "\n" + bn + "\nEN " + endnum + "\nP " + pastav,
(if bn <= lx then color.yellow else color.gray), yes);

plot p3 = pastav;
p3.setdefaultcolor(color.white);
p3.SetStyle(Curve.MEDIUM_DASH);

#

uZK1XXt.jpg

hal_252
 
Last edited:
Handling IPOs and other instruments with a gap in data
Let’s say I have a simple study to plot two moving averages. My problem is that I cannot get the 21-day SMA to plot unless there are at least 50 days of history:

Code:
plot SMA21 = Average(close, 21);
plot SMA50 = Average(close, 50);

As far as I can tell, when TOS doesn't have enough data to compute an expression for a bar (e.g. close[50], Average(close, 50), etc.), it assigns N/A to ALL expressions for that bar. Is that true?

How do I work around this behavior? Any help will be highly appreciated. I don't want to separate this into two studies as I will eventually have more complex studies that cannot be split. I have tried using IsNan() but that hasn't worked either. For example, the following doesn’t work either:

Code:
plot SMA21 = Average(close, 21);
plot SMA50 = if IsNan(close[50]) then SMA21 else Average(close, 50);  # Doesn't work as expected

Thanks.
 
Last edited by a moderator:
There is no exclamation point in the upper left corner. I only have one study that plots the two MAs (21 and 50).

Code:
plot SMA21 = Average(close, 21);
plot SMA50 = Average(close, 50);

Thanks for the help.

TyJTrSZ.png
 
There is no exclamation point in the upper left corner. I only have one study that plots the two MAs (21 and 50).

Code:
plot SMA21 = Average(close, 21);
plot SMA50 = Average(close, 50);

Thanks for the help.

TyJTrSZ.png
CFLT had ipo in june.
i'm not sure why both averages start at the same time, maybe it is a TOS quirk. i think i have seen this , but didn't think much about it back then.
now both averages start at bar 50. what happens if you remove the 50ma, or change it to 15?
 
CFLT had ipo in june.
i'm not sure why both averages start at the same time, maybe it is a TOS quirk. i think i have seen this , but didn't think much about it back then.
now both averages start at bar 50. what happens if you remove the 50ma, or change it to 15?
It appears that only 1 averagetype, exponential, seems to work in this situation as it uses 'prefetch' to access historical data. Search 'prefetch' in education center for more information.
 
I believe this is because you have both moving averages in the same study. When I split them out into separate studies, they plot independently. When they are on one study though, the study will result in N/A until both are plotting.

So to fix it, just split them into different studies.
 
I believe this is because you have both moving averages in the same study. When I split them out into separate studies, they plot independently. When they are on one study though, the study will result in N/A until both are plotting.

So to fix it, just split them into different studies.
Yes, thanks. As I also noted this in my original post, that is a workaround for some simpler scenarios. Unfortunately I have some complex studies that are not easily splittable as I'm making decisions based on the two averages.
 
It appears that only 1 averagetype, exponential, seems to work in this situation as it uses 'prefetch' to access historical data. Search 'prefetch' in education center for more information.
Yes, the exponential average does work. Looks like the limitation in my original example is by design. I was able to find the section in the reference that describes this. I should really RTFM lol.

https://tlc.thinkorswim.com/center/...dvanced/Chapter-12---Past-Offset-and-Prefetch

"In thinkScript®, the highest past offset overrides lower offsets in the same study, which means that all expressions in a single study will have the same (highest) past offset"

Thank you!!
 
I am not aware of any method for determining this directly with thinkScript, there is no function like "GetDateIPO()" or anything like that. As for determining it though other means, I don't see how one could differentiate between an IPO and simply exceeding the selected range of the chart. There is no guarantee that an IPO falls within the maximum available data, and to go father back you need to use monthly if not yearly charts. You can sort of almost do it, but the results would be extremely wonky at best.
 
Got it. I am trying to filter for stocks which are less than 3 years old. I was thinking to use IPODate to solve it. Please let me know if there is an alternative to my problem. Thanks for your response.
 
Hi all,

I am trying to implement something similar to OP's question in a scanner (ThinkOrSwim > Scan > StockHacker) based on this other post: https://usethinkscript.com/threads/ipo-date-or-first-trading-date.6161/

Desired Functionality: Find stocks that are more than 3 years old.

Current Implementation:
Within a Study > Custom Study > thinkScript Editor:
Code:
def daysOld = 3 * 365;
Plot oldEnough = !isNaN(volume[daysOld]);

Problem: When I include the above filter on "All Stocks", I get no results. If I delete just that filter, I get thousands of results.

Anyone know why this code isn't working as intended?
 
Hi,

Is there a way to find the lowest and highest daily values of any stock since the beginning of its trading period (IPO)?

I tried using a the Lowest(Low, standard input lookback period) but this doesn't work and returns N/A.

Appreciate any help.
 
scan stocks have less than 252 Bars

HI Guys,

Is it possible to scan the stocks are within 1 year of IPO?

My thoughts are count bars on daily timeframe < 252

Please help with the script.
Thanks


how to count how many bars the stock has in total (daily timeframe)?
 
Last edited by a moderator:
Best I could come up with since daily scans apparently always scan back one year. If someone knows how to make it scan more than one year I could make it more accurate. However, this should pick up a majority of what you want, might leave a few out that are on the border of one year. It goes by total days, to put a buffer of a month in to hopefully weed out some that aren't IPO's.

Scan on DaysFromDate("fromDate" = First(GetYYYYMMDD())) is less than 330

and to get the count and put it as a label, here you go: (will show the count for your chart length, not its entire history, so a 1 month chart will calculate around 25 bars, etc.)

plot daysfromDate = DaysFromDate(first(GetYYYYMMDD()));
daysfromDate.hide();

addLabel(yes,"Count: "+daysfromDate,color.white);
 
I want to create a study to use in the stock scanner that shows stocks trading for less than 200 days (they don't have a 200 moving average yet).
Code:
plot Data = compoundvalue(1, if IsNan(close[200]) then 1 else 0,close);
My attempt to code this shows stocks that have just started trading for 200 days (DOCS for instance), but that's not what I'm looking for. Any help would be greatly appreciated!
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
412 Online
Create Post

Similar threads

Similar threads

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