def matshow_tseries(time_series, fig=None, axis=0, xtick_n=5, time_unit=None, xlabel=None, ylabel=None): """Creates an image of the time-series, ordered according to the first dimension of the time-series object Parameters ---------- time_series: a nitime time-series object fig: a figure handle, opens a new figure if None axis: an axis number (if there are several in the figure to be opened), defaults to 0. xtick_n: int, optional, sets the number of ticks to be placed on the x axis """ if fig is None: fig = plt.figure() if not fig.get_axes(): ax = fig.add_subplot(1, 1, 1) else: ax = fig.get_axes()[axis] #Make sure that time displays on the x axis with the units you want: #If you want to change the time-unit on the visualization from that used to #represent the time-series: if time_unit is not None: tu = time_unit conv_fac = ts.time_unit_conversion[time_unit] #Otherwise, get the information from your input: else: tu = time_series.time_unit conv_fac = time_series.time._conversion_factor this_time = time_series.time / float(conv_fac) ax.matshow(time_series.data) ax.set_xticks(list(range(len(this_time)))[::len(this_time) / xtick_n]) ax.set_xticklabels(this_time[::len(this_time) / xtick_n]) if xlabel is None: ax.set_xlabel('Time (%s)' % tu) else: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) return fig
def plsvfig(LLS,NNS,X,projval,x_label,y_label,z_label,Title_fnc,save_fnc): fig = pl.figure() ax = fig.gca(projection = '3d') surf=ax.plot_surface(1e9*LS,NS,X,rstride=1,cstride=1,alpha=0.7,cmap=cm.winter,linewidth = 0.05, antialiased = True, shade = False) CS = contour(1e9*LLS,NNS,X, colors = 'k', linewidth = 0.5) cbar = pl.colorbar(surf) #cbar.ax.set_ylabel(r'$\mathcal{A}^{(0)}_{[9,3]}\,\,\,[zJ]$', size = 14) cbar.add_lines(CS) cset = ax.contour(1e9*LLS,NNS,X,zdir='z',offset = projval ,cmap = cm.Blues) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_zlabel(z_label) pl.title(Title_fnc) #pl.title(r'$\rm{Gradient\, \mathcal{A}^{(0)}\, for \,[9,3]\, in\,water}$',size = 21) ax.view_init(elev = 17, azim = 150) savefig(save_fnc)#'plots/grad_A0_93_0.png')#, dpi = 300) #pl.show() return 0
def plot_xcorr(xc, ij, fig=None, line_labels=None, xticks=None, yticks=None, xlabel=None, ylabel=None): """ Visualize the cross-correlation function""" if fig is None: fig = plt.figure() if not fig.get_axes(): ax = fig.add_subplot(1, 1, 1) else: ax = fig.get_axes()[0] if line_labels is not None: #Reverse the order, so that pop() works: line_labels.reverse() this_labels = line_labels #Use the ij input as the labels: else: this_labels = [str(this) for this in ij].reverse() #Make sure that time displays on the x axis with the units you want: conv_fac = xc.time._conversion_factor this_time = xc.time / float(conv_fac) for (i, j) in ij: if this_labels is not None: #Use pop() to get the first one and remove it: ax.plot(this_time, xc.data[i, j].squeeze(), label=this_labels.pop()) else: ax.plot(this_time, xc.data[i, j].squeeze()) ax.set_xlabel('Time(sec)') ax.set_ylabel('Correlation(normalized)') if xlabel is None: #Make sure that time displays on the x axis with the units you want: conv_fac = xc.time._conversion_factor time_label = xc.time / float(conv_fac) ax.set_xlabel('Time (%s)' % xc.time_unit) else: time_label = xlabel ax.set_xlabel(xlabel) if line_labels is not None: plt.legend() if ylabel is None: ax.set_ylabel('Correlation') else: ax.set_ylabel(ylabel) return fig
##pl.axis([0,1.0,0,1.0]) #pl.grid() pl.savefig('plots/skew_ret_water/logG_contour.pdf') show() fig = pl.figure() ax = fig.gca(projection = '3d') #ax.text(-7, 6, 0.7, r'$\zeta/\omega_{0}$', zdir = (-1,1,-3), size = 21) surf = ax.plot_surface(X,Y, G_l_t_dt, rstride = 1, cstride = 1,alpha = 0.2, linewidth = 0.3)#edgecolor = 'none',antialiased = True, shade = False, norm = norm, linewidth = 0.3) #surf = ax.plot_surface(X,Y, G_l_t_dt, rstride = 20, cstride = 20,alpha = 0.2)#, cmap = cm.gnuplot, linewidth = 0.5)#gray)#coolwarm)#bone)#hot, linewidth = 0.01, antialiased = True, shade = False)# True)#, cmap = hot() #colorbar(surf) #cbar.ax.set_ylabel(r'$\frac{\xi}{\omega_{0}}$', size = 24) #cset = ax.contour(X,Y,h, zdir = 'z', offset = 0, cmap = cm.jet) #cset = ax.contour(X,Y,h, zdir = 'x', offset = 5, cmap = cm.jet) #cset = ax.contourf(X,Y,h, zdir = 'y', offset = 6, cmap = cm.jet)# puts plot of max xi vs discrete r values at r=0 plane #ax.view_init(elev = 19, azim = -112) #zlabel(r'$\xi/\omega_{0}$', size = 21) #ylabel(r'$r$', size = 24) #xlabel(r'$(\epsilon(0) -1)$', size = 24) #text = Axes.text(self, x, y, s, **kwargs) #art3d.text_2d_to_3d(text, z, zdir) #return text #pl.text(6,0, 0, r'$\xi/\omega_{0}$',size = 21 ,rotation = 'horizontal') #ax.text(r'$\xi/\omega_{0}$',6,0, 0, size = 21 ,rotation = 'horizontal') #ax.set_zlabel(r'$\xi/\omega_{0}$',size = 21 ,rotation = 'horizontal' ) ax.set_xlabel(r'$\epsilon(0)-1$', size = 21) ax.set_ylabel(r'$r$', size = 22) show() #pp.savefig()
def plot_tseries(time_series, fig=None, axis=0, xticks=None, xunits=None, yticks=None, yunits=None, xlabel=None, ylabel=None, yerror=None, error_alpha=0.1, time_unit=None, **kwargs): """plot a timeseries object Arguments --------- time_series: a nitime time-series object fig: a figure handle, opens a new figure if None subplot: an axis number (if there are several in the figure to be opened), defaults to 0. xticks: optional, list, specificies what values to put xticks on. Defaults to the matlplotlib-generated. yticks: optional, list, specificies what values to put xticks on. Defaults to the matlplotlib-generated. xlabel: optional, list, specificies what labels to put on xticks ylabel: optional, list, specificies what labels to put on yticks yerror: optional, UniformTimeSeries with the same sampling_rate and number of samples and channels as time_series, the error will be displayed as a shading above and below the plotted time-series """ if fig is None: fig = plt.figure() if not fig.get_axes(): ax = fig.add_subplot(1, 1, 1) else: ax = fig.get_axes()[axis] #Make sure that time displays on the x axis with the units you want: #If you want to change the time-unit on the visualization from that used to #represent the time-series: if time_unit is not None: tu = time_unit conv_fac = ts.time_unit_conversion[time_unit] #Otherwise, get the information from your input: else: tu = time_series.time_unit conv_fac = time_series.time._conversion_factor this_time = time_series.time / float(conv_fac) ax.plot(this_time, time_series.data.T, **kwargs) if xlabel is None: ax.set_xlabel('Time (%s)' % tu) else: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if yerror is not None: if len(yerror.data.shape) == 1: this_e = yerror.data[np.newaxis, :] else: this_e = yerror.data delta = this_e e_u = time_series.data + delta e_d = time_series.data - delta for i in range(e_u.shape[0]): ax.fill_between(this_time, e_d[i], e_u[i], alpha=error_alpha) return fig
def plot_corr_diff(tseries1, tseries2, fig=None, ts_names=['1', '2']): """ Show the differences in *Fischer-transformed* snr correlations for two time-series Parameters ---------- tseries1, tseries2 : nitime TimeSeries objects These are the time-series to compare, with each of them having the dims: (n_channels, n_reps, time), where n_channels1 = n_channels2 lb,ub: float Lower and upper bounds on the frequency range over which to calculate the information rate (default to [0,Nyquist]). fig: matplotlib figure object If you want to do this on already existing figure. Otherwise, a new figure object will be generated. ts_names: list of str Labels for the two inputs, to be used in plotting (defaults to ['1','2']) bandwidth, adaptive, low_bias: See :func:`SNRAnalyzer` for details Returns ------- fig: a matplotlib figure object """ if fig is None: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) SNR1 = [] SNR2 = [] corr1 = [] corr2 = [] corr_e1 = [] corr_e2 = [] for i in range(tseries1.shape[0]): SNR1.append(nta.SNRAnalyzer(ts.TimeSeries(tseries1.data[i], sampling_rate=tseries1.sampling_rate))) corr1.append(np.arctanh(np.abs(SNR1[-1].correlation[0]))) corr_e1.append(SNR1[-1].correlation[1]) SNR2.append(nta.SNRAnalyzer(ts.TimeSeries(tseries2.data[i], sampling_rate=tseries2.sampling_rate))) corr2.append(np.arctanh(np.abs(SNR2[-1].correlation[0]))) corr_e2.append(SNR1[-1].correlation[1]) ax.scatter(np.array(corr1), np.array(corr2)) ax.errorbar(np.mean(corr1), np.mean(corr2), yerr=np.std(corr2), xerr=np.std(corr1)) plot_min = min(min(corr1), min(corr2)) plot_max = max(max(corr1), max(corr2)) ax.plot([plot_min, plot_max], [plot_min, plot_max], 'k--') ax.set_xlabel('Correlation (Fischer Z) %s' % ts_names[0]) ax.set_ylabel('Correlation (Fischer Z) %s' % ts_names[1]) return fig, corr1, corr2
def plotTSs1(start_date, end_date, shortMa, longMa): yf.pdr_override() plt.close() shortMaP = int(shortMa) longMaP = int(longMa) data = pdr.get_data_yahoo("BTC-USD", start_date, end_date) btc = pd.DataFrame(data) btc = btc[['Adj Close']] btc.columns = ['price'] btc.reset_index(level=0, inplace=True) ################################################################################### # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading #[online] DataCamp Community. Available at: <https://www.datacamp.com/community/tutorials/finance-python-trading#basics> plt.close() signal = pd.DataFrame(index=btc.index) #copy index from BTC signal['id'] = 0.0 signal['shortMA'] = btc['price'].rolling( window=shortMaP, min_periods=1).mean() #Short Moving Average Calculated signal['longMA'] = btc['price'].rolling( window=longMaP, min_periods=1).mean() ##Long Moving Average Calculated signal['id'][shortMaP:] = np.where( signal['shortMA'][shortMaP:] > signal['longMA'][shortMaP:], 1.0, 0.0) #where short moving average surpasses long, id is changed to 1 #[shortMaP:] only for the period that is surpasses than the short moving average signal['buySell'] = signal['id'].diff() fig = plt.figure() ax1 = fig.add_subplot(111, ylabel=' Currency Price in $') ax1.plot(btc.price) #Plot price # Plot the short and long moving averages ax1.plot(signal['shortMA'], color='black', label='Short Moving Average') ax1.plot(signal['longMA'], color='orange', label='Long Moving Average') ax1.legend(loc='upper right') # The buy signals according to buySell are plotted ax1.plot(signal.loc[signal.buySell == 1.0].index, signal.shortMA[signal.buySell == 1.0], '^', markersize=10, color='green') # The sell signals according to buySell are plotted ax1.plot(signal.loc[signal.buySell == -1.0].index, signal.shortMA[signal.buySell == -1.0], 'v', markersize=10, color='red') # Show the plot plt.show() ################################################################################### # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading portfolio = pd.DataFrame(index=signal.index) initInvestment = 100000 stocksOwned = pd.DataFrame(index=signal.index).fillna(0.0) noCur = 10 #No of currency to be purchased stocksOwned['BTC'] = noCur * signal['id'] portfolio['Holdings'] = stocksOwned['BTC'].multiply(btc['price'], axis=0) buySell = stocksOwned['BTC'].diff() portfolio['cash'] = initInvestment - (buySell.multiply(btc['price'], axis=0)).cumsum() portfolio['total'] = portfolio['cash'] + portfolio['Holdings'] portfolio['cash'][0] = initInvestment portfolio['total'][0] = initInvestment ################################################################################### fig = plt.figure() ax = fig.add_subplot(111) ax.plot(portfolio.index, portfolio['total'], label='Price') ax.set_xlabel('Date') ax.set_ylabel('Value of Portfolio in $') day = portfolio.loc[signal.buySell == 1.0].index day2 = portfolio.loc[signal.buySell == -1.0].index #x co ax.scatter(x=day, y=portfolio.loc[day, 'total'], color='green', marker='^') ax.scatter(x=day2, y=portfolio.loc[day2, 'total'], color='red', marker='^')
surf=ax.plot_surface(1e9*LS,NS,X_91,rstride=1,cstride=1, alpha=0.5,cmap=cm.Greens,linewidth = 0.05, antialiased = True, shade = False) surf=ax.plot_surface(1e9*LS,NS,X_93,rstride=1,cstride=1, alpha=0.5,cmap=cm.Reds,linewidth = 0.05, antialiased = True, shade = False) surf=ax.plot_surface(1e9*LS,NS,X_290,rstride=1,cstride=1,alpha=0.5,cmap=cm.hot,linewidth = 0.05, antialiased = True, shade = False) #cbar.ax.set_ylabel(r'$\mathcal{A}^{(0)}_{[9,3]}\,\,\,[zJ]$', size = 14) #pl.title(r'$\rm{Gradient\, \mathcal{A}^{(0)}\, for \,[9,3]\, in\,water}$',size = 21) ax.view_init(elev = 17, azim = 150) #fig = pl.figure() #ax = fig.gca(projection = '3d') #surf=ax.plot_surface(1e9*LS,NS,X,rstride=1,cstride=1,alpha=0.7,cmap=cm.winter,linewidth = 0.05, antialiased = True, shade = False) #CS = contour(1e9*LS,NS,X, colors = 'k', linewidth = 0.5) #cbar = pl.colorbar(surf) #cbar.ax.set_ylabel(r'$\mathcal{A}^{(0)}_{[9,3]}\,\,\,[zJ]$', size = 14) #cbar.add_lines(CS) #cset = ax.contour(1e9*LS,NS,X,zdir='z',offset = -0.25,cmap = cm.Blues) ax.set_xlabel(r'$\rm{separation}\,\,\,\ell\,\,[nm]$', size = 18) ax.set_ylabel(r'$\rm{n^{th}}\,Matsubra\,term$', size = 18) ax.set_zlabel(r'$\nabla \mathcal{A}^{(0)}\,\,[zJ]$',size = 18 ,rotation = 'horizontal' ) #pl.title(r'$\rm{Gradient\, \mathcal{A}^{(0)}\, for \,[9,3]\, in\,water}$',size = 21) #ax.view_init(elev = 17, azim = 10) savefig('plots/grad_A0_combo.png')#, dpi = 300) #show() # fig = pl.figure() ax = fig.gca(projection = '3d') contour(1e9*LS,NS,X_65, rstride=1,cstride=1,alpha=0.5,cmap=cm.Blues, linewidth = 0.05, antialiased = True, shade = False) contour(1e9*LS,NS,X_91, rstride=1,cstride=1,alpha=0.5,cmap=cm.Greens, linewidth = 0.05, antialiased = True, shade = False) contour(1e9*LS,NS,X_93, rstride=1,cstride=1,alpha=0.5,cmap=cm.Reds, linewidth = 0.05, antialiased = True, shade = False) contour(1e9*LS,NS,X_290,rstride=1,cstride=1,alpha=0.5,cmap=cm.Purples,linewidth = 0.05, antialiased = True, shade = False) #CS = contour(1e9*LS,NS,X, colors = 'k', linewidth = 0.5) #cbar = pl.colorbar(surf) #cbar.ax.set_ylabel(r'$\mathcal{A}^{(0)}_{[9,3]}\,\,\,[zJ]$', size = 14)
cbar_091_0.add_lines(CS_091_0) cbar_290_0 = pl.colorbar(surf_290_0) cbar_290_0.ax.set_ylabel(r'$\mathcal{A}^{(0)}_{[29,0]}\,\,\,[zJ]$', size = 14) cbar_290_0.add_lines(CS_290_0) cset_065_0 = ax.contour(1e9*X,Y,1e21*A0_065_theta,zdir='y',offset = -0.3,cmap = cm.Blues) cset_091_0 = ax.contour(1e9*X,Y,1e21*A0_091_theta,zdir='y',offset = -0.3,cmap = cm.Greens) cset_290_0 = ax.contour(1e9*X,Y,1e21*A0_290_theta,zdir='y',offset = -0.3,cmap = cm.Reds) #man_loc = [(.1,.1),(.2,.2),(.3,.3),(.4,.4)] yticks([0, pi/8, pi/6, pi/4, pi/3, pi/2], ['$0$', r'$\frac{\pi}{8}$', r'$\frac{\pi}{6}$', r'$\frac{\pi}{4}$', r'$\frac{\pi}{3}$', r'$\frac{\pi}{2}$']) #clabel(CS, inline =1,fmt = '%1.1f', fontsize = 18,color = 'k', manual = man_loc) ax.grid(on = True) ax.set_xlabel(r'$\rm{separation}\,\,\,\ell\,\,[nm]$', size = 18) ax.set_ylabel(r'$\rm{angle}\,\,\,\theta\,\,[radians]$', size = 18) ax.set_zlabel(r'$\mathcal{A}^{(0)}\,\,[zJ]$',size = 18 ,rotation = 'horizontal' ) pl.title(r'$\rm{\mathcal{A}^{(0)}\, for \, [6,5],[9,1],\,and\,[29,0]\, in\,water}$', size = 21) ax.view_init(elev = 10, azim = 65) savefig('plots/A0_65_91_290.png')#, dpi = 300) show() ##### A_2 PLOTS ###### fig = figure() ax = fig.gca(projection = '3d') surf_065 = ax.plot_surface(1e9*X,Y,1e21*A2_065_theta, rstride = 5, cstride =5,alpha=0.7,cmap=cm.Blues, linewidth = 0.05, antialiased = True, shade = False)# True)#, cmap = hot() surf_091 = ax.plot_surface(1e9*X,Y,1e21*A2_091_theta, rstride = 5, cstride =5,alpha=0.7,cmap=cm.Greens, linewidth = 0.05, antialiased = True, shade = False)# True)#, cmap = hot() surf_290 = ax.plot_surface(1e9*X,Y,1e21*A2_290_theta, rstride = 5,
# pl.grid() pl.savefig("plots/skew_NR_water/logG_contour.pdf") show() fig = pl.figure() ax = fig.gca(projection="3d") # ax.text(-7, 6, 0.7, r'$\zeta/\omega_{0}$', zdir = (-1,1,-3), size = 21) surf = ax.plot_surface( X, Y, G_l_t_dt, rstride=1, cstride=1, alpha=0.2, linewidth=0.3 ) # edgecolor = 'none',antialiased = True, shade = False, norm = norm, linewidth = 0.3) # surf = ax.plot_surface(X,Y, G_l_t_dt, rstride = 20, cstride = 20,alpha = 0.2)#, cmap = cm.gnuplot, linewidth = 0.5)#gray)#coolwarm)#bone)#hot, linewidth = 0.01, antialiased = True, shade = False)# True)#, cmap = hot() # colorbar(surf) # cbar.ax.set_ylabel(r'$\frac{\xi}{\omega_{0}}$', size = 24) # cset = ax.contour(X,Y,h, zdir = 'z', offset = 0, cmap = cm.jet) # cset = ax.contour(X,Y,h, zdir = 'x', offset = 5, cmap = cm.jet) # cset = ax.contourf(X,Y,h, zdir = 'y', offset = 6, cmap = cm.jet)# puts plot of max xi vs discrete r values at r=0 plane # ax.view_init(elev = 19, azim = -112) # zlabel(r'$\xi/\omega_{0}$', size = 21) # ylabel(r'$r$', size = 24) # xlabel(r'$(\epsilon(0) -1)$', size = 24) # text = Axes.text(self, x, y, s, **kwargs) # art3d.text_2d_to_3d(text, z, zdir) # return text # pl.text(6,0, 0, r'$\xi/\omega_{0}$',size = 21 ,rotation = 'horizontal') # ax.text(r'$\xi/\omega_{0}$',6,0, 0, size = 21 ,rotation = 'horizontal') # ax.set_zlabel(r'$\xi/\omega_{0}$',size = 21 ,rotation = 'horizontal' ) ax.set_xlabel(r"$\epsilon(0)-1$", size=21) ax.set_ylabel(r"$r$", size=22) show() # pp.savefig()
def plot_corr_diff(tseries1, tseries2, fig=None, ts_names=['1', '2']): """ Show the differences in *Fischer-transformed* snr correlations for two time-series Parameters ---------- tseries1, tseries2 : nitime TimeSeries objects These are the time-series to compare, with each of them having the dims: (n_channels, n_reps, time), where n_channels1 = n_channels2 lb,ub: float Lower and upper bounds on the frequency range over which to calculate the information rate (default to [0,Nyquist]). fig: matplotlib figure object If you want to do this on already existing figure. Otherwise, a new figure object will be generated. ts_names: list of str Labels for the two inputs, to be used in plotting (defaults to ['1','2']) bandwidth, adaptive, low_bias: See :func:`SNRAnalyzer` for details Returns ------- fig: a matplotlib figure object """ if fig is None: fig = plt.figure() ax = fig.add_subplot(1, 1, 1) SNR1 = [] SNR2 = [] corr1 = [] corr2 = [] corr_e1 = [] corr_e2 = [] for i in range(tseries1.shape[0]): SNR1.append( nta.SNRAnalyzer( ts.TimeSeries(tseries1.data[i], sampling_rate=tseries1.sampling_rate))) corr1.append(np.arctanh(np.abs(SNR1[-1].correlation[0]))) corr_e1.append(SNR1[-1].correlation[1]) SNR2.append( nta.SNRAnalyzer( ts.TimeSeries(tseries2.data[i], sampling_rate=tseries2.sampling_rate))) corr2.append(np.arctanh(np.abs(SNR2[-1].correlation[0]))) corr_e2.append(SNR1[-1].correlation[1]) ax.scatter(np.array(corr1), np.array(corr2)) ax.errorbar(np.mean(corr1), np.mean(corr2), yerr=np.std(corr2), xerr=np.std(corr1)) plot_min = min(min(corr1), min(corr2)) plot_max = max(max(corr1), max(corr2)) ax.plot([plot_min, plot_max], [plot_min, plot_max], 'k--') ax.set_xlabel('Correlation (Fischer Z) %s' % ts_names[0]) ax.set_ylabel('Correlation (Fischer Z) %s' % ts_names[1]) return fig, corr1, corr2
def plotTsS2(start_date, end_date): plt.close() yf.pdr_override() data = pdr.get_data_yahoo("BTC-USD", start_date, end_date) btc = pd.DataFrame(data) btc = btc[['Adj Close']] btc.columns = ['Close'] btc.reset_index(level=0, inplace=True) b = pd.DataFrame() for x in btc: b['price'] = btc['Close'] b['sma'] = btc['Close'].rolling(window=20).mean() b['std'] = btc['Close'].rolling(window=20).std() b['bolU'] = b['sma'] + (2 * b['std']) #Calculating Upper Bound b['bolD'] = b['sma'] - (2 * b['std']) #Calculating Lower Bound #Convert Bollinger Bands to %b - bollinger column b['bollinger'] = (b['price'] - b['bolD']) / (b['bolU'] - b['bolD']) bb1 = b[['price', 'bolU', 'bolD', 'bollinger']] bb1.columns = ['Price', 'Upper Band', 'Lower Band', 'Bollinger'] bb1.fillna(0, inplace=True) # In[ ]: # In[9]: RSI = pd.DataFrame(index=btc.index) RSI['price'] = btc['Close'] RSI['val'] = None RSI['up'] = 0 #When there is no up value 0 RSI['down'] = 0 #When there is no down value 0 size = RSI.shape[0] dp = 14 for x in range(size): if x == 0: continue #first day will continue #calculating the ups , when closing price is higher in day x than x -1 if RSI['price'].iloc[x] > RSI['price'].iloc[x - 1]: # RSI['up'].iloc[x] = RSI['price'].iloc[x] - RSI['price'].iloc[x - 1] else: #calculating the downs days , when closing price is lower in day x than x -1 RSI['down'].iloc[x] = RSI['price'].iloc[x - 1] - RSI['price'].iloc[x] if x >= dp: avgUp = RSI['up'][x - dp:x].sum( ) / dp #calculates avg up of last dp days avgDown = RSI['down'][x - dp:x].sum( ) / dp #calculates avg down of last dp days rs = avgUp / avgDown #calculation of RS RSI['val'].iloc[x] = 100 - 100 / (1 + rs) signals = pd.DataFrame(index=btc.index) #copy index for BTC signals['price'] = btc['Close'] signals['id'] = 0.0 signals['RSI'] = RSI['val'] signals['RSI'].fillna(0, inplace=True) signals['bollinger'] = bb1['Bollinger'] signals['id'] = [np.nan for i in signals.index] # only verifications for days after DPth (period of RSI) day signals['id'][dp:].loc[((signals['RSI'] < 30) & (signals['bollinger'] < 0))] = 1 signals['id'][dp:].loc[((signals['RSI'] > 70) & (signals['bollinger'] > 1))] = 0 signals['id'].ffill(inplace=True) #fill empty values with 0 signals['id'].fillna(0, inplace=True) signals['buySell'] = signals['id'].diff() signals['buySell'].fillna(0, inplace=True) fig, (ax) = plt.subplots(1, 1) ax.plot(signals['price']) ax.set_xlabel('Date') ax.set_ylabel('Value in $') day = signals.loc[signals.buySell == 1.0].index day2 = signals.loc[signals.buySell == -1.0].index #x cordinates, index of day --> y cordinate,price of day index ax.scatter( x=day, y=signals.loc[day, 'price'], marker='^', color='green', ) ax.scatter(x=day2, y=signals.loc[day2, 'price'], marker='v', color='red') plt.show()
def plotPorts2(start_date, end_date): plt.close() yf.pdr_override() data = pdr.get_data_yahoo("BTC-USD", start_date, end_date) btc = pd.DataFrame(data) btc = btc[['Adj Close']] btc.columns = ['Close'] btc.reset_index(level=0, inplace=True) # In[8]: b = pd.DataFrame() for x in btc: b['price'] = btc['Close'] b['sma'] = btc['Close'].rolling(window=20).mean() b['std'] = btc['Close'].rolling(window=20).std() b['bolU'] = b['sma'] + (2 * b['std']) #Calculating Upper Bound b['bolD'] = b['sma'] - (2 * b['std']) #Calculating Lower Bound #Convert Bollinger Bands to %b - bollinger column b['bollinger'] = (b['price'] - b['bolD']) / (b['bolU'] - b['bolD']) bb1 = b[['price', 'bolU', 'bolD', 'bollinger']] bb1.columns = ['Price', 'Upper Band', 'Lower Band', 'Bollinger'] bb1.fillna(0, inplace=True) # In[ ]: # In[9]: RSI = pd.DataFrame(index=btc.index) RSI['price'] = btc['Close'] RSI['val'] = None RSI['up'] = 0 #When there is no up value 0 RSI['down'] = 0 #When there is no down value 0 size = RSI.shape[0] dp = 14 for x in range(size): if x == 0: continue #first day will continue #calculating the ups , when closing price is higher in day x than x -1 if RSI['price'].iloc[x] > RSI['price'].iloc[x - 1]: # RSI['up'].iloc[x] = RSI['price'].iloc[x] - RSI['price'].iloc[x - 1] else: #calculating the downs days , when closing price is lower in day x than x -1 RSI['down'].iloc[x] = RSI['price'].iloc[x - 1] - RSI['price'].iloc[x] if x >= dp: avgUp = RSI['up'][x - dp:x].sum( ) / dp #calculates avg up of last dp days avgDown = RSI['down'][x - dp:x].sum( ) / dp #calculates avg down of last dp days rs = avgUp / avgDown #calculation of RS RSI['val'].iloc[x] = 100 - 100 / (1 + rs) signals = pd.DataFrame(index=btc.index) #copy index for BTC signals['price'] = btc['Close'] signals['id'] = 0.0 signals['RSI'] = RSI['val'] signals['RSI'].fillna(0, inplace=True) signals['bollinger'] = bb1['Bollinger'] signals['id'] = [np.nan for i in signals.index] # only verifications for days after DPth (period of RSI) day signals['id'][dp:].loc[((signals['RSI'] < 30) & (signals['bollinger'] < 0))] = 1 signals['id'][dp:].loc[((signals['RSI'] > 70) & (signals['bollinger'] > 1))] = 0 signals['id'].ffill(inplace=True) #fill empty values with 0 signals['id'].fillna(0, inplace=True) signals['buySell'] = signals['id'].diff() signals['buySell'].fillna(0, inplace=True) ################################################################################### # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading initInvestment = 100000 stocksOwned = pd.DataFrame(index=signals.index).fillna(0.0) noCur = 10 #No of currency to be purchased stocksOwned['BTC'] = noCur * signals['id'] portfolio = pd.DataFrame(index=signals.index) portfolio['Holdings'] = stocksOwned['BTC'].multiply(btc['Close'], axis=0) buySell = stocksOwned['BTC'].diff() portfolio['cash'] = initInvestment - (buySell.multiply(btc['Close'], axis=0)).cumsum() portfolio['total'] = portfolio['cash'] + portfolio['Holdings'] portfolio['cash'][0] = initInvestment portfolio['total'][0] = initInvestment ################################################################################### # In[50]: fig, (ax) = plt.subplots(1, 1, sharex=True) ax.plot(portfolio.index, portfolio['total'], label='Price') ax.set_xlabel('Date') ax.set_ylabel('Value of portfolio in USD') day = signals.loc[signals.buySell == 1.0].index day2 = signals.loc[signals.buySell == -1.0].index ax.scatter(x=day, y=portfolio.loc[day, 'total'], color='green') ax.scatter(x=day2, y=portfolio.loc[day2, 'total'], color='red') plt.show()