Pine Script correction - scripting

study("Order Block Tracker")
// Define the symbol and exchange
symbol = "BTC/USDT"
exchange = "Binance"
// Define the time frames to track
tf5m = 5
tf15m = 15
tf45m = 45
tf1h = 60
tf4h = 240
tf1d = 1440
tf1w = 10080
tf1mo = 43200
// Get historical price data for the selected symbol
btc = security(symbol, tf1h, close, exchange=exchange)
// Calculate the order blocks for each time frame
ob5m = abs(diff(close, tf5m))
ob15m = abs(diff(close, tf15m))
ob45m = abs(diff(close, tf45m))
ob1h = abs(diff(close, tf1h))
ob4h = abs(diff(close, tf4h))
ob1d = abs(diff(close, tf1d))
ob1w = abs(diff(close, tf1w))
ob1mo = abs(diff(close, tf1mo))
// Plot the order blocks on the chart
plot(ob5m, style=histogram, color=red, linewidth=2, title="5m")
plot(ob15m, style=histogram, color=orange, linewidth=2, title="15m")
plot(ob45m, style=histogram, color=yellow, linewidth=2, title="45m")
plot(ob1h, style=histogram, color=green, linewidth=2, title="1h")
plot(ob4h, style=histogram, color=cyan, linewidth=2, title="4h")
plot(ob1d, style=histogram, color=blue, linewidth=2, title="1d")
plot(ob1w, style=histogram, color=purple, linewidth=2, title="1w")
plot(ob1mo, style=histogram, color=magenta, linewidth=2, title="1mo")
changed
study("Order Block Tracker")
with
Indicator .
now it is showing the
Could not find function or function reference 'security'
this is an 'Order Block Tracker' indicator. correction required

Related

Is there any other way to find percentage and plot a group bar-chart without using matplotlib?

emp_attrited = pd.DataFrame(df[df['Attrition'] == 'Yes'])
emp_not_attrited = pd.DataFrame(df[df['Attrition'] == 'No'])
print(emp_attrited.shape)
print(emp_not_attrited.shape)
att_dep = emp_attrited['Department'].value_counts()
percentage_att_dep = (att_dep/237)*100
print("Attrited")
print(percentage_att_dep)
not_att_dep = emp_not_attrited['Department'].value_counts()
percentage_not_att_dep = (not_att_dep/1233)*100
print("\nNot Attrited")
print(percentage_not_att_dep)
fig = plt.figure(figsize=(20,10))
ax1 = fig.add_subplot(221)
index = np.arange(att_dep.count())
bar_width = 0.15
rect1 = ax1.bar(index, percentage_att_dep, bar_width, color = 'black', label = 'Attrited')
rect2 = ax1.bar(index + bar_width, percentage_not_att_dep, bar_width, color = 'green', label = 'Not Attrited')
ax1.set_ylabel('Percenatage')
ax1.set_title('Comparison')
xTickMarks = att_dep.index.values.tolist()
ax1.set_xticks(index + bar_width)
xTickNames = ax1.set_xticklabels(xTickMarks)
plt.legend()
plt.tight_layout()
plt.show()
The first block represents how the dataset is split into 2 based upon Attrition
The second block represents the calculation of percentage of Employees in each Department who are attrited and not attrited.
The third block is to plot the given as a grouped chart.
You can do:
(df.groupby(['Department'])
['Attrited'].value_counts(normalize=True)
.unstack('Attrited')
.plot.bar()
)

plot observed data and predict data by two models (lm and lme) in the same plot

