'NA' does not work with and 'AND' logical pine script - variables

My script does not working as expected when I put a 'NA' variable in 'AND' logical.
// ON/OFF Indicator
// Buy Condition
MACDonoffbuy = useMACD ? macdLine > 0 : na
ADXonfoffbuy = useADX ? ADX > thradx : na
RSIonoffbuy = useRSI ? rsi >= overbought : na
Williamonoffbuy = useWilliam ? percentR >= -25 : na
Squeezeronoffbuy = useSqueezer ? sqzOff : na
// Sell Condition
MACDonoffsell = useMACD ? macdLine < 0 : na
ADXonfoffsell = useADX ? ADX > thradx : na
RSIonoffsell = useRSI ? rsi <= overbought : na
Williamonoffsell = useWilliam ? percentR <= -25 : na
Squeezeronoffsell = useSqueezer ? sqzOff : na
// Final Combination
buy = MACDonoffbuy and ADXonfoffbuy and RSIonoffbuy and Williamonoffbuy and Squeezeronoffbuy
sell = MACDonoffsell and ADXonfoffsell and RSIonoffsell and Williamonoffsell and Squeezeronoffsell
My expectation is if one of expression is 'NA' on that 'AND' logical, the other expression is still calculated.

Related

I want to find the highest price since entry in pine script?

I want to find the highest price and exit when current price is lower than highest price. The code to find the highest price is copied from here. how can I make a simpler code that finds highest price since entry? I also want to close the deal if current price is lower than a specific price. Please help me.
// SETTING //
length1=input(1)
length3=input(3)
length7=input(7)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=(low>upper and BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit,10)
// - INPUTS
ShowPivots = input(true, title="Show Pivot Points")
ShowHHLL = input(true, title="Show HH,LL,LH,HL markers on Pivots Points")
left = input(5, minval=1, title="Pivot Length Left Hand Side")
right = input(5, minval=1, title="Pivot Length Right Hand Side")
ShowSRLevels = input(true, title="Show S/R Level Extensions")
maxLvlLen = input(0, minval=0, title="Maximum S/R Level Extension Length (0 = Max)")
ShowChannel = input(false, title="Show Levels as a Fractal Chaos Channel")
//
ShowFB = input(true, title="Show Fractal Break Alert Arrows")
// Determine pivots
pvtLenL = left
pvtLenR = right
// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
pvthi = pvthi_
pvtlo = pvtlo_
// ||-----------------------------------------------------------------------------------------------------||
// ||--- Higher Highs, Lower Highs, Higher Lows, Lower Lows -------------------------------------------||
valuewhen_1 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_2 = valuewhen(pvthi, high[pvtLenR], 0)
higherhigh = na(pvthi) ? na : valuewhen_1 < valuewhen_2 ? pvthi : na
valuewhen_3 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_4 = valuewhen(pvthi, high[pvtLenR], 0)
lowerhigh = na(pvthi) ? na : valuewhen_3 > valuewhen_4 ? pvthi : na
valuewhen_5 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_6 = valuewhen(pvtlo, low[pvtLenR ], 0)
higherlow = na(pvtlo) ? na : valuewhen_5 < valuewhen_6 ? pvtlo : na
valuewhen_7 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_8 = valuewhen(pvtlo, low[pvtLenR ], 0)
lowerlow = na(pvtlo) ? na : valuewhen_7 > valuewhen_8 ? pvtlo : na
// If selected Display the HH/LL above/below candle.
plotshape(ShowHHLL ? higherhigh : na, title='HH', style=shape.triangledown, location=location.abovebar, color=color.new(color.green,50), text="HH", offset=-pvtLenR)
plotshape(ShowHHLL ? higherlow : na, title='HL', style=shape.triangleup, location=location.belowbar, color=color.new(color.green,50), text="HL", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerhigh : na, title='LH', style=shape.triangledown, location=location.abovebar, color=color.new(color.red,50), text="LH", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerlow : na, title='LL', style=shape.triangleup, location=location.belowbar, color=color.new(color.red,50), text="LL", offset=-pvtLenR)
plot(ShowPivots and not ShowHHLL ? pvthi : na, title='High Pivot', style=plot.style_circles, join=false, color=color.green, offset=-pvtLenR, linewidth=3)
plot(ShowPivots and not ShowHHLL ? pvtlo : na, title='Low Pivot', style=plot.style_circles, join=false, color=color.red, offset=-pvtLenR, linewidth=3)
//Count How many candles for current Pivot Level, If new reset.
counthi = 0
countlo = 0
counthi := na(pvthi) ? nz(counthi[1]) + 1 : 0
countlo := na(pvtlo) ? nz(countlo[1]) + 1 : 0
pvthis = 0.0
pvtlos = 0.0
pvthis := na(pvthi) ? pvthis[1] : high[pvtLenR]
pvtlos := na(pvtlo) ? pvtlos[1] : low[pvtLenR]
hipc = pvthis != pvthis[1] ? na : color.new(color.red,50)
lopc = pvtlos != pvtlos[1] ? na : color.new(color.green,50)
// Show Levels if Selected
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, linewidth=1, offset=-pvtLenR , title="Top Levels",style=plot.style_circles)
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, linewidth=1, offset=-pvtLenR , title="Bottom Levels",style=plot.style_circles)
// Show Levels as a Fractal Chaos Channel
plot(ShowSRLevels and ShowChannel ? pvthis : na, color=color.green, linewidth=1, style=plot.style_stepline, offset=0, title="Top Chaos Channel", trackprice=false)
plot(ShowSRLevels and ShowChannel ? pvtlos : na, color=color.red, linewidth=1, style=plot.style_stepline, offset=0, title="Bottom Chaos Channel", trackprice=false)
// //
float fixedHH = fixnan(higherhigh)
// add offset = -pvtLenR to move the plot to the left and match the HH points.
plot(fixedHH)
bool lowerThanHH = close < fixedHH
float closeHHDiff = abs(fixedHH - close)
if barstate.islast
label.new(bar_index, high + 3*tr, tostring(closeHHDiff), xloc.bar_index, color = color.gray, style = label.style_label_down)
// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60)
strategy.entry("Long",strategy.long,1)
if (higherhigh*0.80==close)`enter code here`
strategy.close("Long",1)
imInATrade = strategy.position size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
The code above finds the highest price after entry or when you're in a trade.

