Pine Editor V5 Plotting OHLC levels with a timeframe selector - ohlc

Im trying to simplify some code for an indicator Im working one and need some help. Currently trying to setup and OHLC level that allows you to change it while selecting an option from the timeframe dropdown. I found a script on here but wasnt sure how to tie in the timeframe option. The first option is to activate the OHLC levels and the second one is to adjust the timeframe while for example staying on the 15 minute chart
ohlcscan = input(false, title='OHLC Scanner', group='OPEN HIGH LOW CLOSE')
ohlctf = input.timeframe(title="Timeframe", defval="1D", group='OPEN HIGH LOW CLOSE')
f_newLine(_color) => line.new(na, na, na, na, xloc.bar_time, extend.right, _color)
f_moveLine(_line, _x, _y) =>
line.set_xy1(_line, _x, _y)
line.set_xy2(_line, _x+1, _y)
var line line_open = f_newLine(color.yellow)
var line line_high = f_newLine(color.red)
var line line_low = f_newLine(color.green)
var line line_close = f_newLine(color.white)
[pdo,pdh,pdl,pdc,pdt] = request.security(syminfo.tickerid,"D",
[open[1],high[1],low[1],close[1],time[1]])
if barstate.islast
f_moveLine(line_open, pdt, pdo)
f_moveLine(line_high, pdt, pdh)
f_moveLine(line_low , pdt, pdl)
f_moveLine(line_close, pdt, pdc)

Related

Choropleth us-states map showing incorrect data and color coding

I am trying to show hospitals by type in US states. The dataset I am using is here https://www.kaggle.com/carlosaguayo/usa-hospitals
I am using choropleth and here is my code. I basically have a dropdown with the type of hospital and when select, I am getting the count
#app.callback(Output('figure-1', 'figure'),
[Input('options-drop', 'value')])
def make_figure(varname):
mygraphtitle = f'Hospitals of {varname}'
mycolorscale = 'Blues'
mycolorbartitle = "Count"
data=go.Choropleth(
locations=df['STATE'],
locationmode = 'USA-states',
z = df[df["TYPE"] == varname]["STATE"].value_counts(),
colorscale = mycolorscale,
colorbar_title = mycolorbartitle,
)
fig = go.Figure(data)
fig.update_layout(
title_text = mygraphtitle,
geo_scope='usa',
width=1200,
height=800
)
return fig
I have 3 issues with the grpah
Data is not being shown for all states
Data shown for few states is incorrect
Color coding is incorrect even for those states with incorrect data. state with higher hospital count is shown with lighter blue whereas with lower count is shown with darker blue
You can see below from pandas, I can tell Texas has only 65 critical access hospitals but the US map shows count as 78 and even if it was 78, the color of Texas is light blue compared with other state with lower hospitals. Where am I going wrong?
I have not verified this in the Dash environment, but I believe the operation will be the same. The cause is that you are specifying a state column for the entire data frame you are setting up. The easiest response is to target the filtered data frame.
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('./data/Hospitals.csv')
varname = 'CRITICAL ACCESS'
filtered_df = df[df["TYPE"] == varname]["STATE"].value_counts().to_frame('value')
#print(filtered_df)
fig = go.Figure(data=go.Choropleth(
locations=filtered_df.index,
z = filtered_df['value'],
locationmode = 'USA-states',
colorscale = 'Blues',
colorbar_title = "Count",
))
fig.update_layout(
title_text = f'Hospitals of {varname}',
geo_scope='usa',
width=1200,
height=800
)
fig.show()

Percentage labels in pie chart with ggplot