How can I plot observed data and the results of differents models (lm and lme) in the same plot?
I tried the code below, but it only worked for points. I would like to add the data predicted by the inline models of different colors.
#Data
d <- runif(160,0,100)#data
y <- rnorm(16,1,0.05)*x + rnorm(16,0,0.5)#data
df = data.frame(d,y)
#Models
#linear - 1
m1 = lm(y~d, data = df)
summary(m1)
# linear - 2
m2 = lm(y~d+I(d^2), data = df)
summary(m2)
df$Class10<-with(df,ifelse(d<20,"<20",ifelse(d<30,"20-30",
ifelse(d<40,"30-40",ifelse(d<50,"40-50",ifelse(d<60,"50-60",
ifelse(d<70,"60-70",ifelse(d<80,"70-80",ifelse(d<90,"80-90",
ifelse(d>=90,">90","ERROR"))))))))))
# number of classes
length(unique(df$Class10))
# classes
sort(unique(df$Class10))
# observations by class
table(df$Class10)
plot(table(df$Class10))
# b0
m10 = lme(y~d, random=~1|Class10, method="ML" ,data = df)
# b1
m10 = lme(y~d, random=~-1+d|Class10, method="ML" , data = df)
#
m10 = lme(y~d, random=~d|Class10, method="ML" , data = df,
control = lmeControl(niterEM = 5200, msMaxIter = 5200))
#plot points - It works
plot(df$d, df$y)
points(df$d, predict(m1), col="blue")
points(df$d, predict(m10, level=1), col="red")
#curve
plot(df$d, df$y)
curve(predict(m1,newdata=data.frame(d=x)),lwd=2, add=T)
curve(predict(m10,newdata=data.frame(d=x)),lwd=1, add=T)#error
# line
plot(df$d,df$y)
curve(predict(m1,newdata=data.frame(d=x)),lwd=2, add=T)
lines(df$d, predict(m10, level=1),col="green")#error
Is there any way in ggplot2, for example?
Here is a way! I like using broom and broom.mixed to get a complete tibble with predicted values for each model.
library(tidyverse)
library(lme4)
library(broom)
library(broom.mixed)
df <- ChickWeight
lin <- lm(weight ~ Time,df)
mlm <- lmer(weight ~ Time + (1 | Chick),df)
df <- df %>%
mutate(linpred = broom::augment(lin)[,3] %>% pull(),
mlmpred = broom.mixed::augment(mlm)[,4] %>% pull())
ggplot(df,aes(Time,weight,group = Chick)) +
geom_line(alpha = .2) +
geom_line(aes(y = linpred,color = 'Fixed Linear Effect')) +
geom_line(aes(y = mlmpred,color = 'Random Intercepts'), alpha = .4) +
scale_color_manual(values = c('blue','red')) +
labs(color = '') +
theme_minimal()

add more space to the color_row in sns.clustermap

How to add more spacing to column/row_colors? It looks it gets really dense after adding 3 or more rows
#modified example data is from this question: https://stackoverflow.com/questions/48173798/additional-row-colors-in-seaborn-cluster-map
matrix = pd.DataFrame(np.random.random_integers(0,1, size=(50,4)))
labels = np.random.random_integers(0,5, size=50)
lut = dict(zip(set(labels), sns.hls_palette(len(set(labels)), l=0.5, s=0.8)))
row_colors = pd.DataFrame(labels)[0].map(lut)
#Create additional row_colors here
labels2 = np.random.random_integers(0,1, size=50)
lut2 = dict(zip(set(labels2), sns.hls_palette(len(set(labels2)), l=0.5, s=0.8)))
row_colors2 = pd.DataFrame(labels2)[0].map(lut2)
# add more rows
row_colors = pd.concat([row_colors,row_colors,row_colors2,row_colors2,row_colors2],axis=1)
g=sns.clustermap(matrix, col_cluster=False, linewidths=0.1, cmap='coolwarm', row_colors=row_colors)
plt.show()
cluster_example
You can adjust the linewidths parameter.
g=sns.clustermap(matrix, col_cluster=False, linewidths=0.9, cmap='coolwarm', row_colors=row_colors) will give you more spacing.

Several ggplotly figures from within if block in rmarkdown

