trendline in tradingview with a text in it (pinescript) - text

In tradingview, we can draw a trendline and put text on it, set a template, etc...
is it possible with the pine script to draw a line and assign either a template or a text to the line ? or do we need to add the text in the label absolutelyenter image description here

Yes, it is possible. Please read this for more information.
Here is an example of pivot points:
//#version=4
study("Pivot Points Standard", overlay=true)
higherTF = input("D", type=input.resolution)
prevCloseHTF = security(syminfo.tickerid, higherTF, close[1], lookahead=true)
prevOpenHTF = security(syminfo.tickerid, higherTF, open[1], lookahead=true)
prevHighHTF = security(syminfo.tickerid, higherTF, high[1], lookahead=true)
prevLowHTF = security(syminfo.tickerid, higherTF, low[1], lookahead=true)
pLevel = (prevHighHTF + prevLowHTF + prevCloseHTF) / 3
r1Level = pLevel * 2 - prevLowHTF
s1Level = pLevel * 2 - prevHighHTF
var line r1Line = na
var line pLine = na
var line s1Line = na
if pLevel[1] != pLevel
line.set_x2(r1Line, bar_index)
line.set_x2(pLine, bar_index)
line.set_x2(s1Line, bar_index)
line.set_extend(r1Line, extend.none)
line.set_extend(pLine, extend.none)
line.set_extend(s1Line, extend.none)
r1Line := line.new(bar_index, r1Level, bar_index, r1Level, extend=extend.right)
pLine := line.new(bar_index, pLevel, bar_index, pLevel, width=3, extend=extend.right)
s1Line := line.new(bar_index, s1Level, bar_index, s1Level, extend=extend.right)
label.new(bar_index, r1Level, "R1", style=label.style_none)
label.new(bar_index, pLevel, "P", style=label.style_none)
label.new(bar_index, s1Level, "S1", style=label.style_none)
if not na(pLine) and line.get_x2(pLine) != bar_index
line.set_x2(r1Line, bar_index)
line.set_x2(pLine, bar_index)
line.set_x2(s1Line, bar_index)

Related

how to grey out other lines using Mouse hover?

I'm trying to grey out other lines when i hover over one of them so far i have this:
from sklearn import datasets
data_wine = datasets.load_wine (as_frame = True).frame
new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
hover = alt.selection(
type="single", on="mouseover", fields=["variable"], nearest=True
)
lineplot = alt.Chart(new_data).mark_line().encode(
alt.X("variable:N"),
alt.Y("value:Q"),
alt.Color ('target:N'),
alt.Detail ('index:N'),
).properties(width = 1000)
# nearest point
point = lineplot.mark_circle().encode(
opacity=alt.value(0)
).add_selection(hover)
# highlight
singleline = lineplot.mark_line().encode(
size=alt.condition(~hover, alt.value(0.5), alt.value(3))
)
point+singleline
it looks like this and while hovering the mouse the size changes and i couldn't replace size with Color:
how can i achieve this?
new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
highlight = alt.selection(type='single', on='mouseover', fields=['target'], nearest=False, bind='legend')
selection = alt.selection_multi(fields=['target'], bind='legend', on='mouseover')
lineplot=alt.Chart(new_data).mark_line().encode(
alt.X("variable:N"),
alt.Y("value:Q"),
alt.Color ('target:N'),
alt.Detail ('index:N'),
).properties(width = 1000)
# nearest point
point = lineplot.mark_circle().encode(
opacity=alt.value(0)
).add_selection(highlight)
#highlight
singleline = lineplot.mark_line().encode(
opacity=alt.condition(selection, alt.value(0.7), alt.value(0.03))
#size=alt.condition(~highlight, alt.value(1), alt.value(3))
).add_selection(selection)
point + singleline

Unable to plot the data point using Bokeh and Python- shows empty layout

I have a dataframe that has the following values. I am looking to plot them on an interactive graph using Bokeh.
locs = ['a', 'b', 'c']
prime_vals = [1000, 54, 457]
sub_vals = [0, 112, 34]
my_dict = {'loc' : locs, 'prime' : prime_vals, 'sub' : sub_vals}
df = pd.DataFrame(my_dict)
df
*I want the 'prime' and 'sub' to be two different checkboxes in the visualization. One could select both of them (prime and sub) and see the values with respect to 'loc' or see their values individually.
Below is the code I have, but it gives me the below image only- without any values.
p = figure(plot_width=1200, plot_height = 800)
aline = p.line(df["locs"], df['prime_vals'], line_width=2,
color=Viridis4[0])
bline = p.line(df["locs"], df['sub_vals'], line_width=2,
color=Viridis4[3])
p.yaxis.axis_label = 'x - axis label '
p.xaxis.axis_label = 'y - axis label'
legend = Legend(items=[("Prime", [aline]),("Sub", [bline])], location=(0, 450))
t = Title()
t.text = 'Prime and sub roles over various offices'
p.title = t
p.add_layout(legend, 'left')
checkboxes = CheckboxGroup(labels=list(['Prime', 'Sub']), active=[0, 1])
callback = CustomJS(code="""aline.visible = false; // aline and etc.. are
bline.visible = false; // passed in from args
// cb_obj is injected in thanks to the callback
if (cb_obj.active.includes(0)){aline.visible = true;}
// 0 index box is aline
if (cb_obj.active.includes(1)){bline.visible = true;} """,
args={'aline': aline, 'bline': bline})
checkboxes.js_on_click(callback)
output_file('some_name.html')
show(row(p, checkboxes))
I am unable to understand why the data points are not being plotted.

