Thinkscript Probabilty Statistics Study- Need help finishing - stock

I'm trying to figure the probability that if a stock moves .05 up at the open, what are the chances it will move .50 up? Running into a few hiccups.
This idea comes from a forex trader, "TheRumpledOne." He calls it the “Buyzone.” Check him out if you don't know of him. Think of it as a probability based opening range.
Once you load up the code you can see the numbers should not be more than "barsago" length.
EDIT: figured it out. Added "crosses above" to the code. Although there must be a better, “cleaner” way? Also added "...var and..." to this portion of code which idk if it's really needed.
def countsells = Sum( var and var1, barsago);
EDIT 2:
This is my current issue.
Something else is still off. The numbers don't seem right. Now they seem low. I would expect some stocks to hit open + .50 more than 70% of the time but this indicator says differently.
# (Probabilty of XYZ FROM THE LAST / PAST XYZ BARS )
# Original/base code By XeoNoX via Usethinkscript.com
# Idea by TheRumpledOne
# By Prison Mike
input barsago = 100;
input buy= .05;
def buyzone= (open + buy);
def var = close crosses above buyzone;
def count = Sum(var, barsago);
AddLabel (yes, "COUNT " + (count) );
def pct= round(count/barsago)*100;
AddLabel (yes, "BuyZone " + (pct) );
input Sell= .50;
def sellzone= (open + sell);
def var1 =close crosses above sellzone;
def countsells = Sum(var and var1, barsago);
AddLabel (yes, "COUNT " + (countsells) );
def pct2=round (countsells/barsago)*100;
AddLabel (yes, "SellZone " + (pct2) );