How to find word frequency per country list in pandas?

Let's say I have a .CSV which has three columns: tidytext, location, vader_senti
I was already able to get the amount of *positive, neutral and negative text instead of word* pero country using the following code:
data_vis = pd.read_csv(r"csviamcrpreprocessed.csv", usecols=fields)
def print_sentiment_scores(text):
vadersenti = analyser.polarity_scores(str(text))
return pd.Series([vadersenti['pos'], vadersenti['neg'], vadersenti['neu'], vadersenti['compound']])
data_vis[['vadersenti_pos', 'vadersenti_neg', 'vadersenti_neu', 'vadersenti_compound']] = data_vis['tidytext'].apply(print_sentiment_scores)
data_vis['vader_senti'] = 'neutral'
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_senti'] = 'positive'
data_vis.loc[data_vis['vadersenti_compound'] < 0.23 , 'vader_senti'] = 'negative'
data_vis['vader_possentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_possentiment'] = 1
data_vis['vader_negsentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] <0.23 , 'vader_negsentiment'] = 1
data_vis['vader_neusentiment'] = 0
data_vis.loc[(data_vis['vadersenti_compound'] <=0.3) & (data_vis['vadersenti_compound'] >=0.23) , 'vader_neusentiment'] = 1
sentimentbylocation = data_vis.groupby(["Location"])['vader_senti'].value_counts()
sentimentbylocation
sentimentbylocation gives me the following results:
Location vader_senti
Afghanistan negative 151
positive 25
neutral 2
Albania negative 6
positive 1
Algeria negative 116
positive 13
neutral 4
TO GET THE MOST COMMON POSITIVE WORDS, I USED THIS CODE:
def process_text(text):
tokens = []
for line in text:
toks = tokenizer.tokenize(line)
toks = [t.lower() for t in toks if t.lower() not in stopwords_list]
tokens.extend(toks)
return tokens
tokenizer=TweetTokenizer()
punct = list(string.punctuation)
stopwords_list = stopwords.words('english') + punct + ['rt','via','...','…','’','—','—:',"‚","â"]
pos_lines = list(data_vis[data_vis.vader_senti == 'positive'].tidytext)
pos_tokens = process_text(pos_lines)
pos_freq = nltk.FreqDist(pos_tokens)
pos_freq.most_common()
Running this will give me the most common words and the number of times they appeared, such as
[(good, 1212),
(amazing, 123)
However, what I want to see is how many of these positive words appeared in a country.
For example:
I have a sample CSV here: https://drive.google.com/file/d/112k-6VLB3UyljFFUbeo7KhulcrMedR-l/view?usp=sharing
Create a column for each most_common word, then do a groupby location and use agg to apply a sum for each count:
words = [i[0] for i in pos_freq.most_common()]
# lowering all cases in tidytext
data_vis.tidytext = data_vis.tidytext.str.lower()
for i in words:
data_vis[i] = data_vis.tidytext.str.count(i)
funs = {i: 'sum' for i in words}
grouped = data_vis.groupby('Location').agg(funs)
Based on the example from the CSV and using most_common as ['good', 'amazing'] the result would be:
grouped
# good amazing
# Location
# Australia 0 1
# Belgium 6 4
# Japan 2 1
# Thailand 2 0
# United States 1 0

How can I achieve SQL Pivot statement from LINQ

I am looking to achieve below SQL statement from LINQ. I am not sure whether is it possible? Can someone advice me on this?
SELECT *
FROM (
SELECT CONVERT(VARCHAR, (DATEADD(WEEK, DATEDIFF(WEEK, 0, S.SampleDrawn), 0)), 101) [Date], [Range] =
CASE
WHEN ProbBacteremia >= 0 AND ProbBacteremia < 0.50 THEN 'Low'
WHEN ProbBacteremia >= 0.50 AND ProbBacteremia < 0.75 THEN 'Med'
ELSE 'High'
END
FROM Result.Calculation C INNER JOIN Data.SampleSet S ON C.SampleSetID = S.ID WHERE S.SampleDrawn >= DATEADD(WEEK,-1,GETDATE())) o
PIVOT
(
COUNT(o.[Range])
FOR [Range] IN (
[Low], [Med], [High])
) pt
ORDER BY [Date]
Result of the above query will be as below
Date Low Med High
09/04/2017 370 174 175
09/11/2017 764 352 389
09/18/2017 759 384 360
09/25/2017 765 385 404
10/02/2017 115 48 56
Note that, above date has grouped by week. Ie. 09/04 , 09/11, 09/18 etc. I did lot of research but i found only to group by Week Number.
This is as far as i could come up with LINQ which will return me the below result set.
data = (from a in context.Calculations
where a.SampleSet.SampleDrawn >= dtStart && (isDeptFilter || a.SampleSet.Department == location)
group a by new { Text = RangeProvider(a.ProbBacteremia * 100, riskCats), Date = a.SampleSet.SampleDrawn.Date } into groupedData
orderby groupedData.Key.Date ascending
select new { Value = groupedData.Count(), Text = groupedData.Key.Text, Date = groupedData.Key.Date.ToShortDateString() }).ToList();
public static string RangeProvider(int value)
{
if (value > 0 && value <= 25)
{ return "Low"; }
if (value > 25 && value <= 75)
{ return "Medium"; }
if (value > 75 && value <= 90)
{ return "High"; }
else
{ return "Very High"; }
}
Result dataset of the obver LINQ is
Date Text Value
09/04/2017 Low 65
09/04/2017 Med 80
09/04/2017 High 40
09/05/2017 Low 30
10/05/2017 Med 50
10/05/2017 High 44
Hope this explains what I'm trying to achieve. Please can someone help me with this?
Well as a work-around i have used the Entity Framework Core's "FromSQL" method to execute my stored procedure which take cares of all the GROUP BY's.
you can use this.
data = (from a in context.Calculations
where a.SampleSet.SampleDrawn >= dtStart && (isDeptFilter || a.SampleSet.Department == location)
group a by new { Text = RangeProvider(a.ProbBacteremia * 100, riskCats), Date = a.SampleSet.SampleDrawn.Date } into groupedData
orderby groupedData.Key.Date ascending
select new {
Date = groupedData.Key.Date.ToShortDateString() ,
Low = ( groupedData.Key.Text =="Low" )?groupedData.Count() : 0,
Medium = ( groupedData.Key.Text =="Medium" )?groupedData.Count() : 0,
High = ( groupedData.Key.Text =="High" )?groupedData.Count() : 0,
VeryHigh = ( groupedData.Key.Text =="Very High" )?groupedData.Count() : 0
}).ToList();

SAS Proc IML Optimization

proc iml;
start f_prob(beta) global(one_m_one, pone_m_one);
p = nrow(one_m_one);
td = j(p,3,0.);
a = 1;
do i = 1 to p;
td[i,1] = exp((one_m_one[i,1])*(beta[1]) + (one_m_one[i,2])*(beta[2]) + (one_m_one[i,3])*(beta[3]) + (one_m_one[i,4])*(beta[4]) + (one_m_one[i,5])*(beta[5]) + (one_m_one[i,6])*(beta[6]) + (one_m_one[i,7])*(beta[7]) + (one_m_one[i,8])*(beta[8]) + (one_m_one[i,9])*(beta[9]) + (one_m_one[i,10])*(beta[10]));
do j = a to 11+a;
td[i,2] = td[i,2] + exp((pone_m_one[j,1])*(beta[1]) + (pone_m_one[j,2])*(beta[2]) + (pone_m_one[j,3])*(beta[3]) + (pone_m_one[j,4])*(beta[4]) + (pone_m_one[j,5])*(beta[5]) + (pone_m_one[j,6])*(beta[6]) + (pone_m_one[j,7])*(beta[7]) + (pone_m_one[j,8])*(beta[8]) + (pone_m_one[j,9])*(beta[9]) + (pone_m_one[j,10])*(beta[10]));
end;
a = a + 12;
end;
td[,3] = td[,1]/td[,2];
f = 1;
do i = 1 to p;
f = f*td[i,3];
end;
return(f);
finish f_prob;
/* Set up the constraints: sum(x)=0 */
/* x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 SIGN VALUE */
con = {. . . . . . . . . . . ., /* specify lower bounds */
. . . . . . . . . . . ., /* specify upper bounds */
1 1 1 1 1 1 1 1 1 1 0 0}; /* constraints */
beta0 = j(1,10,0);
optn = {1,4};
call nlpnra(rc, result, "f_prob", beta0, optn) blc=con;
Hi, I am trying to optimise the function f that has 10 parameters in it with a constraint of all 10 parameters sum up to zero.
Can anyone suggest how can I write the code for the last part so that i can optimise f and get the results i want? Thanks in advance.
The documentation provides an example of how to specify a linear constraint matrix. For your example, use a 3 x 12 matrix.
On the first row (columns 1:10) put any lower-bound constraints for the parameters.
On the second row (columns 1:10) put any upper-bound constraints for the parameters.
On the third row, put all ones in columns 1:10. Put a 0 in column 11 to indicate the EQUAL sign. Put 0 in the 12th column to indicate the value of the constraint.
The code looks like this:
/* Set up the constraints: sum(x)=0 */
/* x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 SIGN VALUE */
con = {. . . . . . . . . . . ., /* specify lower bounds */
. . . . . . . . . . . ., /* specify upper bounds */
1 1 1 1 1 1 1 1 1 1 0 0}; /* constraints */
call nlpnra(rc, result, "f_prob", beta, optn) blc=con;
The last line specifies the coefficients of the matrix expression c*x = 0, where c = {1 1 ... 1} contains the of the third row.

Algorithm to find direction between two keys on the num pad?

Given the following direction enum:
typedef enum {
DirectionNorth = 0,
DirectionNorthEast,
DirectionEast,
DirectionSouthEast,
DirectionSouth,
DirectionSouthWest,
DirectionWest,
DirectionNorthWest
} Direction;
And number matrix similar to the numeric pad:
7 8 9
4 5 6
1 2 3
How would you write a function to return the direction between adjacent numbers from the matrix? Say:
1, 2 => DirectionEast
2, 1 => DirectionWest
4, 8 => DirectionNorthEast
1, 7 => undef
You may change the numeric values of the enum if you want to. Readable solutions preferred. (Not a homework, just an algorithm for an app I am working on. I have a working version, but I’m interested in more elegant takes.)
int direction_code(int a, int b)
{
assert(a >= 1 && a <= 9 && b >= 1 && b <= 9);
int ax = (a - 1) % 3, ay = (a - 1) / 3,
bx = (b - 1) % 3, by = (b - 1) / 3,
deltax = bx - ax, deltay = by - ay;
if (abs(deltax) < 2 && abs(deltay) < 2)
return 1 + (deltay + 1)*3 + (deltax + 1);
return 5;
}
resulting codes are
1 south-west
2 south
3 south-east
4 west
5 invalid
6 east
7 north-west
8 north
9 north-east
I would redefine the values in the enum so that North, South, East and West take a different bit each.
typedef enum {
undef = 0,
DirectionNorth = 1,
DirectionEast = 2,
DirectionSouth = 4,
DirectionWest = 8,
DirectionNorthEast = DirectionNorth | DirectionEast,
DirectionSouthEast = DirectionSouth | DirectionEast,
DirectionNorthWest = DirectionNorth | DirectionWest,
DirectionSouthWest = DirectionSouth | DirectionWest
} Direction;
With those new values:
int ax = ( a - 1 ) % 3, ay = ( a - 1 ) / 3;
int bx = ( b - 1 ) % 3, by = ( b - 1 ) / 3;
int diffx = std::abs( ax - bx );
int diffy = std::abs( ay - by );
int result = undef;
if( diffx <= 1 && diffy <= 1 )
{
result |= ( bx == ax - 1 ) ? DirectionWest : 0;
result |= ( bx == ax + 1 ) ? DirectionEast : 0;
result |= ( by == ay - 1 ) ? DirectionSouth : 0;
result |= ( by == ay + 1 ) ? DirectionNorth : 0;
}
return static_cast< Direction >( result );
Update: Finally, I think its correct now.
With this matrix of numbers the following holds true:
1) a difference of 1 (+ve or -ve) always implies that the direction is either east or west.
2) similary, a difference of 3 for direction north or south.
3) a difference of 4 north east or south west.
4) a difference of 2 north west or south east.