tradingview pine script error "cannot use 'plot' in a local scope" - plot

I am trying to write a simple if-then-else statement using the Pine language under Tradingview. What the code does is based upon user input.
If the box is checked, the plot the line.
If the box is not checked do not plot the line.
This is the code I have:
notPlot = -2000
var ch382= input(true, ".382")
if ch382
plot( ch382? bottom + diff * .382: noPlot, title="fib-.236", linewidth=3, color=color.orange )
How can I write this in a proper way?
If I try to run it, I get: “cannot use 'plot' in a local scope”
Any assistance would be greatly appreciated.
ETA: I found this thread below
How to put plot statement inside if statement
but -
what I need to do is to plot if the box is checked and ~not plot~ if the box is not checked.

ETA: figured out the issue. One would use "na" (in the case of plotting) to note that the line should not be displayed - my mistake ...
var ch382 = input(true, ".382")
plot( ch382? bottom + diff * .382: na, title="fib-.382", linewidth=3, color=color.orange )

Related

Multiple altair charts generated by the same cell

I have a list of pandas dataframes I named entries, which I want to visualize after running code from the same cell. Below is the code I used :
alt.data_transformers.disable_max_rows()
for entry in entries :
entry['ds'] = entry.index
entry['y'] = entry['count']
entry['floor'] = 0
serie = alt.Chart(entry).mark_line(size=2, opacity=0.7, color = 'Black').encode(
x=alt.X('ds:T', title ='date'),
y='y'
).interactive().properties(
title='Evolution of '+entry.event.iloc[0]+' events over time'
)
alt.layer(serie)\
.properties(width=870, height=450)\
.configure_title(fontSize=20)
When i run the same code out of the 'for' loop, I get to see the one chart that corresponds to one dataframe, but once I run the code above, I don't get any graphs at all.
Does anyone know why It's not working or how to solve this issue?
TLDR: use chart.display()
Unless a chart appears at the end of the cell, you must manually display it.
By analogy, if you run
x + 1
by itself, Python will display the result. However, if you run
for x in range(10):
x + 1
Python will not display anything, because the last statement in the cell (in this case the for loop) has no return value to display. Instead you have to write
for x in range(10):
print(x + 1)
For altair, the mechanism is similar: if the chart is defined in the last statement in the cell, it will be automatically displayed. Otherwise, you have to manually trigger the display, which you can do using the display method:
for i in range(10:
chart = alt.Chart(...)
chart.display()
For more information on display troubleshooting in Altair, see https://altair-viz.github.io/user_guide/troubleshooting.html

How to suppress unwanted Plot figure object information in Jupyter Notebook

I want to suppress any text output when I run Jupyter Notebook cell. Specifically I output some figures and each is accompanied by something like:
<Figure size 432x288 with 0 Axes>
I have seen that if I put a ; at the end of a line, it should suppress the output, but it is not working in my case.
The code:
for i in tqdm_notebook(range(data.shape[0])):
print('BIN:',i)
fig = plt.figure(figsize=(15,4))
plt.tight_layout()
gs = gridspec.GridSpec(2,1)
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(match[window_begin:window_end],'k')
plt.vlines(i,-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05,'r',linewidth=4,alpha=0.2)
ax1.set_xlim(0-1,post_bin_match_median[window_begin:window_end].shape[0])
ax1.set_ylim(-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05)
plt.tick_params(axis='y', which='both', left=True, labelleft=False)
ax1.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
plt.grid()
ax2 = fig.add_subplot(gs[1, 0])
fig.subplots_adjust(hspace=0.0)
ax2.plot(gp_mjds[:],gp_data[i,:],'k')
ax2.errorbar(remain, all[i,:], yerr=all_noise[i], fmt=".k", capsize=0);
ax2.fill_between(gp[:], gp2[i,:] - np.sqrt(gp_var[i,:]), gp2[i,:] + np.sqrt(gp_var[i,:]),color="k", alpha=0.2)
ax2.set_xlim(gp[0],gp[-1])
plot_y_min = np.minimum(np.min(gp2[:,:] - np.sqrt(gp_var[:,:])),np.min(all_profile_residuals[:,:]-y_noise))
plot_y_max = np.maximum(np.max(gp2[:,:] + np.sqrt(gp_var[:,:])), np.max(all[:,:]+y_noise))
ax2.set_ylim(plot_y_min,plot_y_max)
plt.grid()
plt.show()
plt.clf()
plt.close(fig);
The semi-colon would work if the typical output from the last line of the cell is what you are trying to suppress. As succinctly summarized by #kynan here, "The reason this works is because the notebook shows the return value of the last command. By adding ; the last command is "nothing" so there is no return value to show."
However, you have a loop inside a cell generating objects.
The culprit seems to be plt.clf(). Comment out that line or remove it from your code, and it should fix it.
Plus, I'd remove plt.show() as it isn't necessary when plt.clf() is removed, and I am seeing it being in the loop causing fig = plt.figure(figsize=(15,4)) to also show output text like you posted in your issue.
(I'll add for others looking at this later, that it is important have %matplotlib inline or %matplotlib notebook at the start of the cell (or at the start of a cell somewhere above this one.))
A complete guide on how to hide or remove content in Jupyter is available from the official documentation: https://jupyterbook.org/interactive/hiding.html#
For removing the single output line, you can tweak the command lines by adding a _ = [command ] assignment as suggested in this blog: https://www.tutorialguruji.com/python/suppress-output-in-matplotlib/.
The underscore there is a throwaway variable, actually an unidentified variable "when not in interactive mode". See the official Python documentation: https://docs.python.org/3.9/reference/lexical_analysis.html#reserved-classes-of-identifiers

Dimension value_format callback not working properly

This is a new question related to a previous question I asked:
holoviews can't find flexx when using a Dimension value_format callback
Thanks to downgrading my version of flexx, I am no longer getting the warning message. However, the callback function is not working. Here is the code:
%%output size=200
%%opts Curve [width=600 height=250] {+framewise}
%%opts Curve.Load.Ticket (color='red')
def xformat(x):
# update the default tick label to append an 'a'
new = x + 'a'
return(new)
kdims=hv.Dimension('Day Section', label='Week Day and Hour', value_format=xformat)
tload = hv.Curve(simple_pd,vdims=[('Max Ticket Load', 'Maxiumum Ticket Load')],kdims=kdims,group='Load',label='Ticket')
tload
When I run with the above code, I expect to see the same amount of x axis tick labels, however, each label should have an 'a' appended to the end. However, what I am seeing is no rendering of the element at all in my notebook. I have tried a number of variations of modifying the value, and the same thing happens.
Strangely, the issue appears to be the use of the variable name new in the xformat function. If I change the name of the variable it works fine. It doesn't appear as though new is a reserved work in python though, so I am not sure why its causing a problem.
Note that using the matplotlib extension does not have the same problem, only Bokeh.

How to create a new command line?

I have a very simple question, How to create a new command line?? my code is
barplot(Danes, col = rainbow(12), beside = T)
legend(locator(1), legend = rownames(Danes), col = rainbow(12), pch = rep(18, 12))
But when I click enter, it creates the graph but doesn't give me a new command line (<) or gave me the legend so I guess I must have messed the legend command up. how do I basically restart and keep my data and code?
Your problem is locator(1). R is waiting for you to click somewhere in the plot window (to decide where to put the legend). Alternatively, if you want to cancel the action (from ?locator):
For the usual ‘X11’ device the identification process is
terminated by pressing any mouse button other than the first. For
the ‘quartz’ device the process is terminated by pressing the
‘ESC’ key.
(it doesn't say what to do for a Windows graphics device, but I'd try ESC and other mouse buttons and maybe Ctrl-C).

matplotlib mathtext does not work

I'm doing a hist plot and I want some numbers shown in the plot, so I put in a text box using mathtext for the text, but I doesn't work and I can't see why.
a = [2086., 360.5, 1000.]
b = [977., 37., 498.]
c = [4512., 690., 378.]
textstr = r'$\per50=%.2f$\n$\per16=%.2f$\n$\per84=%.2f$'%(a[0],b[0],c[0])
# these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.75)
# place a text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
verticalalignment='top', bbox=props)
At the end of my figure I'm getting this error:
matplotlib.pyparsing.ParseFatalException: Expected end of math '$'
$\per50=2086.00$\n$\per16=977.00$\n$\per84=4512.00$ (at char 0), (line:1, col:1)
I hope you can help me!
You are getting that error because the command $\per$ does not exist. Is that a latex command you defined? If you set the matplotlib parameter text.usetex=True, it is possible to set a latex preamble and define commands there, e.g.:
rc('text', usetex=True)
rc('text.latex', preamble='something')
But I don't think this can be used to define new commands (and the use of preamble is discouraged). So your best bet is to write explicitly in matplotlib whatever \per stands for.

Resources