I'm working now in a statistics project and recently started with R. I have some problems with the visualization. I found a lot of different tutorials about how to add percentage labels in pie charts, but after one hour of trying I still don't get it. Maybe something is different with my data frame so that this doesn't work?
It's a data frame with collected survey answers, so I'm not allowed to publish them here. The column in question (geschäftliche_lage) is a factor with three levels ("Gut", "Befriedigend", "Schlecht"). I want to add percentage labels for each level.
I used the following code in order to create the pie chart:
dataset %>%
ggplot(aes(x= "", fill = geschäftliche_lage)) +
geom_bar(stat= "count", width = 1, color = "white") +
coord_polar("y", start = 0, direction = -1) +
scale_fill_manual(values = c("#00BA38", "#619CFF", "#F8766D")) +
theme_void()
This code gives me the desired pie chart, but without percentage labels. As soon as a I try to add percentage labels, everything is messed up. Do you know a clean code for adding percentage labels?
If you need more information or data, just let me know!
Greetings
Using mtcars as example data. Maybe this what your are looking for:
library(ggplot2)
ggplot(mtcars, aes(x = "", fill = factor(cyl))) +
geom_bar(stat= "count", width = 1, color = "white") +
geom_text(aes(label = scales::percent(..count.. / sum(..count..))), stat = "count", position = position_stack(vjust = .5)) +
coord_polar("y", start = 0, direction = -1) +
scale_fill_manual(values = c("#00BA38", "#619CFF", "#F8766D")) +
theme_void()
Created on 2020-05-25 by the reprex package (v0.3.0)

Moving average line is only shown till last ticker.id close

