How can I see weekly and monthly pivots for their respected time range from the first day itself? - pivot

I need to see weekly and monthly pivots for their respected time range from the first day itself. I don't want pivot lines to form with bars. For example when new week/month start Pivots are fixed for entire week/month. I am new into coding so need help with this. this is an indicator I am using in trading view.
//#version=4
study("THC LEVELS", shorttitle="THC LEVELS", overlay = true, max_bars_back=500)
disp_pivot = input(true, title="Show Daily Pivots ?", tooltip="Show Central Pivot Range")
cprcolor = input(defval=color.blue, title="Select Pivot Color", type=input.color)
cprlinestyle=input(defval= line.style_dotted, title="Select Pivot Line Style", type=input.string, options=["dsh", "sol", "dot"], tooltip="Dashed, Solid, Dotted")
cprlinewidth=input(defval= 2, title="Select Pivot Line Thickness", type=input.integer, options=[1, 2, 3, 4, 5])
disp_s1r1 = input(true, title="Show Daily S1, S2, S3, R1, R2, R3 ?", tooltip="Show Pivot Support and Resistance")
s1color = input(defval=color.green, title="Select S1, S2, S3 Color", type=input.color)
r1color = input(defval=color.orange, title="Select R1, R2, R3 Color", type=input.color)
s1r1linestyle=input(defval= line.style_dotted, title="Select S/R Line Style", type=input.string, options=["dsh", "sol", "dot"], tooltip="Dashed, Solid, Dotted")
s1r1linewidth=input(defval= 2, title="Select S/R Line Thickness", type=input.integer, options=[1, 2, 3, 4, 5])
disp_dp = input(false, title="Show PDH & PDL ?", tooltip="Previous Day High and Low")
previousdayHcolor = input(defval=color.black, title="Select Previous Day High Color", type=input.color)
previousdayLcolor = input(defval=color.black, title="Select Previous Day Low Color", type=input.color)
previousdaylinestyle = input(defval= line.style_dashed, title="Select Line Style", type=input.string, options=["dsh", "sol", "dot"], tooltip="Dashed, Solid, Dotted")
pdhllinewidth=input(defval= 1, title="Select PDH/PDL Line Thickness", type=input.integer, options=[1, 2, 3, 4, 5])
disp_historicalpivot = input(title="Show Historical Daily Pivots ?", type=input.bool, defval=false)
showweeklyCPR = input(title="Show Weekly Pivot ?", type=input.bool, defval=false)
showweeklyHL = input(title="Show Prev Week High/Low ?", type=input.bool, defval=false)
showmonthlyCPR =input(title="Show Monthly Pivot ?", type=input.bool, defval=false)
showmonthlyHL =input(title="Show Prev Month High/Low ?", type=input.bool, defval=false)
firstbar(resolution) =>
ch = 0
if(resolution == 'Y')
t = year(time('D'))
ch := change(t) != 0 ? 1 : 0
else
t = time(resolution)
ch := change(t) != 0 ? 1 :0
ch
pp_res = 'D'
bars_sinse = 0
bars_sinse := firstbar(pp_res) ? 0 : bars_sinse[1] + 1
// label location shift
chper = time - time[1]
chper := change(chper) > 0 ? chper[1] : chper
xlocation = time + chper * 30
// label location shift ends
phigh_d = security(syminfo.tickerid, "D", high[1], barmerge.gaps_off, barmerge.lookahead_on)
plow_d = security(syminfo.tickerid, "D", low[1], barmerge.gaps_off, barmerge.lookahead_on)
pclose_d = security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
y_th = line.new(bar_index[min(bars_sinse, 10)], disp_dp?phigh_d :na, bar_index, disp_dp?phigh_d :na, color=previousdayHcolor, style = previousdaylinestyle, width=pdhllinewidth, extend = extend.right)
y_tl = line.new(bar_index[min(bars_sinse, 10)], disp_dp?plow_d :na, bar_index, disp_dp?plow_d :na, color=previousdayLcolor, style = previousdaylinestyle,width=pdhllinewidth, extend = extend.right)
line.delete(y_th[1])
line.delete(y_tl[1])
label_yh = label.new(x = xlocation, y=disp_dp?phigh_d : na, text="PDH", style= label.style_none, xloc = xloc.bar_time, yloc=yloc.price)
label_yl = label.new(x = xlocation, y=disp_dp?plow_d : na, text="PDL", style= label.style_none, xloc = xloc.bar_time, yloc=yloc.price)
label.delete(label_yh[1])
label.delete(label_yl[1])
// Pivot Range
P = (phigh_d + plow_d + pclose_d) / 3
BC = (phigh_d + plow_d)/2
TC = (P - BC) + P
line_p_d = line.new(bar_index[max(bars_sinse, 1)], disp_pivot?TC :na, bar_index, disp_pivot?TC :na, color=cprcolor, style = cprlinestyle,width=cprlinewidth, extend = extend.right)
line_TC_d = line.new(bar_index[max(bars_sinse, 1)], disp_pivot?P :na, bar_index, disp_pivot?P :na, color=cprcolor, style = cprlinestyle,width=cprlinewidth, extend = extend.right)
line_BC_d = line.new(bar_index[max(bars_sinse, 1)], disp_pivot?BC :na, bar_index, disp_pivot?BC :na, color=cprcolor, style = cprlinestyle,width=cprlinewidth, extend = extend.right)
line.delete(line_p_d[1])
line.delete(line_TC_d[1])
line.delete(line_BC_d[1])
// Resistance Levels
R3 = phigh_d + 2*(P - plow_d)
R2 = P + (phigh_d - plow_d)
R1 = (P * 2) - plow_d
// Support Levels
S1 = (P * 2) - phigh_d
S2 = P - (phigh_d - plow_d)
S3 = plow_d - 2*(phigh_d - P)
line_s1_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?S1 :na, bar_index, disp_s1r1?S1 :na, color=s1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_s1_d[1])
line_s2_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?S2 :na, bar_index, disp_s1r1?S2 :na, color=s1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_s2_d[1])
line_s3_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?S3 :na, bar_index, disp_s1r1?S3 :na, color=s1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_s3_d[1])
line_r1_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?R1 :na, bar_index, disp_s1r1?R1 :na, color=r1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_r1_d[1])
line_r2_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?R2 :na, bar_index, disp_s1r1?R2 :na, color=r1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_r2_d[1])
line_r3_d = line.new(bar_index[max(bars_sinse, 1)], disp_s1r1?R3 :na, bar_index, disp_s1r1?R3 :na, color=r1color, style = s1r1linestyle,width=s1r1linewidth, extend = extend.right)
line.delete(line_r3_d[1])
//show daily historical pivots
plot(disp_historicalpivot ? P : na, title="Historical Pivot", linewidth=1, color=color.blue, style=plot.style_circles)
plot(disp_historicalpivot ? TC : na, title="Historical TC", linewidth=1, color=color.blue, style=plot.style_circles)
plot(disp_historicalpivot ? BC : na, title="Historical BC", linewidth=1, color=color.blue, style=plot.style_circles)
plot(disp_historicalpivot ? S1 : na, title="Historical S1", linewidth=1, color=color.green, style=plot.style_circles)
plot(disp_historicalpivot ? S2 : na, title="Historical S2", linewidth=1, color=color.green, style=plot.style_circles)
plot(disp_historicalpivot ? S3 : na, title="Historical S3", linewidth=1, color=color.green, style=plot.style_circles)
plot(disp_historicalpivot ? R1 : na, title="Historical R1", linewidth=1, color=color.orange, style=plot.style_circles)
plot(disp_historicalpivot ? R2 : na, title="Historical R2", linewidth=1, color=color.orange, style=plot.style_circles)
plot(disp_historicalpivot ? R3 : na, title="Historical R3", linewidth=1, color=color.orange, style=plot.style_circles)
// Calculate weekly CPR
th_w = security(syminfo.tickerid, "W", high[1], barmerge.gaps_off, barmerge.lookahead_on)
tl_w = security(syminfo.tickerid, "W", low[1], barmerge.gaps_off, barmerge.lookahead_on)
tc_w = security(syminfo.tickerid, "W", close[1], barmerge.gaps_off, barmerge.lookahead_on)
// weekly Pivot Range
wP = (th_w + tl_w + tc_w) / 3
wBC = (th_w + tl_w)/2
wTC = (wP - wBC) + wP
// Resistance Levels
wR3 = th_w + 2*(wP - tl_w)
wR2 = wP + (th_w - tl_w)
wR1 = (wP * 2) - tl_w
// Support Levels
wS1 = (wP * 2) - th_w
wS2 = wP - (th_w - tl_w)
wS3 = tl_w - 2*(th_w - wP)
// show weekly high low
plot (showweeklyHL ? th_w : na, title="Weekly High", linewidth=1, color=color.black, style=plot.style_circles)
plot (showweeklyHL ? tl_w : na, title="Weekly Low", linewidth=1, color=color.black, style=plot.style_circles)
//showweeklyCPR
plot (showweeklyCPR ? wP : na, title="Weekly Pivot", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showweeklyCPR ? wTC : na, title="Weekly TC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showweeklyCPR ? wBC : na, title="Weekly BC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showweeklyCPR ? wS1 : na, title="Weekly S1", linewidth=1, color=color.green, style=plot.style_circles)
plot (showweeklyCPR ? wS2 : na, title="Weekly S2", linewidth=1, color=color.green, style=plot.style_circles)
plot (showweeklyCPR ? wS3 : na, title="Weekly S3", linewidth=1, color=color.green, style=plot.style_circles)
plot (showweeklyCPR ? wR1 : na, title="Weekly R1", linewidth=1, color=color.orange, style=plot.style_circles)
plot (showweeklyCPR ? wR2 : na, title="Weekly R2", linewidth=1, color=color.orange, style=plot.style_circles)
plot (showweeklyCPR ? wR3 : na, title="Weekly R3", linewidth=1, color=color.orange, style=plot.style_circles)
// Calculate monthly CPR
th_m = security(syminfo.tickerid, "M", high[1], barmerge.gaps_off, barmerge.lookahead_on)
tl_m = security(syminfo.tickerid, "M", low[1], barmerge.gaps_off, barmerge.lookahead_on)
tc_m = security(syminfo.tickerid, "M", close[1], barmerge.gaps_off, barmerge.lookahead_on)
// weekly Pivot Range
mP = (th_m + tl_m + tc_m) / 3
mBC = (th_m + tl_m)/2
mTC = (mP - mBC) + mP
// Resistance Levels
mR3 = th_m + 2*(mP - tl_m)
mR2 = mP + (th_m - tl_m)
mR1 = (mP * 2) - tl_m
// Support Levels
mS1 = (mP * 2) - th_m
mS2 = mP - (th_m - tl_m)
mS3 = tl_m - 2*(th_m - mP)
//showmonthlyCPR
plot (showmonthlyCPR ? mP : na, title="Monthly Pivot", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showmonthlyCPR ? mTC : na, title="Monthly TC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showmonthlyCPR ? mBC : na, title="Monthly BC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (showmonthlyCPR ? mS1 : na, title="Monthly S1", linewidth=1, color=color.green, style=plot.style_circles)
plot (showmonthlyCPR ? mS2 : na, title="Monthly S2", linewidth=1, color=color.green, style=plot.style_circles)
plot (showmonthlyCPR ? mS3 : na, title="Monthly S3", linewidth=1, color=color.green, style=plot.style_circles)
plot (showmonthlyCPR ? mR1 : na, title="Monthly R1", linewidth=1, color=color.orange, style=plot.style_circles)
plot (showmonthlyCPR ? mR2 : na, title="Monthly R2", linewidth=1, color=color.orange, style=plot.style_circles)
plot (showmonthlyCPR ? mR3 : na, title="Monthly R3", linewidth=1, color=color.orange, style=plot.style_circles)
// show monthly high low
plot (showmonthlyHL ? th_m : na, title="Monthly High", linewidth=2, color=color.black, style=plot.style_cross)
plot (showmonthlyHL ? tl_m : na, title="Monthly Low", linewidth=2, color=color.black, style=plot.style_cross)
// Calculate Tomorrow's CPR
// Get High, Low and Close
th_d = security(syminfo.tickerid, "D", high, barmerge.gaps_off, barmerge.lookahead_on)
tl_d = security(syminfo.tickerid, "D", low, barmerge.gaps_off, barmerge.lookahead_on)
tc_d = security(syminfo.tickerid, "D", close, barmerge.gaps_off, barmerge.lookahead_on)
// Pivot Range
tP = (th_d + tl_d + tc_d) / 3
tTC = (th_d + tl_d)/2
tBC = (tP - tTC) + tP
// Resistance Levels
tR3 = th_d + 2*(tP - tl_d)
tR2 = tP + (th_d - tl_d)
tR1 = (tP * 2) - tl_d
// Support Levels
tS1 = (tP * 2) - th_d
tS2 = tP - (th_d - tl_d)
tS3 = tl_d - 2*(th_d - tP)
disp_tomorrowcpr = input(title="Show Tomorrow Pivots ?", type=input.bool, defval=false)
plot (disp_tomorrowcpr ? tP : na, title="Tomorrow Pivot", linewidth=1, color=color.blue, style=plot.style_circles)
plot (disp_tomorrowcpr ? tTC : na, title="Tomorrow TC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (disp_tomorrowcpr ? tBC : na, title="Tomorrow BC", linewidth=1, color=color.blue, style=plot.style_circles)
plot (disp_tomorrowcpr ? tS1 : na, title="Tomorrow S1", linewidth=1, color=color.green, style=plot.style_circles)
plot (disp_tomorrowcpr ? tR1 : na, title="Tomorrow R1", linewidth=1, color=color.orange, style=plot.style_circles)

Related

R plotly line color by value range

I would like to make this kind of graph (here from Our World In data ) where the line color varies by value range.
edit : adding a screenshot to make it clearer :
With plotly, I found this example but working with type = scatter and mode = markers plot and not with lines:
x <- seq(from = -2,
to = 2,
b = 0.1)
y <- sin(x)
p11 <- plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "markers",
marker = list(size = 10,
color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
is there any ways to use the colorRampPalette or values range but with line (actually it's a time series)
x <- seq(from = -2,
to = 2,
b = 0.1)
y <- sin(x)
p11 <- plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "lines",
line = list(width = 1,
color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
Thank you
You can, but the more points you have the better it will look. Note that I change the .1 in x, to .001.
library(plotly)
library(RColorBrewer)
x <- seq(from = -2,
to = 2,
b = 0.001)
y <- sin(x)
z = cut(x, breaks = 5, include.lowest = T)
p11 <- plot_ly() %>%
add_lines(x = ~x,
y = ~y,
color = ~z,
colors = colorRampPalette(brewer.pal(10,"Spectral"))(length(x))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
If I change that .001 back to .1, it's a bit ugly! You can see the gaps.

Matplotlib update bbox position

I have a code to make a custom pie chart that moves the annotations when it detects a colision on their bboxes.
I want to move the bbox (and thus the text) to avoid the texting overlaping.
I already detect the colision but when I use the “set_points” method it doesn’t update my figure.
The code is as it follows:
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
wedges, texts = ax.pie(
np.array(values) / sum(values),
wedgeprops=dict(width=0.5),
startangle=startAngle,
colors=color_map,
)
# bbox_props=dict(facecolor='none', edgecolor='none')
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"), bbox=bbox_props, zorder=0, va="center")
annot_bbox_list = []
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1) / 2.0 + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
actual_annot = ax.annotate(
labels[i] + f" {values[i]:.1%}",
xy=(x, y),
xytext=(1.35 * np.sign(x), 1.4 * y),
horizontalalignment=horizontalalignment,
**kw,
)
actual_bbox = actual_annot.get_window_extent(renderer=fig.canvas.get_renderer())
for (annot, bbox) in annot_bbox_list:
intersect, move = bbox_intersection(bbox, actual_bbox, margin=10)
if intersect:
print(f'{annot.get_text()} e {actual_annot.get_text()} intersectam, movendo a segunda em {move}')
#fig.canvas.draw()
points = actual_bbox.get_points()#.copy()
print('pontos da caixa2 :\n {}'.format(points))
points[0][1] += move
points[1][1] += move
print('pontos novos da caixa2 :\n {}'.format(points))
renderer=fig.canvas.get_renderer()
#actual_annot.update_positions(renderer)
#fig.canvas.draw()
actual_bbox.set_points(points)
fig.draw(renderer)
annot_bbox_list.append((actual_annot, actual_bbox))
diff += np.sign(x)
dict_angulos[startAngle] = diff

plt.savefig saves a blank image

My code is the following:
def distplot_stripplot_buy_signal_3(y_train, y_dev, y_test, y, plot_data_stripplot_distplot, performance_metrics_3_test,
performance_metrics_3_plus_day_train):
fig, axs = plt.subplots(2,1, figsize = (18, 18))
path = 'D:\\DIGITAL_LIBRARY\\Elpis\\cu2003\\Eddie\\2\\'
n_train = y_train.shape[0]
n_dev = y_dev.shape[0]
n_test = y_test.shape[0]
n_all = n_train + n_dev + n_test
start_forecasting_horizon = y.iloc[n_all:n_all+1].index.to_series().dt.strftime('%Y-%m-%d %H-%M-%S').iloc[0]
end_forecasting_horizon = y.iloc[n_all+300:n_all+301].index.to_series().dt.strftime('%Y-%m-%d %H-%M-%S').iloc[0]
timespan_forecasting_horizon = round((y.iloc[n_all+300:n_all+ 1+300].index.to_series().iloc[0] - \
y.iloc[n_all:n_all+1].index.to_series().iloc[0]).total_seconds())
sns.distplot(plot_data_stripplot_distplot.query('y_test == 1').y_test_pred, color = '#0571b0',
label = 'Price rose in the next 3 mnutes',
ax = axs[0])
sns.distplot(plot_data_stripplot_distplot.query('y_test == 0').y_test_pred, color = '#e31a1c',
label = 'Price did not increase in the next 3 mnutes',
ax = axs[0])
axs[0].axvline(performance_metrics_3_test.query('fbeta==fbeta.max()', engine = 'python').index[-1],\
lw = 4, color = 'black', label = 'optimal threshold using buy_signal_3 on the Test set')
axs[0].axvline(performance_metrics_3_plus_day_train.query('fbeta==fbeta.max()', engine = 'python').index[-1],\
lw = 4, color = 'gray', label = 'optimal threshold using buy_signal_3_plus_day on the Train set')
axs[0].legend()
axs[0].set_title(f'Distribution of Probability Scores by Class \n \
What is the probability to Profit in the next3 to 5 minutes -- if you buy now', fontsize = 18)
axs[0].set_xlabel('Predicted Probability that the Price will rise in the next 3-5 minutes')
sns.stripplot(x = 'y_test', y = 'y_test_pred', data = plot_data_stripplot_distplot , ax = axs[1])
axs[1].axhline(performance_metrics_3_test.query('fbeta==fbeta.max()', engine = 'python').index[-1],\
lw = 4, color = 'black', label = 'optimal threshold using buy_signal_3 on the Test set')
axs[1].axhline(performance_metrics_3_plus_day_train.query('fbeta==fbeta.max()', engine = 'python').index[-1],\
lw = 4, color = 'gray', label = 'optimal threshold using buy_signal_3_plus_day on the Train set')
axs[1].set_title(f'Distribution of Probability Scores by Class \n \
What is the probability to Profit in the next 3-5 minutes -- if you buy now', fontsize = 18)
axs[1].set_xlabel('Ground Truth Outcome \n 0 = The Price did not rise, 1 = Price rose')
axs[1].set_ylabel('Predicted Probability of a Price \n rise in the next 3-5 minutes')
axs[1].legend()
fig.subplots_adjust(wspace=0.1, hspace = 0.8)
plt.tight_layout()
contract = y_train.name[1]
number_of_rows_train = y_train.shape[0]
day = y_train.index.to_series().dt.day.iloc[0]
start_time = performance_metrics_3_plus_day_test.start_time.iloc[0]
end_time = performance_metrics_3_plus_day_test.end_time.iloc[0]
duration = performance_metrics_3_plus_day_test.duration.iloc[0]
contract = y_train.name[1]
plt.suptitle(f'Distplot and Stripplot of Probabilities by Class --Ground Truth: buy_signal_3 \n \
contract : {contract} -- day : {day} \n \
forecasting horizon : from: {start_forecasting_horizon} - to : {end_forecasting_horizon} -- \
timespan of forecasting horizon in seconds :{timespan_forecasting_horizon} \n \
Number of timestamps in Train Set: {number_of_rows_train}, Time Span of Test Set : {duration} \n \
Start Time of Test Set: {start_time}, End Time of Test Set: {end_time}', fontsize = 20, y = 1.1)
plt.savefig(\
f'{path}Distplot and Stripplot of Probabilities by Class --Ground Truth: buy_signal_3\
-contract_{contract}_number_of_timesteps_in_train_set{number_of_rows_train}.pdf')
plt.show()
Then calling the function plots this picture inside the Jupyter Notebook:
distplot_stripplot_buy_signal_3(y_train, y_dev, y_test, y, plot_data_stripplot_distplot, performance_metrics_3_test,performance_metrics_3_plus_day_train)
[![enter image description here][1]][1]
But the file saved is blank:
Why does this occur and how can I correct it?
Well if you want to fix your problem input this in your code. I don't know exactly why it happens but it is fixed by this plt.show() should come before plt.savefig()
Explanation: plt.show() clears the whole thing, so anything afterwards will happen on a new empty figure.
fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig(y_train, y_dev, y_test, y, plot_data_stripplot_distplot, dpi=100)

Draw a line of certain length in Pine Script

I'm trying to develop a Pivot Points indicator on Trading View v4.0 and an issue I'm facing is that the pivot lines are drawn only up to the current bar. The behavior I want is that I want the line to extend for the duration of the period. For example, the weekly pivot line should extend from Monday to Sunday even if today is Monday.
Below is the code I'm using as well as the result:
// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
ch = 0
if(res == 'Y')
t = year(time('D'))
ch := change(t) != 0 ? 1 : 0
else
t = time(res)
ch := change(t) != 0 ? 1 : 0
ch
bars_since_week = 0
bars_since_week := is_newbar(pp_res_week) ? 0 : bars_since_week[1] + 1
vpp_p_week = line.new(bar_index[min(bars_since_week, 300)], PP_week, bar_index, PP_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vs1_p_week = line.new(bar_index[min(bars_since_week, 300)], S1_week, bar_index, S1_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vs2_p_week = line.new(bar_index[min(bars_since_week, 300)], S2_week, bar_index, S2_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vs3_p_week = line.new(bar_index[min(bars_since_week, 300)], S3_week, bar_index, S3_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vr1_p_week = line.new(bar_index[min(bars_since_week, 300)], R1_week, bar_index, R1_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vr2_p_week = line.new(bar_index[min(bars_since_week, 300)], R2_week, bar_index, R2_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
vr3_p_week = line.new(bar_index[min(bars_since_week, 300)], R3_week, bar_index, R3_week, color=color.black, width = 2, style = line.style_solid, extend = extend.none)
Also, below is the behavior I would expect - notice the longer lines:
It's not a simple matter, at least not the way it's done here ) There is perhaps a better way, but haven't figured out any:
You'll need to work with xloc = xloc.bar_time to be able to draw a line in the future when you need to.
Use the f_avgDilationOf() from the PineCoders MTF Selection Framework to know the average number of chart bars in the dilation of the higher TF (on a 24/7 market, this would be 7 on a daily chart if HTF=1W).
Figure out if current chart bars (current being the one the script is executing on) are included in the last dilation of the HTF. We need this info because when that is true, we will project the line in the future.
//#version=4
study("Periodic lines", "", true)
htf = input("W", type = input.resolution)
// Returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history).
f_avgDilationOf(_res) =>
// _res: resolution of any TF (in "timeframe.period" string format).
b = barssince(change(time(_res)))
cumTotal = cum(b == 0 ? b[1] + 1 : 0)
cumCount = cum(b == 0 ? 1 : 0)
cumTotal / cumCount
// Period change detection.
pChange(res) =>
change(time(res == 'Y' ? 'D' : res))
// Get some previous value from last HTF period.
pHi = security(syminfo.tickerid, htf, high[1], lookahead = barmerge.lookahead_on)
// Verify if current charts bars are part of the last dilation of HTF.
lastPBar = security(syminfo.tickerid, htf, barstate.islast, lookahead = barmerge.lookahead_on)
// Get avg no of chart bars in one dilation of HTF.
dilation = round(f_avgDilationOf(htf))
timeDelta = time - time[1]
var line pHiLine = na
// Holds bar index where a new line is created.
var pHiBar = 0
if pChange(htf)
// Extend old line for the last bar before creating a new one.
line.set_xy2(pHiLine, time, pHi[1])
// Save bar index on transition.
pHiBar := bar_index
// Create new line.
pHiLine := line.new(time, pHi, time + timeDelta, pHi, xloc.bar_time, color = color.black, width = 2)
// Make type of the 2 `if` blocks the same.
float(na)
else
// We are not on a transition; prolong line until next transition.
line.set_xy2(pHiLine, time, pHi)
float(na)
// If we are in the last bars of the HTF resolution's dilation, project line into the future with remaining bars in average no of bars in dilation.
if lastPBar
line.set_xy2(pHiLine, time + (timeDelta * (dilation - (bar_index - pHiBar))), pHi)
Caveat: Haven't forward-tested this, so unsure how it'll perform in those conditions.

Seaborn boxplot whiskers are missing from just one category

I've been using the Seaborn library to plot box plots. In one instance, I see that the whiskers are randomly missing from one of my categorical variables.
fig, ax = plt.subplots(1, 1, figsize = (60,30))
plt.axhline(y = 0, color = 'k', linestyle = ':', linewidth = 2)
ax = sns.boxplot(x = 'Neighborhood', y = 'Price difference', data = sf_data_residuals_neighborhoods,
showfliers = False, order = list(neighborhood_order_residuals['Neighborhood']), linewidth = 5)
ax = sns.stripplot(x = 'Neighborhood', y = 'Price difference', data = sf_data_residuals_neighborhoods,
order = list(neighborhood_order_residuals['Neighborhood']), jitter = 0.25, size = 15,
linewidth = 3, edgecolor = 'black', alpha = 0.5)
# set axis properties
plt.xticks(rotation=45, fontname = 'Helvetica', fontsize = 42, ha = 'right')
plt.yticks(fontname = 'Helvetica', fontsize = 42)
plt.xlabel('San Francisco neighborhood', fontsize = 55, fontname = 'Arial', fontweight = 'bold')
plt.ylabel('Actual - predicted price ($M)', fontsize = 55, fontname = 'Arial',
fontweight = 'bold')
scale = 1000000; ax.set_ylim(-1000000, 3000000); ax.yaxis.labelpad = 25
ticks = ticker.FuncFormatter(lambda y, pos: '{0:g}'.format(y/scale))
ax.xaxis.set_tick_params(width = 3, length = 15)
ax.yaxis.set_tick_params(width = 3, length = 15)
ax.yaxis.set_major_formatter(ticks)
plt.setp(ax.spines.values(), linewidth = 3)
This produces the desired plot, but appears to leave out whiskers for the Potrero Hill category:
I've tried manually stipulating the default whis = 1.5 setting in sns.boxplot() but this does not make the missing whiskers appear.
Any idea what might be causing this?

Resources