I am unable to generate an html file, from rmarkdown, which displays two or more ggplotly plots created inside an if block in a given code chunk.
My MWE rmarkdown source code follows:
---
title: Several ggplotly figures from within if block in rmarkdown
author: "Mauricio Calvao"
date: "February 27, 2017"
output:
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(ggplot2)
library(plotly)
```
## Outside if block:
I can have rmarkdown generate an html document with two ggplotly plots, outside of an if block in a given chunk:
```{r}
ggplotly(qplot(data = pressure, x = temperature, y = pressure))
ggplotly(qplot(data = pressure, x = pressure, y = temperature))
```
## Inside if block:
However, when I try the same code inside an if block, only the last plot shows up in the html document:
```{r}
if (TRUE) {
ggplotly(qplot(data = pressure, x = temperature, y = pressure))
ggplotly(qplot(data = pressure, x = pressure, y = temperature))
}
```
**How do I print two (or more plots, for that matter) from within an if block in the html document???**
The above is a MWE, but, in fact, in a more general setting I would have a large number of plots to be printed depending on several if else blocks...
Any suggestions are welcome!!
The answer is now available from the plotly reference.
In short, you either use:
subplot:
if (TRUE) {
p1= ggplotly(qplot(data = pressure, x = temperature, y = pressure))
p2= ggplotly(qplot(data = pressure, x = pressure, y = temperature))
subplot(p1, p2)
}
or taglist
if (TRUE) {
p1= ggplotly(qplot(data = pressure, x = temperature, y = pressure))
p2= ggplotly(qplot(data = pressure, x = pressure, y = temperature))
htmltools::tagList(list(p1, p2))
}

Plotting an Indicator with matplotlib

I rewrote a indicator from another language into Python but my plot doesn't look like right. This is a Picture how the Plot should look like
But my plot look like this
Something it's wrong on the bottom part of my indicator but I don't how to fix it. My full code is here and here is the data.csv file i'm using.
def matrixSeries(matrix):
nn = 10 #Smoother
# --Sup/Res Detail
SupResPeriod = 50
SupResPercentage = 100
PricePeriod = 16
ob = 200 #Overbought
os = -200 #Oversold
#OBOS = false
#dynamic = true
high = np.array(r['max'])
low = np.array(r['min'])
close = np.array(r['close'])
ys1 = (high + low + close * 2 ) / 4
rk3 = ta.EMA(ys1, nn)
rk4 = ta.STDDEV(ys1, nn)
rk5 = (ys1 - rk3) * 200 /rk4
rk6 = ta.EMA(rk5, nn)
up = ta.EMA(rk6, nn)
down = ta.EMA(up, nn)
# remove nans in array
upNans = np.isnan(up)
up[upNans] = 0
downNans = np.isnan(down)
down[downNans] = 0
Oo = np.where(up<down, up, down)
Cc= np.where(up<down, down, up )
#color
if matrix == 'color':
color = []
aa = Oo > Cc
bb = up > down
color = np.where( aa , 'red' , np.where(bb, 'green','red') )
return color
#Body Calculations
bodyHigh = np.where(up>down, up, down)
bodyLow = np.where(Oo<down, up, down)
bodyCover = np.where( np.any(up>0) and np.any(down>0), bodyLow, np.where( np.any(up<0) and np.any(down<0), bodyHigh,0))
bodyCover = bodyCover
if matrix == 'cover':
return bodyCover
if matrix == 'top':
return Oo
if matrix == 'bottom':
return Cc
ax3 = plt.subplot2grid((6,4), (0,0),sharex=ax1, rowspan=2, colspan=4)
ax3.bar(r['date'], matrixSeries('top'), width=1.1,linewidth=0, color=matrixSeries('color'))
ax3.bar(r['date'], matrixSeries('bottom'), width=1.1,linewidth=0, color=matrixSeries('color'))
ax3.bar(r['date'], matrixSeries('cover'), width=1.1, linewidth=0, color='black' )
ax2.axes.xaxis.set_ticklabels([])
plt.show()
I have fix it by my own. The bodyCover Calculation was wrong.
#Body Calculations
bodyLow = np.where(up>down, up, down).clip(max=0)
bodyHigh = np.where(Oo<down, up, down).clip(min=0)
bodyCover = bodyLow + bodyHigh