Bokeh: Is there a way to set the styling for all figures at once?

I am coding for 20+ tabs to plot similar parameters and have been writing the styling for each figure separately. Is there a way to set the styling all at once for all figures?
p = figure(tools=TOOLS, x_axis_type='datetime',plot_height=400, plot_width=700,
outline_line_color = 'gray',
y_axis_label = 'Volts',
y_range = DataRange1d()
)
# Setting the second y axis range name and range
#p.extra_y_ranges = {"foo": Range1d(start=0, end=0.000006)}
p.extra_y_ranges = {"foo": DataRange1d()}
# Adding the second axis to the plot.
p.add_layout(LinearAxis(y_range_name="foo"), 'right')
a1=p.line(x='Time', y='340', line_color="darkcyan", line_width=1, source=source)
a11 = p.line(x='Time',y='StdDev', line_color = 'red', line_width=1, y_range_name="foo", source=source)
p.y_range.renderers=[a1]
p.extra_y_ranges['foo'].renderers = [a11]
tooltips=[( "Time", "#Time{%H:%M:%S}"),
("Y-value", "$y")]
formatt ={'Time':'datetime'}
p.add_tools(HoverTool(tooltips=tooltips, formatters=formatt, mode = 'mouse'))
p.title.text = "Plot Title "
p.title.text_color = "gray"
p.title.text_font = "arial"
p.title.text_font_style = "bold"
p.xgrid[0].grid_line_color=None
p.ygrid[0].grid_line_alpha=0.5
p.xaxis.axis_label = 'TimeStamp'
Following my way, I would essentially need to repeat above code 20+ times for each tab.

How to fix 'Dropdown Menu Read' Error in Plotly Dash

