s2 = request.security(syminfo.tickerid, tfD2, outD2, gaps=barmerge.gaps_on)
plot(s2, title="Daily 20 EMA", color=color.purple,linewidth=2)
I want to display this only on "Daily" TF, in weekly, monthly or lower than Daily TF, I want to hide this or not plot it at all. Can I do it via script?
I have tried using timeframe.isdaily on plot stmt but it didn't work.
drawEMA2 = timeframe.isintraday and timeframe.isweekly and timeframe.ismonthly
s2 = request.security(syminfo.tickerid, tfD3, outD3, gaps=barmerge.gaps_on)
plot(series=drawEMA2 ? s2 :na, title="Daily 50 EMA",color=color.fuchsia,linewidth=2)
This works, just figured out after posting!
Related
I am working on arima modeling. The data has hourly granularity - taken from 1st May 2022 till 8th June 2022. I am trying to do forecasting for next 30 days i.e 720 hours. I am facing trouble & getting confused with the below doubts. If anybody could provide pointers then it will be great.
Tried plotting the raw data & found no trend, and seasonality
a) Checked with seasonal_decomposition() with a few period values with period=1 (correct with my understanding that season should be 0)
b) period = 12 (just random - but why it is showing some seasons?. Even if I pot without period for which default value is 7, it still shows season - why?)
Plotted this graph with seasonality value False as in the raw plot I do not see any seasons/trend & getting the below plot. How & what should be concluded???
Then I thought of capturing this season thing through resampling by plotting daily graph and getting further confused.
a) period - 7 (default for seasonal_decomposition), again I can see seasonality of 4 days when the raw plot do not show seasons.
The forecasting for this resampled (daily) data is below
I am extremely clueless now as to what to see. The more I am reading the more I am getting confused.
Below is the code that I am using.
df=pd.read_csv('~/Desktop/gru-scl/gru-scl-filtered.csv', index_col="time")
del df["Index"]
df.index=pd.to_datetime(df.index)
model = pm.auto_arima(df.bps, start_p=0, start_q=0,
test='adf', # use adftest to find optimal 'd'
max_p=3, max_q=3, # maximum p and q
m=24, # frequency of series
d=None, # let model determine 'd'
seasonal=False, # No Seasonality
start_P=0,
D=0,
trace=True,
error_action='ignore',
suppress_warnings=True,
stepwise=True)
f_steps=720
fc, confint = model.predict(n_periods=f_steps, return_conf_int=True)
fc_index = np.arange(len(df.bps), len(df.bps)+f_steps)
val=0
for f in fc:
val = val+f
mean = val/f_steps
print(mean)
# make series for plotting purpose
fc_series = pd.Series(fc, index=fc_index)
lower_series = pd.Series(confint[:, 0], index=fc_index)
upper_series = pd.Series(confint[:, 1], index=fc_index)
# Plot
plt.plot(df.bps, label="Actual values")
plt.plot(fc, color='darkgreen', label="Predicted values")
plt.fill_between(fc_index,
lower_series,
upper_series,
color='k', alpha=.15)
plt.legend(loc='upper left', fontsize=8)
plt.title('Forecast vs Actuals')
plt.xlabel("Hours since 1st May 2022")
plt.ylabel("Bps")
plt.show()
what I want to plot
Hi, I want to visualize results for one A/B test. The experiment tracks 4 metrics, and I want to show them in one plot altogether. The schema of my dataframe is:
test_control | metric1 | metric2 | metric3 | metric4
Does anyone know how to plot, by matplotlib, pandas or seaborn?
Thanks in advance!
I found it's probably easier to be done in R.
In python, I calculated the error bar and then used matplotlib.pyplot.errorbar to plot:
get CI
kpi_map = {'kpi':[], 'mean_diff':[], 'err':[], 'pval':[]}
for col in metrics:
sp1 = df.loc[df['test_control']=='test'][col]
sp2 = df.loc[df['test_control']=='control'][col]
std1 = np.std(sp1, ddof=1)
std2 = np.std(sp2, ddof=1)
mean_diff_std = (std1**2/len(sp1) + std2**2/len(sp2)) **0.5
mean_diff = sp1.mean() - sp2.mean()
kpi_map['kpi'].append(col)
kpi_map['mean_diff'].append(mean_diff)
kpi_map['err'].append(1.96*mean_diff_std)
plot
df_kpi = pd.DataFrame(data = kpi_map)
plt.errorbar(y=df_kpi['kpi'], x=df_kpi['mean_diff'], xerr=df_kpi['err'], fmt='o', elinewidth=2, capsize=4, capthick=2)
I have created this code on pine and I though it would work but is does not. I have no error according to them but when I add the code to the graph I am not able to see where it buys and sells. Furthermore when I try strategy test it is not allowing me to backtest it. It does not show any data.
//#version=4
strategy("Bushiri project",default_qty_type=strategy.percent_of_equity, default_qty_value=2, pyramiding=5, initial_capital=1000, overlay=true)
// MTF analysis
len = input(8, minval=1, title="Length")
src = input(close, title="Source")
out = sma(src, len)
res = input(title="Resolution", type=input.resolution, defval="1D")
s1 = security(syminfo.tickerid, res, out, gaps=true)
plot(s1, color=color.blue)
len2 = input(21, minval=1, title="Length2")
src2 = input(close, title="Source2")
out2 = sma(src, len2)
res2 = input(title="Resolution2", type=input.resolution, defval="1D")
s2 = security(syminfo.tickerid, res2, out2, gaps=true)
plot(s2, color=color.yellow)
//Ema inputs
fastemaLength= input(50, title="EMA Length", minval=1, maxval=200)
slowemaLength= input(200, title="EMA Length", minval=1, maxval=200)
//values
fastemaVal=ema(close, fastemaLength)
slowemaVal=ema(close, slowemaLength)
//plot values
plot(fastemaVal, title="EMA", color=color.red, transp=2)
plot(slowemaVal, title="EMA", color=color.green, transp=2)
// Entry requirement
dcross= s1>s2
ecross=crossover(fastemaVal, slowemaVal)
if(ecross and dcross)
strategy.entry(id="enterbuy", long=true, stop=20, comment="BUY")
//exit requirement
dcross1=s1>s2
ecross1=crossunder(fastemaVal, slowemaVal)
if(ecross1 and dcross1)
strategy.close(id="enterbuy", comment="EXIT")
You might have overlooked the fact that stop= 20 at 'strategy.entry(id="enterbuy", long=true, stop=20, comment="BUY")' will place an order at a price of 20. If you are trying this on the eurusd you will never place a trade because the price has never reaches 20 price. Another thing is that, as Bjorn Mistiaen said, this script rarely places trades. The condition to strategy.entry rarely takes place(specifically the dcross and the dcross1) and both ecross1 and dcross1 have to be true to also close the trade. You might have place a trade but it does not close. Look at your list of trades. Also don't forget to add the script to the chart by clicking "add to chart" at the pine editor
I have created a very basic script in pinescript.
study(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
rc = close
buy_entry = rc[0] > rc[2]
sell_entry = rc[0] < rc[2]
alertcondition(buy_entry, title='BUY')
alertcondition(sell_entry, title='SELL')
plot(buy_entry/10)
The problem is that I get a lot of duplicate alerts. I want to edit this script so that I only get a 'Buy' alert when the previous alert was a 'Sell' alert and visa versa. It seems like such a simple problem, but I have a hard time finding good sources to learn pinescript. So, any help would be appreciated. :)
One way to solve duplicate alters within the candle is by using "Once Per Bar Close" alert. But for alternative alerts (Buy - Sell) you have to code it with different logic.
I Suggest to use Version 3 (version shown above the study line) than version 1 and 2 and you can accomplish the result by using this logic:
buy_entry = 0.0
sell_entry = 0.0
buy_entry := rc[0] > rc[2] and sell_entry[1] == 0? 2.0 : sell_entry[1] > 0 ? 0.0 : buy_entry[1]
sell_entry := rc[0] < rc[2] and buy_entry[1] == 0 ? 2.0 : buy_entry[1] > 0 ? 0.0 : sell_entry[1]
alertcondition(crossover(buy_entry ,1) , title='BUY' )
alertcondition(crossover(sell_entry ,1), title='SELL')
You'll have to do it this way
if("Your buy condition here")
strategy.entry("Buy Alert",true,1)
if("Your sell condition here")
strategy.entry("Sell Alert",false,1)
This is a very basic form of it but it works.
You were getting duplicate alerts because the conditions were fulfulling more often. But with strategy.entry(), this won't happen
When the sell is triggered, as per paper trading, the quantity sold will be double (one to cut the long position and one to create a short position)
PS :You will have to add code to create alerts and enter this not in study() but strategy()
The simplest solution to this problem is to use the built-in crossover and crossunder functions.
They consider the entire series of in-this-case close values, only returning true the moment they cross rather than every single time a close is lower than the close two candles ago.
//#version=5
indicator(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
c = close
bool buy_entry = false
bool sell_entry = false
if ta.crossover(c[1], c[3])
buy_entry := true
alert('BUY')
if ta.crossunder(c[1], c[3])
sell_entry := true
alert('SELL')
plotchar(buy_entry, title='BUY', char='B', location=location.belowbar, color=color.green, offset=-1)
plotchar(sell_entry, title='SELL', char='S', location=location.abovebar, color=color.red, offset=-1)
It's important to note why I have changed to the indices to 1 and 3 with an offset of -1 in the plotchar function. This will give the exact same signals as 0 and 2 with no offset.
The difference is that you will only see the character print on the chart when the candle actually closes rather than watch it flicker on and off the chart as the close price of the incomplete candle moves.
I have a zoo object called aux with yearly data from 1961 to 2009:
x$nao x[, 2]
1961 -0.03 63.3
1962 0.20 155.9
1963 -2.98 211.0
I want to calculate the correlation between the two columns using a 20 years sliding window. I am trying to use rollapply, but I don't seem to be able to make it work. I tried several different ways of doing it but always without success...
> rollapply(aux,20, cor(aux[,1],aux[,2],method="pearson"))
Error in match.fun(FUN) : 'cor(aux[, 1], aux[, 2], method = "pearson")' is not a function, character or symbol
> rollapply(aux,20, cor,method="pearson")
Error in FUN(coredata(data)[posns], ...) : supply both 'x' and 'y' or a matrix-like 'x'
> rollapply(aux,20, cor)
Error in FUN(coredata(data)[posns], ...) : supply both 'x' and 'y' or a matrix-like 'x'
Can anybody tell me how to make rollapply work?
Thanks for helping!
Try this.
library(quantmod)
library(TTR)
#Set the seed so results can be duplicated
set.seed(123)
#Build a zoo object with typical price data
var1 <- zoo(cumprod(1+rnorm(50, 0.01, 0.05)), seq(1961, 2001, 1))
var2 <- zoo(cumprod(1+rnorm(50, 0.015, 0.1)), seq(1961, 2001, 1))
dat <- merge(var1=var1, var2=var2)
plot(dat)
grid()
#Calculate the percent returns for the two prices
del1 <- Delt(dat$var1)
del2 <- Delt(dat$var2)
dat <- merge(dat, del1=del1, del2=del2)
dimnames(dat)[[2]][3] <- "del1"
dimnames(dat)[[2]][4] <- "del2"
head(dat)
plot(dat)
#Calculate the correlation between the two returns using a 5 year sliding window
delcor <- runCor(dat$del1, dat$del2, n=5, use="all.obs", sample=TRUE, cumulative=FALSE)
dat <- merge(dat, delcor)
plot(dat$delcor, type="l", main="Sliding Window Correlation of Two Return Series", xlab="", col="red")
grid()