A modification: it counts how many bars are in the displayed chart (note: TheRumpledOne's algorithm was designed for intraday trading). It places an orange up-arrow on the price chart wherever the open has gone up by 5 cents; and it places a green arrow wherever the price went up 50 cents. It then shows labels with the counts, percents, and the number of bars (highestBar value) that it used for calculating the percent values.
And, I agree: on an AAPL chart, counting approximately 360 15-minute bars, I got a little over 30% that went to 5 cents, and only about 3% that went up 50 cents. That's off the total number of bars; however, when I added the part to calculate the percent of sell count only, I still only got about 8%. Not anywhere near the suggested numbers in TheRumpledOne's Stockfetcher post.
Note: the chart I was using to test included out-of-hours bars. Perhaps if I excluded out-of-hours, the numbers would look better? Considering where I got arrows, I don't think so...
Here's the modified script:
#hint: from SO: https://stackoverflow.com/q/66232117/1107226\nThinkscript Probabilty Statistics Study- Need help finishing
def highestBar = HighestAll(BarNumber());
### buy zone ###
input buy = .05;
def buyzone = (open + buy);
plot hitBuyZone = close >= buyzone;
hitBuyZone.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
hitBuyZone.setDefaultColor( Color.ORANGE );
def count = if hitBuyZone then count[1] + 1 else count[1];
AddLabel (yes, " BUY COUNT: " + count + " ", Color.YELLOW );
def pct = Round(count / highestBar) * 100;
AddLabel (yes, " BuyZone %: " + (pct) + " ", Color.YELLOW );
### sell zone ###
input Sell = .50;
def sellzone = (open + Sell);
plot hitSellZone = close >= sellzone;
hitSellZone.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
hitSellZone.SetDefaultColor( Color.GREEN );
def countsells = if hitSellZone then countsells[1] + 1 else countsells[1];
AddLabel (yes, " SELL COUNT: " + (countsells) + " ", Color.YELLOW );
def pct2 = Round (countsells / highestBar) * 100;
AddLabel (yes, " SellZone %: " + (pct2) + " ", Color.YELLOW );
### percent of buy count that made it to the full buyzone cents ###
def pctOfBuyCount = Round (countsells / count) * 100;
AddLabel (yes, " Buy Count % of Sell Count: " + (pctOfBuyCount) + " ", Color.YELLOW );
### show bar count ###
AddLabel(BarNumber() == highestBar, " Bars Counted for %: " + BarNumber() + " ", Color.ORANGE);

Related

Maximizing with constraint for number of distinct SKU not greater than X

I'm building a optimization tool using Pulp.
It's purpose is to define which SKU to take and which SKU to leave from each warehouse.
I'm having trouble with the following constraint:
"The maximum of different SKUs selected should not exceed 500"
That is to say, that no matter how many units you take, as long as they do not exceed 500 varieties (different SKUs), its all good.
This is what I've got so far
#simplex
df=pd.read_excel(ruta+"actual/202109.xlsx", nrows=20) #leemos la nueva base del mes
# Create variables and model
x = pulp.LpVariable.dicts("x", df.index, lowBound=0)
mod = pulp.LpProblem("Budget", pulp.LpMaximize)
# Objective function
objvals = {idx: (1.0)*(df['costo_unitario'][idx]) for idx in df.index}
mod += sum([x[idx]*objvals[idx] for idx in df.index])
# Lower and upper bounds:
for idx in df.index:
mod += x[idx] <= df['unidades_sobrestock'][idx]
# Budget sum
mod += sum([x[idx] for idx in df.index]) <= max_uni
# Solve model
mod.solve()
# Output solution
for idx in df.index:
print (str(idx) + " " + str(x[idx].value()))
print ('Objective' + " " + str(pulp.value(mod.objective)))
In the same dataframe, I have a column with the SKU of each particular row df['SKU']
I'm imagining that the constraint should look something like:
for idx in df.index:
mod += df['SKU'].count(distinct) <= 500
but that doesn't seem to work.
Thanks!
You will need a binary variable y[i] to indicate if a SKU is used. In math-like notation:
x[i] ≤ maxx[i]*y[i] (y[i] = 0 ==> x[i] = 0)
sum(i, y[i]) ≤ maxy (limit number of different SKUs)
y[i] ∈ {0,1} (binary variable)
where
maxx[i] = upperbound on x[i]
maxy = limit on number of different SKUs

pine script: how do you get the length of a series?

How can I get the number of days for a tickerid? For example, how long is the 'close' series in a simple default script? Or how can I get the first date availble for the current tickerid? If I had that I think that I can compute the number of days available.
This will show the information you requested in a label on the last bar.
If you set the timeframe to Daily, you'll get the number of (trading) days.
//#version=4
study("My Script", overlay=true)
var string firstDate = na
if barstate.isfirst
firstDate := tostring(dayofmonth(time)) + "/" + tostring(month(time)) + "/" + tostring(year(time))
if barstate.islast
label.new(bar_index, high, "First date = " + firstDate + "\nNumber of bars = " + tostring(bar_index+1), yloc=yloc.abovebar)

Formatting decimal as percent showing 100% for 0,98

I'm showing a progress bar in %.
When it almost reaches the final goal (like 0,98 or 0,99) it is showing 100%.
Here is the code.
main.Shapes("shape1").DrawingObject.Text = Format(result, "(0%)")
Where result goes down from 0,00 to 1,00.
Is there a trick to not show 100% if result is not 100% yet?
Just give it as many decimal places as it needs not to round the number.
result = 0.99999
fmtPattern = "0%"
If result >= 0 And result < 1 Then
decPlaces = Len(CStr(result)) - 4
If decPlaces > 0 Then
fmtPattern = "0." & String(decPlaces, "0") & "%"
End If
End If
main.Shapes("shape1").DrawingObject.Text = Format(result, "(" & fmtPattern & ")")

Apparent incorrect value from variable definition?

New to VBA and lousy at it, so please be gentle!
I have the following code which gives the Long type variable "EIa" a value. I was getting a bunch of odd results later down the code so I put in some Debug.Print lines to find my issue and notice that when I Debug.Print the variable EIa, I get 0 but if I Debug.Print EXACTLY the expression that defines EIa, I get the expected value. Code below, any ideas?
'Calculate mA1:
'****************************************************************************************************
EIa = Etimber * ImatA / (Etimber * (ImatA + ImatB + ImatC + ImatD))
Debug.Print "EIa = "; EIa
Debug.Print "EIa = "; Etimber * ImatA / (Etimber * (ImatA + ImatB + ImatC + ImatD))
mA1 = 12 * 0.5 * (q1PSF * EIa) * bMat * LcantiA ^ 2 '12 puts this into lb-in
If LmatSymA = 0 Then
fbA1 = 0
Else
fbA1 = (mA1 * (0.5 * tMatA) / ImatA)
End If
The result of the expression is a kind of fractional, floating point number, but since you defined EIa as Long (a large integer), it gets truncated to zero upon assignment.
See Visual Basic Data Types.

groovy closure instantiate variables

is it possible to create a set of variables from a list of values using a closure??
the reason for asking this is to create some recursive functionality based on a list of (say) two three four or five parts
The code here of course doesn't work but any pointers would be helpful.then
def longthing = 'A for B with C in D on E'
//eg shopping for 30 mins with Fiona in Birmingham on Friday at 15:00
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
i = 0
line = place = with = event = ""
breaks.each{
shortline = longthing.split(breaks[i])
longthing= shortline[0]
//this is the line which obviously will not work
${vary[i]} = shortline[1]
rez[i] = shortline[1]
i++
}
return place + "; " + with + "; " + event
// looking for answer of D; C; B
EDIT>>
Yes I am trying to find a groovier way to clean up this, which i have to do after the each loop
len = rez[3].trim()
if(len.contains("all")){
len = "all"
} else if (len.contains(" ")){
len = len.substring(0, len.indexOf(" ")+2 )
}
len = len.replaceAll(" ", "")
with = rez[2].trim()
place = rez[1].trim()
when = rez[0].trim()
event = shortline[0]
and if I decide to add another item to the list (which I just did) I have to remember which [i] it is to extract it successfully
This is the worker part for then parsing dates/times to then use jChronic to convert natural text into Gregorian Calendar info so I can then set an event in a Google Calendar
How about:
def longthing = 'A for B with C in D on E'
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
rez = []
line = place = with = event = ""
breaks.eachWithIndex{ b, i ->
shortline = longthing.split(b)
longthing = shortline[0]
this[vary[i]] = shortline[1]
rez[i] = shortline[1]
}
return place + "; " + with + "; " + event
when you use a closure with a List and "each", groovy loops over the element in the List, putting the value in the list in the "it" variable. However, since you also want to keep track of the index, there is a groovy eachWithIndex that also passes in the index
http://groovy.codehaus.org/GDK+Extensions+to+Object
so something like
breaks.eachWithIndex {item, index ->
... code here ...
}