def plot_spectral_estimate(f, sdf, sdf_ests, limits=None, elabels=()): """ Plot an estimate of a spectral transform against the ground truth. Utility file used in building the documentation """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax_limits = (sdf.min() - 2*np.abs(sdf.min()), sdf.max() + 1.25*np.abs(sdf.max())) ax.plot(f, sdf, 'c', label='True S(f)') if not elabels: elabels = ('',) * len(sdf_ests) colors = 'bgkmy' for e, l, c in zip(sdf_ests, elabels, colors): ax.plot(f, e, color=c, linewidth=2, label=l) if limits is not None: ax.fill_between(f, limits[0], y2=limits[1], color=(1, 0, 0, .3), alpha=0.5) ax.set_ylim(ax_limits) ax.legend() return fig
def plot_spectral_estimate(f, sdf, sdf_ests, limits=None, elabels=()): """ Plot an estimate of a spectral transform against the ground truth. Utility file used in building the documentation """ fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax_limits = (sdf.min() - 2 * np.abs(sdf.min()), sdf.max() + 1.25 * np.abs(sdf.max())) ax.plot(f, sdf, 'c', label='True S(f)') if not elabels: elabels = ('', ) * len(sdf_ests) colors = 'bgkmy' for e, l, c in zip(sdf_ests, elabels, colors): ax.plot(f, e, color=c, linewidth=2, label=l) if limits is not None: ax.fill_between(f, limits[0], y2=limits[1], color=(1, 0, 0, .3), alpha=0.5) ax.set_ylim(ax_limits) ax.legend() return fig
def HomeWinPercentGraph(teamname, HomeWin,ax): ax.plot(teamname,HomeWin) ax.set(title='Home Win %'); plt.ylabel("Win %"); plt.xlabel("Team"); plt.ylim(0,100); ax.xaxis.set_label_coords(0.50, 0.075); plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') plt.tick_params(axis='x', which='major', labelsize=7)
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
def plotRSI(startDate, endDate, cur, dp): plt.close() RSI = getRSI(startDate, endDate, cur, dp) xc2 = [] for x in range(len(RSI)): xc2.append(70) xc1 = [] for y in range(len(RSI)): xc1.append(30) fig, ax = plt.subplots() rsiLine = ax.plot(RSI.Date, RSI.RSI, label=str(dp) + ' Day RSI') upperLine = ax.plot(RSI.Date, xc2, '--', color='red') LowerLine = ax.plot(RSI.Date, xc1, '--', color='green') s1 = datetime.strptime(startDate, '%Y-%m-%d') plt.title('Resistance Strength Index', fontsize=20) plt.xlabel('Dates', fontsize=18) plt.ylabel('RSI', fontsize=18) plt.text(s1, 75, 'Overbought') plt.text(s1, 35, 'Oversold') plt.legend(loc='upper right') plt.show()
def animate(x): global runtime try: current_temp = float((get(APIURL + 'temp')).text) except: current_temp = 0 print("Cannot reach API") if current_temp < 10: current_temp = 10 if current_temp > 50: current_temp = 50 print(temperature_history) temperature_history.insert(0,current_temp) time_ran.append(runtime) runtime += 1 time_ran_plot = time_ran temperature_history_plot = temperature_history axis.clear() axis.plot(time_ran_plot, temperature_history_plot) axis.set_xlim(300,0) axis.set_ylim(10,50) plot.xlabel('seconds ago') plot.ylabel('degrees C')
for u in arange(1,101): sum_Li2_A_dep[t] += (((A_dep[r]/(A_dep[r]+2.*z_y[t]**2 +2))**2)**u)/(u**2) yA_dep[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))*\ (1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) max_yA[r]= max(yA_dep)/yA_dep[0] max_xA[r]= z_y[yA_dep.argmax()] ax.plot(max_xA, max_yA, linestyle = '', marker = 's', markerfacecolor='m')#,linestyle = lts[i],label=labels)#color = colors[j], pl.xlabel(r'$\zeta/\omega_{0}$', size = 21) pl.ylabel(r'$ \mathcal{\delta A}(i\zeta/\omega_{0} ) $', size = 21) # INSET # ---------------------------------------------------------- ax_inset = fig.add_axes([0.5,0.5,0.36,0.36]) #ax_inset = fig.add_axes([0.55,0.55,0.33,0.33]) # NB, if you change the above eqn for y, you must regenerate this input: A_dep_r = linspace(0.0000000000001,10,300)#(0.000001,10,20) #Ar = [A_dep_r,A_dep_r,A_dep_r,A_dep_r] #r_dep = [r09,r10,r15,r20]
#(1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) Aiz = [y_dep * dee for y_dep, dee in zip(yA_dep_exp, de_e)] # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- #ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) #ax.plot(n/10.4,Aiz/Aiz[0],linestyle = ':',color = 'k')#, color = colors[r], label = labels) #ax.plot(n/ 11.0,Aiz,linestyle = ':',color = 'b')#, color = colors[r], label = labels) #ax.plot(n/(8.4*3.14/2),Aiz,linestyle = ':',color = 'g')#, color = colors[r], label = labels) #ax.plot(n/12.0,Aiz/Aiz[0],linestyle = ':',color = 'r')#, color = colors[r], label = labels) ax.plot(n / 8.4, Aiz / Aiz[0], linestyle=':', color='y') #, color = colors[r], label = labels) # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- #ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) #ax.plot(z_y,yA_dep/yA_dep[0])#, color = colors[r], label = labels) ax.plot(z_y, yA_dep / yA_dep[0]) #, color = colors[r], label = labels) #ax.plot(z_y,yA_dep)#/yA_dep[0])#, color = colors[r], label = labels) pl.xlabel(r'$\xi/\omega_{0}$', size=21)
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='^')
#ax.plot(n/(8.4*3.14/2),Aiz,linestyle = ':',color = 'g')#, color = colors[r], label = labels) # ax.plot(n/12.0,Aiz,linestyle = ':',color = 'r')#, color = colors[r], label = labels) #ax.plot(n/12.,Aiz,linestyle = ':',color = 'y')#, color = colors[r], label = labels) total = trapz(yA_dep / yA_dep[0], z_y) #print total # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] #pl.plot(A_dep,total) # MAIN PLOT # ---------------------------------------------------------- #ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) #ax.plot(z_y,yA_dep/yA_dep[0])#, color = colors[r], label = labels) ax.plot(z_y, yA_dep / yA_dep[0]) #, color = colors[r], label = labels) #ax.plot(z_y,yA_dep)#/yA_dep[0])#, color = colors[r], label = labels) pl.xlabel(r'$\xi/\omega_{0}$', size=21) pl.ylabel(r'$ A(\xi/\omega_{0} ) $', size=21) totals = [ 0.0, 0.844235588588, 0.902052850418, 0.959171922439, 1.01581508011, 1.07214213658, 1.12827223495, 1.18429669819, 1.24028706962, 1.2963003875, 1.35238278039, 1.40857199673, 1.46489923268, 1.52139048298, 1.57806755879, 1.63494886788, 1.69205002126, 1.74938431132, 1.80696309288, 1.86479609019, 1.92289164646, 1.98125692852, 2.03989809587, 2.09882044138, 2.1580285091, 2.21752619349, 2.2773168235, 2.33740323411, 2.39778782755, 2.45847262587, 2.51945931629, 2.58074929044, 2.6423436785, 2.70424337889, 2.76644908432, 2.82896130457, 2.89178038653, 2.95490653189, 3.01833981278, 3.08208018557, 3.14612750322, 3.21048152616, 3.27514193206, 3.3401083245, 3.40538024081,
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
#(1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) Aiz = [y_dep*dee for y_dep,dee in zip(yA_dep_exp,de_e)] # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- #ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) #ax.plot(n/10.4,Aiz/Aiz[0],linestyle = ':',color = 'k')#, color = colors[r], label = labels) #ax.plot(n/ 11.0,Aiz,linestyle = ':',color = 'b')#, color = colors[r], label = labels) #ax.plot(n/(8.4*3.14/2),Aiz,linestyle = ':',color = 'g')#, color = colors[r], label = labels) #ax.plot(n/12.0,Aiz/Aiz[0],linestyle = ':',color = 'r')#, color = colors[r], label = labels) ax.plot(n/8.4,Aiz/Aiz[0],linestyle = ':',color = 'y')#, color = colors[r], label = labels) # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- #ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) #ax.plot(z_y,yA_dep/yA_dep[0])#, color = colors[r], label = labels) ax.plot(z_y,yA_dep/yA_dep[0])#, color = colors[r], label = labels) #ax.plot(z_y,yA_dep)#/yA_dep[0])#, color = colors[r], label = labels)
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()
for u in arange(1,101): sum_Li2_A_dep[t] += (((A_dep[r]/(A_dep[r]+2.*z_y[t]**2 +2))**2)**u)/(u**2) yA_dep[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))*\ (1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) # yA_dep[t] = (sum_Li2_A_dep[t]*\ # (A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**(-1)*\ # (1-(A_dep[r]/(A_dep[r]+2.*z_y[t]**2+2))**2))\ # max_xA[r]= z_y[yA_dep.argmax()] # MAIN PLOT # ---------------------------------------------------------- ax.plot(z_y,yA_dep/yA_dep[0], color = colors[r], label = labels) pl.xlabel(r'$\frac{\xi}{\omega_{0}}$', size = 'x-large') pl.ylabel(r'$ y (\frac{\xi}{\omega_{0}} ) $', size = 'x-large') # INSET # ---------------------------------------------------------- ax_inset = fig.add_axes([0.55,0.55,0.33,0.33]) # NB, if you change the above eqn for y, you must regenerate this input: ax_inset.plot(x_ymax,y_ymax, color = 'k', linestyle = '-') pl.xlabel(r'$A\,=\,\frac{2}{\pi}C$',size = 'small') pl.ylabel(r'MAX$[y(\frac{\xi}{\omega_{0}})] $',size = 'small') pl.tick_params(labelsize = 'small') #ax.legend(loc = 'best') pp.savefig() pl.show() pl.close()
#pl.figure() #pl.plot(z_y,yA/yA[0], color = 'b', label = 'A = 1.0') #pl.plot(z_y,yB/yB[0], color = 'g', label = 'B = 4.0') #pl.plot(z_y,yC/yC[0], color = 'r', label = 'C = 6.0') #pl.title(r'Function $y(\xi)$ from $eqn\,6$') #pl.tick_params(labelsize = 'small') #pl.xlabel(r'$0<\frac{\xi}{\omega_0}<2$', size = 'x-large') #pl.ylabel(r'$y(\xi)$', size = 'x-large')# \mathrm{ F}\,\, \frac{ 8 \pi D^{2} }{k_{B} T}$') #pl.legend(loc = 'best') #pl.axis([0.0, 2.2,0.0,1.2]) #pp.savefig() #pl.show() ############################################################## fig = pl.figure() ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.plot(x_peak , y_peak, color = 'g',label = r'Synthesized')# $\epsilon$"($\omega$)', linestyle='-') ax.plot(x_nopeak, y_nopeak, color = 'b',label = r'Ab initio')# $\epsilon$"($\omega$)', linestyle='-') #ax.legend(loc = 'best') #pl.title(r'$\epsilon$"($\omega$) Ab Initio and Synthisized') pl.xlabel(r'$\omega$', size = 22) pl.ylabel(r'$\epsilon$"($\omega$)', size = 21) ax_inset = fig.add_axes([0.53,0.50,0.36,0.36]) ax_inset.plot(x_nopeak,diff_eps,color='r',label=r'$\epsilon$"($\omega)_{synthesized}$-$\epsilon$"($\omega)_{ab\,initio}$') ax_inset.plot(x_nopeak,listofzeros,color = 'k', label=r'$\delta$$\epsilon$"($\omega$) = 0') #pl.title(r'Difference $\epsilon$"($\omega$)', size = 'small') pl.tick_params(labelsize = 'small') pl.xlabel(r'$\omega$', size = 14) pl.ylabel(r'$\delta$$\epsilon$"($\omega$)', size = 14) #pp.savefig() #pl.savefig('130807_plots/fig2a_eps2_deps2.pdf')
ax = fig.add_axes([0.1,0.1,0.8,0.8]) colors = ['b','g','r','c','m','y','k'] for r in range(len(A_dep)): labels=r'$A\, =\, %.2f$' % A_dep[r] for t in range(len(z_y)): sum_Li2_A_dep[t] = 0.0 for u in arange(1,101): sum_Li2_A_dep[t] += (((A_dep[r]/(A_dep[r]+2.*z_y[t]**2 +2))**2)**u)/(u**2) yA_dep[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))*\ (1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) yA_dep_exp[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))#*\ #(1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) Aiz = [2.0*y_dep*dee for y_dep,dee in zip(yA_dep_exp,de_e)] ax.plot(n/12.,Aiz,linestyle = ':',color = 'y')#, color = colors[r], label = labels) total = trapz(yA_dep,z_y) print total ax.plot(z_y,yA_dep)#, color = colors[r], label = labels) pl.xlabel(r'$\xi/\omega_{0}$', size = 21) pl.ylabel(r'$ A(\xi/\omega_{0} ) $', size = 21) pl.show() pl.close()
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
pl.xlabel(r'$n$', size = 'large') pl.ylabel(r'$\delta \mathrm{ F}\,\, \frac{ 8 \pi D^{2} }{k_{B} T}$') pl.legend(loc = 'best') pl.text(75,-0.053,r'Total $\delta F( \omega_0 = 4.2) = %.2f$' % sum_dF_042, color='b') pl.text(75,-0.056,r'Total $\delta F( \omega_0 = 6.2) = %.2f$' % sum_dF_062, color='g') pl.text(75,-0.059,r'Total $\delta F( \omega_0 = 8.2) = %.2f$' % sum_dF_082, color='r') pl.text(75,-0.062,r'Total $\delta F(\omega_0 = 10.2) = %.2f$' % sum_dF_102, color='c') pl.text(75,-0.065,r'Total $\delta F(\omega_0 = 13.2) = %.2f$' % sum_dF_132, color='m') pl.text(75,-0.068,r'Total $\delta F(\omega_0 = 18.2) = %.2f$' % sum_dF_182, color='y') pp.savefig() pl.show() fig = pl.figure() ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.plot(x_peak, y_peak, color = 'g',label = r'Synthesized')# $\epsilon$"($\omega$)', linestyle='-') ax.plot(x_nopeak,y_nopeak, color = 'b',label = r'Ab initio')# $\epsilon$"($\omega$)', linestyle='-') ax.legend(loc = 'best') #pl.title(r'$\epsilon$"($\omega$) Ab Initio and Synthisized') pl.xlabel(r'$\omega$', size = 'x-large') pl.ylabel(r'$\epsilon$"($\omega$)', size = 'x-large') ax_inset = fig.add_axes([0.55,0.42,0.3,0.3]) ax_inset.plot(x_nopeak,diff_eps,color='r',label=r'$\epsilon$"($\omega)_{synthesized}$-$\epsilon$"($\omega)_{ab\,initio}$') #ax_inset.plot(x_nopeak*1e-16,diff_eps,color='r',label=r'$\epsilon$"($\omega)_{synthesized}$-$\epsilon$"($\omega)_{ab\,initio}$') #ax_inset.plot(x_nopeak*1e-16,listofzeros,color = 'k', label=r'$\delta$$\epsilon$"($\omega$) = 0') ax_inset.plot(x_nopeak,listofzeros,color = 'k', label=r'$\delta$$\epsilon$"($\omega$) = 0') #pl.title(r'Difference $\epsilon$"($\omega$)', size = 'small') pl.tick_params(labelsize = 'small') pl.xlabel(r'$\omega$', size = 'small') pl.ylabel(r'$\delta$$\epsilon$"($\omega$)', size = 'small')
def makeplot_recurrence(sequence, sequence2, recurrence_table, f_sequence, s_sequence): recurrence_table = np.array( np.reshape(recurrence_table, (sequence2, sequence)).tolist()) # create list of coordinates for requrence plot x_rqa = [] y_rqa = [] for y in range(0, 2 * sequence2, 2): for x in range(0, 2 * sequence, 2): if recurrence_table[int(y / 2)][int(x / 2)] == 1: x_rqa.append(x) y_rqa.append((2 * sequence2 - y - 1)) multi_plot = plt.figure(figsize=(12, 9)) multi_plot.clear() ax = multi_plot.add_subplot(1, 1, 1) # ax1 = plt.subplot2grid((8, 8), (0, 0), colspan=6, rowspan=2) # ax1.plot(list(range(len(count_y))), count_y) # plt.ylim(0, max(count_y) + 1) # plt.xlim(0,len(count_y)-1) # ax2 = plt.subplot2grid((8, 8), (2, 0), rowspan=6, colspan=6) if sequence > 100 or sequence2 > 100: size = 0.5 else: size = 3 wsp = [[x, y] for x, y in zip(x_rqa, y_rqa)] print(wsp) if wsp: wsp_spr = wsp[0] x = [] y = [] while len(wsp) > 1: wsp.remove(wsp_spr) if [wsp_spr[0] + 2, wsp_spr[1] - 2] in wsp: x.append(wsp_spr[0]) y.append(wsp_spr[1]) wsp_spr = [wsp_spr[0] + 2, wsp_spr[1] - 2] print(x, y) else: x.append(wsp_spr[0]) y.append(wsp_spr[1]) wsp_spr = wsp[0] print(x, y) if len(x) == 1: ax.plot(x, y, 'ro', markersize=1.5) else: ax.plot(x, y, 'r') x = [] y = [] if len(wsp) == 1: x.append(wsp[0][0]) y.append(wsp[0][1]) if len(x) == 1: ax.plot(x, y, 'ro', markersize=1.5) else: ax.plot(x, y, 'r') x = [] y = [] plt.xlim(-1, (2 * sequence) - 2) plt.ylim(0, 2 * sequence2) plt.xticks(range(0, 2 * sequence, 2), f_sequence) plt.yticks(range(1, 2 * sequence2 + 1, 2), s_sequence[::-1]) minorLocator = MultipleLocator(5) minor_xticks = np.arange(1, 2 * sequence, 2) minor_yticks = np.arange(0, 2 * sequence2, 2) ax.xaxis.tick_top() ax.set_xticks(minor_xticks, minor=True) ax.set_yticks(minor_yticks, minor=True) plt.grid(which='minor', alpha=0.5) multi_plot.canvas.draw() multi_plot.savefig('static/RQA.png')
F_3 = -sum_Li3 F_3_p = -sum_Li3_p diff_F = -F_3 + F_3_p divide = dF / diff_F ## calc difference eps2 and eiz for with and without peak # ----------------------------------------------------------- diff_eps = y_peak - y_nopeak diff_eiz = eiz_peak - eiz_nopeak listofzeros = numpy.zeros(len(x_nopeak)) # plot line for y = 0 ## PLOTS # ------------------------------------------------------------- fig = pl.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.plot(x_peak, y_peak, color="g", label=r"Synthesized") # $\epsilon$"($\omega$)', linestyle='-') ax.plot(x_nopeak, y_nopeak, color="b", label=r"Ab initio") # $\epsilon$"($\omega$)', linestyle='-') ax.legend(loc="best") # pl.title(r'$\epsilon$"($\omega$) Ab Initio and Synthisized') pl.xlabel(r"$\omega$", size="large") pl.ylabel(r'$\epsilon$"($\omega$)') ax_inset = fig.add_axes([0.55, 0.42, 0.3, 0.3]) ax_inset.plot( x_nopeak * 1e-16, diff_eps, color="r", label=r'$\epsilon$"($\omega)_{synthesized}$-$\epsilon$"($\omega)_{ab\,initio}$', ) ax_inset.plot(x_nopeak * 1e-16, listofzeros, color="k", label=r'$\delta$$\epsilon$"($\omega$) = 0') # pl.title(r'Difference $\epsilon$"($\omega$)', size = 'small')
fig = pl.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] for r in range(len(A_dep)): labels = r'$A\, =\, %.2f$' % A_dep[r] for t in range(len(z_y)): sum_Li2_A_dep[t] = 0.0 for u in arange(1, 101): sum_Li2_A_dep[t] += (( (A_dep[r] / (A_dep[r] + 2. * z_y[t]**2 + 2))**2)**u) / (u**2) yA_dep[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))*\ (1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) yA_dep_exp[t] = (sum_Li2_A_dep[t])*\ ((1. - ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2))))**2)/\ ((A_dep[r]/(1.+z_y[t]**2)) / (2.+(A_dep[r]/(1.+z_y[t]**2)))))#*\ #(1./(1.+z_y[t]**2))/(1. + A_dep[r]/(1+z_y[t]**2)) Aiz = [2.0 * y_dep * dee for y_dep, dee in zip(yA_dep_exp, de_e)] ax.plot(n / 12., Aiz, linestyle=':', color='y') #, color = colors[r], label = labels) total = trapz(yA_dep, z_y) print total ax.plot(z_y, yA_dep) #, color = colors[r], label = labels) pl.xlabel(r'$\xi/\omega_{0}$', size=21) pl.ylabel(r'$ A(\xi/\omega_{0} ) $', size=21) pl.show() pl.close()