I have tried to re-create the following example Towards Data Science Example shown on the web
I have written the following code which I modified to this:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
# Step 1. Launch the application
app = dash.Dash()
# Step 2. Import the dataset
filepath = 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
st = pd.read_csv(filepath)
# range slider options
st['Date'] = pd.to_datetime(st.Date)
dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17',
'2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']
features = st.columns[1:-1]
opts = [{'label' : i, 'value' : i} for i in features]
# Step 3. Create a plotly figure
trace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'],
name = 'AAPL HIGH',
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
layout = go.Layout(title = 'Time Series Plot',
hovermode = 'closest')
fig = go.Figure(data = [trace_1], layout = layout)
# Step 4. Create a Dash layout
app.layout = html.Div([
# a header and a paragraph
html.Div([
html.H1("This is my first dashboard"),
html.P("Dash is so interesting!!")
],
style = {'padding' : '50px' ,
'backgroundColor' : '#3aaab2'}),
# adding a plot
dcc.Graph(id = 'plot', figure = fig),
# dropdown
html.P([
html.Label("Choose a feature"),
dcc.Dropdown(
id='opt',
options=opts,
value=features[0],
multi=True
),
# range slider
html.P([
html.Label("Time Period"),
dcc.RangeSlider(id = 'slider',
marks = {i : dates[i] for i in range(0, 9)},
min = 0,
max = 8,
value = [1, 7])
], style = {'width' : '80%',
'fontSize' : '20px',
'padding-left' : '100px',
'display': 'inline-block'})
])
])
# Step 5. Add callback functions
#app.callback(Output('plot', 'figure'),
[Input('opt', 'value'),
Input('slider', 'value')])
def update_figure(input1, input2):
# filtering the data
st2 = st[(st.Date > dates[input2[0]]) & (st.Date < dates[input2[1]])]
# updating the plot
trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'],
name = 'AAPL HIGH',
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
trace_2 = go.Scatter(x = st2.Date, y = st2[input1],
name = str(input1),
line = dict(width = 2,
color = 'rgb(106, 181, 135)'))
fig = go.Figure(data = [trace_1, trace_2], layout = layout)
return fig
# Step 6. Add the server clause
if __name__ == '__main__':
app.run_server(debug = True)
When I change the feature input, it does not update the plot correctly and does not show the selected features in the plot.
Either there is something wrong with the callback function or the initialization of the graph with the second trace. But I cant figure out where the issue is.
As you are only providing two scatter traces within your callback. From both, one is static for 'AAPL.High'. So you need to limit the dropdown values to Multi=False.
Valid plots are only generated for choosing options like 'AAPL.LOW' and others like dic won't display a second trace. The callback wouldn't terminate if you would keepmulti=True the callback would stil work, if always only one option is selected. The moment you select two or more options the script will fail as it would try to find faulty data for the data return block here:
trace_2 = go.Scatter(x = st2.Date, y = st2[**MULTIINPUT**],
name = str(input1),
line = dict(width = 2,
color = 'rgb(106, 181, 135)'))
Only one column id is allowed to be passed at MULTIINPUT. If you want to introduce more traces please use a for loop.
Change the code to the following:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
# Step 1. Launch the application
app = dash.Dash()
# Step 2. Import the dataset
filepath = 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
st = pd.read_csv(filepath)
# range slider options
st['Date'] = pd.to_datetime(st.Date)
dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17',
'2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']
features = st.columns
opts = [{'label' : i, 'value' : i} for i in features]
# Step 3. Create a plotly figure
trace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'],
name = 'AAPL HIGH',
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
layout = go.Layout(title = 'Time Series Plot',
hovermode = 'closest')
fig = go.Figure(data = [trace_1], layout = layout)
# Step 4. Create a Dash layout
app.layout = html.Div([
# a header and a paragraph
html.Div([
html.H1("This is a Test Dashboard"),
html.P("Dash is great!!")
],
style = {'padding' : '50px' ,
'backgroundColor' : '#3aaab2'}),
# adding a plot
dcc.Graph(id = 'plot', figure = fig),
# dropdown
html.P([
html.Label("Choose a feature"),
dcc.Dropdown(
id='opt',
options=opts,
value=features[0],
multi=False
),
# range slider
html.P([
html.Label("Time Period"),
dcc.RangeSlider(id = 'slider',
marks = {i : dates[i] for i in range(0, 9)},
min = 0,
max = 8,
value = [1, 7])
], style = {'width' : '80%',
'fontSize' : '20px',
'padding-left' : '100px',
'display': 'inline-block'})
])
])
# Step 5. Add callback functions
#app.callback(Output('plot', 'figure'),
[Input('opt', 'value'),
Input('slider', 'value')])
def update_figure(input1, input2):
# filtering the data
st2 = st#[(st.Date > dates[input2[0]]) & (st.Date < dates[input2[1]])]
# updating the plot
trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'],
name = 'AAPL HIGH',
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
trace_2 = go.Scatter(x = st2.Date, y = st2[input1],
name = str(input1),
line = dict(width = 2,
color = 'rgb(106, 181, 135)'))
fig = go.Figure(data = [trace_1, trace_2], layout = layout)
return fig
# Step 6. Add the server clause
if __name__ == '__main__':
app.run_server(debug = True)
I hope this cleared things up and solved your issues. :)

How do I add vertical moving hover line to my plotly chart

I am trying to achieve what is done here: https://www.quantalys.com/Fonds/120955 with javascript in python plotly. I want to add the hover vertical line and the red annotation on the x axis. I have done some searching on goolgle but I couldn't find the the answer I'm looking for. My current chart looks like this:
trace1 = go.Scatter(
x = df1.x,
y = df1.y,
name = "M&G OPTIMAL INCOME FD EUR AH ACC",
hoverinfo= 'name',
opacity=0.7,
mode = 'lines',
line = dict(
color = ('rgb(2, 12, 245)'),
width = 1,
),
)
trace2 = go.Scatter(
x = df2.x,
y = df2.y,
opacity=0.7,
name = "Alloc Flexible Prudent Monde",
hoverinfo= 'name',
mode = 'lines',
line = dict(
color = ('rgb(67, 45, 24)'),
width = 1,
)
)
trace3 = go.Scatter(
x = df3.x,
y = df3.y,
name = "25% MSCI World + 75% ML Global",
hoverinfo= 'name',
mode = 'lines',
opacity=0.7,
line = dict(
color = ('rgb(205, 12, 24)'),
width = 1,
)
)
layout = go.Layout(
xaxis=dict(
showline=True,
showgrid=True,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
mirror=True,
),
yaxis=dict(
showline=True,
showgrid=True,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
mirror=True,
),
showlegend=True,
)
data= [trace1, trace2,trace3]
fig = dict(data=data, layout=layout)
iplot(fig, filename='line-mode')
Add this to your layout definition.
showlegend = True,
hovermode = 'x'
Add this to your xaxis definition.
showspikes = True,
spikemode = 'across',
spikesnap = 'cursor',
showline=True,
showgrid=True,
...
And add this to your layout definition:
spikedistance = -1,
xaxis=dict(...
Please refer to this post and the documentation by plotly. :)
EDIT
You ask for the x-axis lable. Please use
spikemode = 'across+toaxis'
Additionally I would suggest to use
spikedash = 'solid'
because it is better fitting your example.

Resources