I am working on a moving average indicator which shows the MA line of a given time frame.
For some reason is the MA line only displaced till the last ticker.id period close. So when for example I have set the indicator to show a daily MA the line is only updated when the day closes.
(Link to image https://i.stack.imgur.com/QjkvO.jpg)
Does anyone know how my indicator will be able include data between daily closes, so the line is being updated continuously?
I think this line not being updated continuously also causes the label which is supposed to be plotted right at the MA line being plotted at the 1 point / dollar height on the chart.
I have only recently started writing code, so excuse me if this is a dumb question. I have written this code looking at other indicators and trying to fit parts into my own
This is the code of the entire indicator.
//#version=4
study(title="Custom Timeframe SMA", shorttitle="Custom TF MA", overlay=true)
res = input(title="MA Timeframe", type=input.resolution, defval="D",options=["60", "240", "D", "W"])
length1 = input(title="SMA Length", type=input.integer, defval=50)
Label=input(title="show Labels",defval=true)
sma1 = sma(close, length1)
sourceEmaSmooth1 = security(syminfo.tickerid, res, sma1, barmerge.gaps_on, barmerge.lookahead_on)
plot(sourceEmaSmooth1, style=plot.style_line, linewidth=2, title="25 period", color=#a21e7b)
plotchar((sourceEmaSmooth1 ? Label : barstate.islast and not barstate.isconfirmed) ? sourceEmaSmooth1 : na, location=location.absolute, text=" 50 SMA", textcolor=#a21e7b, offset=10, editable=false)
Using barmerge.gaps_on with security() creates holes which appear as na values at the chart's resolution, which is why your ma wasn't always showing. It wasn't apparent on historical bars because the plot() function fills the space from non-gap to non-gap (you could see it if you plotted circles instead of a line).
Using barmerge.lookahead_on with security() produces lookahead bias on historical bars. Very nasty if you don't index the value you're fetching, as is explained in this publication on how to use security() correctly: How to avoid repainting when using security().
I added show_last = 1 to you label-plotting call and fixed the conditional. Because it now only plots the last occurrence of the label, we no longer need to worry about barstates:
//#version=4
study(title="Custom Timeframe SMA", shorttitle="Custom TF MA", overlay=true)
res = input(title="MA Timeframe", type=input.resolution, defval="D",options=["60", "240", "D", "W"])
length1 = input(title="SMA Length", type=input.integer, defval=50)
Label=input(title="show Labels",defval=true)
sma1 = sma(close, length1)
sourceEmaSmooth1 = security(syminfo.tickerid, res, sma1)
plot(sourceEmaSmooth1, linewidth=2, title="25 period", color=#a21e7b)
plotchar(Label ? sourceEmaSmooth1 : na, location=location.absolute, text=" 50 SMA", textcolor=#a21e7b, offset=10, show_last = 1, editable=false)

how to draw lines in Pine script (Tradingview)?

Pine editor still does not have built-in functions to plot lines (such as support lines, trend lines).
I could not find any direct or indirect method to draw lines.
I want to build function that look like below (for example only)
draw_line(price1, time1,price2, time2)
any Ideas or suggestions ?
Unfortunately I don't think this is something they want to provide. Noticing several promising posts from 4 years ago that never came through. The only other way, seem to involve some calculations, by approximating your line with some line plots, where you hide the non-relevant parts.
For example:
...
c = close >= open ? lime : red
plot(close, color = c)
would produce something like this:
Then, you could try to replace red with na to get only the green parts.
Example 2
I've done some more experiments. Apparently Pine is so crippled you can't even put a plot in function, so the only way seem to be to use the point slope formula for a line, like this:
//#version=3
study(title="Simple Line", shorttitle='AB', overlay=true)
P1x = input(5744)
P1y = input(1.2727)
P2x = input(5774)
P2y = input(1.2628)
plot(n, color=na, style=line) // hidden plot to show the bar number in indicator
// point slope
m = - (P2y - P1y) / (P2x - P1x)
// plot range
AB = n < P1x or n > P2x ? na : P1y - m*(n - P1x)
LA = (n == P1x) ? P1y : na
LB = (n == P2x) ? P2y : na
plot(AB, title="AB", color=#ff00ff, linewidth=1, style=line, transp=0)
plotshape(LA, title='A', location=location.absolute, color=silver, transp=0, text='A', textcolor=black, style=shape.labeldown)
plotshape(LB, title='B', location=location.absolute, color=silver, transp=0, text='B', textcolor=black, style=shape.labelup )
The result is quite nice, but too inconvenient to use.
UPDATE: 2019-10-01
Apparently they have added some new line functionality to Pinescript 4.0+.
Here is an example of using the new vline() function:
//#version=4
study("vline() Function for Pine Script v4.0+", overlay=true)
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line, 54 lines maximum allowable per indicator
return = line.new(BarIndex, -1000, BarIndex, 1000, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
if(bar_index%10==0.0)
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
As for the other "new" line function, I have not tested it yet.
This is now possible in Pine Script v4:
//#version=4
study("Line", overlay=true)
l = line.new(bar_index, high, bar_index[10], low[10], width = 4)
line.delete(l[1])
Here is a vertical line function by midtownsk8rguy on TradingView:
vline(BarIndex, Color, LineStyle, LineWidth) => // Verticle Line Function, ≈50-54 lines maximum allowable per indicator
// return = line.new(BarIndex, 0.0, BarIndex, 100.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and RSI, Stochastic, etc...
// return = line.new(BarIndex, -1.0, BarIndex, 1.0, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=false) and +/-1.0 oscillators
return = line.new(BarIndex, low - tr, BarIndex, high + tr, xloc.bar_index, extend.both, Color, LineStyle, LineWidth) // Suitable for study(overlay=true)
if(bar_index%10==0.0) // Generically plots a line every 10 bars
vline(bar_index, #FF8000ff, line.style_solid, 1) // Variable assignment not required
You can also use if barstate.islast if you only draw your lines once instead of on each candle, this way you don't need to delete the previous lines.
More compact code for draw lines:
//#version=3
study("Draw line", overlay=true)
plot(n, color=na, style=line)
AB(x1,x2,y1,y2) => n < x1 or n > x2 ? na : y1 + (y2 - y1) / (x2 - x1) * (n - x1)
plot(AB(10065,10136,3819,3893), color=#ff00ff, linewidth=1, style=line,
transp=0)
plot(AB(10091,10136,3966.5,3931), color=#ff00ff, linewidth=1, style=line,
transp=0)
Here is an example that might answer the original question:
//#version=4
study(title="trendline example aapl", overlay=true)
//#AAPL
line12= line.new(x1=int(1656322200000),
y1=float(143.49),
x2=int(1659519000000),
y2=float(166.59),
extend=extend.right,
xloc=xloc.bar_time)
(to calculate the time it needs to be calculated as the *bar open time in unix milliseconds see: https://currentmillis.com/ ; can be calculated in excel with this formula =
= (([date eg mm/dd/yyyy]+[bar open time eg 9.30am])- 0/24 - DATE(1970,1,1)) * 86400000
= ((6/27/2022+9:30:00 AM)- 0/24 - DATE(1970,1,1)) * 86400000
= ((44739+0.395833333333333)- 0/24 - DATE(1970,1,1)) * 86400000
= 1656322200000
)
adjust the zero/24 to offset the time zone if needed eg 1/24

How to change colors in stat_summary()

I am trying to plot two columns of raw data (I have used melt to combine them into one data frame) and then add separate error bars for each. However, I want to make the raw data for each column one pair of colors and the error bars another set of colors, but I can't seem to get it to work. The plot I am getting is at the link below. I want to have different color pairs for the raw data and for the error bars. A simple reproducible example is coded below, for illustrative purposes.
dat2.m<-data.frame(obs=c(2,4,6,8,12,16,2,4,6),variable=c("raw","raw","raw","ip","raw","ip","raw","ip","ip"),value=runif(9,0,10))
c <- ggplot(dat2.m, aes(x=obs, y=value, color=variable,fill=variable,size = 0.02)) +geom_jitter(size=1.25) + scale_colour_manual(values = c("blue","Red"))
c<- c+stat_summary(fun.data="median_hilow",fun.args=(conf.int=0.95),aes(color=variable), position="dodge",geom="errorbar", size=0.5,lty=1)
print(c)
[1]: http://i.stack.imgur.com/A5KHk.jpg
For the record: I think that this is a really, really bad idea. Unless you have a use case where this is crucial, I think you should re-examine your plan.
However, you can get around it by adding a new set of variables, padded with a space at the end. You will want/need to play around with the legends, but this should work (though it is definitely ugly):
dat2.m<- data.frame(obs=c(2,4,6,8,12,16,2,4,6),variable=c("raw","raw","raw","ip","raw","ip","raw","ip","ip"),value=runif(9,0,10))
c <- ggplot(dat2.m, aes(x=obs, y=value, color=variable,fill=variable,size = 0.02)) +geom_jitter(size=1.25) + scale_colour_manual(values = c("blue","Red","green","purple"))
c<- c+stat_summary(fun.data="median_hilow",fun.args=(conf.int=0.95),aes(color=paste(variable," ")), position="dodge",geom="errorbar", size=0.5,lty=1)
print(c)
One way around this would be to use repetitive calls to geom_point and stat_summary. Use the data argument of those functions to feed subsets of your dataset into each call, and set the color attribute outside of aes(). It's repetitive and somewhat defeats the compactness of ggplot, but it'd do.
c <- ggplot(dat2.m, aes(x = obs, y = value, size = 0.02)) +
geom_jitter(data = subset(dat2.m, variable == 'raw'), color = 'blue', size=1.25) +
geom_jitter(data = subset(dat2.m, variable == 'ip'), color = 'red', size=1.25) +
stat_summary(data = subset(dat2.m, variable == 'raw'), fun.data="median_hilow", fun.args=(conf.int=0.95), color = 'pink', position="dodge",geom="errorbar", size=0.5,lty=1) +
stat_summary(data = subset(dat2.m, variable == 'ip'), fun.data="median_hilow", fun.args=(conf.int=0.95), color = 'green', position="dodge",geom="errorbar", size=0.5,lty=1)
print(c)