def plot_acf_pacf(timeSeries, nlags=40, alpha=0.05, method_acf=True, method_pacf='ywunbiased', legend=["ACF", "PACF"], labels=["timeSeries"]): valuesACF, confIntACF = tsa.acf(timeSeries, nlags=30, alpha=0.05, unbiased=True, qstat=False) # qstat: For LJung-Box values and pvalues: For Pvalues of this ## For some reason the first value of the PACF is 1, when it should not be defined valuesPACF, confIntPACF = tsa.pacf(timeSeries, nlags=30, alpha=0.05, method='ywunbiased') gl.set_subplots(2, 1) gl.stem([], valuesACF, labels=[labels[0], "lag", "ACF"], legend=[legend[0]]) # gl.plot([],confIntACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)], # lw = 1) plt.axhline(y=-1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) plt.axhline(y=1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) gl.stem([], valuesPACF, labels=[labels[0], "lag", "PACF"], legend=[legend[1]]) # gl.plot([],confIntPACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)]) plt.axhline(y=-1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) plt.axhline(y=1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3)
def plot_acf_pacf(timeSeries, nlags = 40, alpha = 0.05, method_acf = True, method_pacf = 'ywunbiased', legend = ["ACF", "PACF"], labels = ["timeSeries"]): valuesACF, confIntACF = tsa.acf(timeSeries, nlags = 30, alpha = 0.05, unbiased = True, qstat = False) # qstat: For LJung-Box values and pvalues: For Pvalues of this ## For some reason the first value of the PACF is 1, when it should not be defined valuesPACF, confIntPACF = tsa.pacf(timeSeries, nlags = 30, alpha = 0.05, method = 'ywunbiased') gl.set_subplots(2,1) gl.stem([],valuesACF, labels = [labels[0], "lag", "ACF"], legend = [legend[0]]) # gl.plot([],confIntACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)], # lw = 1) plt.axhline(y=-1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) plt.axhline(y=1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) gl.stem([],valuesPACF, labels = [labels[0], "lag", "PACF"], legend = [legend[1]]) # gl.plot([],confIntPACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)]) plt.axhline(y=-1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) plt.axhline(y=1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3)
def get_TMA(time_series, L): """ First it trains the data so that the prediction is maximized""" ### Training phase, we obtained the MSQE of the filter for predicting the next value time_series = time_series.flatten() Ns = time_series.size Xtrain, Ytrain = ul.windowSample(time_series, L) window = np.linalg.pinv((Xtrain.T).dot(Xtrain)) window = window.dot(Xtrain.T).dot(Ytrain) window = np.fliplr([window])[0] gl.stem([], window) sM = np.convolve(time_series.flatten(),window.flatten(), mode = "full") # print sM.shape sM = sM sM = sM/np.sum(window) # Divide so that it is the actual mean. sM[:L] = (np.ones((L,1)) * sM[L]).flatten() # Set the first ones equal to the first fully obtained stimator sM = sM[:-L+1] # Remove the last values since they hare convolved with 0's as well return sM
dates = Cartera.get_timeData(symbolIDs[symbol_ID_indx1],periods[0]).get_dates() #print dates[0], dates[26], dates[27] ################# Plotting the data ################# if(trading_graph): # Trading plot of the points ! title = "CLOSE Price, Volume and Return evolution" ax1 = gl.subplot2grid((5,1), (0,0), rowspan=2, colspan=1) gl.tradingBarChart(Cartera.get_timeData(symbolIDs[symbol_ID_indx1],periods[0]), ax = ax1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", labels = [title,"",symbolIDs[symbol_ID_indx1] +"(" +str(periods[0])+")"]) ax2 = gl.subplot2grid((5,1), (2,0), rowspan=1, colspan=1, sharex = ax1) gl.stem(dates, volume, ax = ax2, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis - Ny:4", labels = ["","",symbolIDs[0] +"("+ str(periods[0])+ "M)"], legend = [ "Volume"]) ax3 = gl.subplot2grid((5,1), (3,0), rowspan=2, colspan=1, sharex = ax1) gl.stem(dates, ret1, ax = ax3, dataTransform = dataTransform, AxesStyle = "Normal", labels = ["","",symbolIDs[0] +"("+ str(periods[0])+ "M)"], legend = ["Return"]) # gl.set_fontSizes(ax = [ax1,ax2,ax3], title = 20, xlabel = 20, ylabel = 20, legend = 20, xticks = 10, yticks = 10) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.01, hspace=0.01) gl.savefig(folder_images +'PriceAndReturns1Symbol_EM.png', dpi = 100, sizeInches = [22, 12])
alpha_stem = 0.5 marker_stem = [".",1,None] gl.init_figure(); ax1 = gl.subplot2grid((4,1), (0,0), rowspan=1, colspan=1) ax2 = gl.subplot2grid((4,1), (1,0), rowspan=1, colspan=1, sharex = ax1) ax3 = gl.subplot2grid((4,1), (2,0), rowspan=1, colspan=1, sharex = ax1) ax4 = gl.subplot2grid((4,1), (3,0), rowspan=1, colspan=1, sharex = ax1) ## Ax1 = Close price at the end of the sessions gl.plot(days_keys, C, ax = ax1, labels = ["Time variables","","Close Rate"], AxesStyle = "Normal - No xaxis", legend = ["Close Price"], color = "k") ## Ax2 = days gl.stem(days_keys, day_of_week, ax = ax2, labels = ["","","Day"], bottom = 0.0, AxesStyle = "Normal - No xaxis", alpha = alpha_stem, marker = marker_stem, color = "k", legend = ["Day"]) # Ax3 = week gl.stem(days_keys,week_of_year ,bottom = 0.0, ax = ax3, labels = ["","","Week"],AxesStyle = "Normal - No xaxis", alpha =alpha_stem, marker = marker_stem, color = "k", legend = ["Week"]) ## Ax4 = year gl.plot(days_keys,year, ax = ax4, labels = ["","","Year"],AxesStyle = "Normal", alpha = alpha_stem, color = "k", legend = ["Year"]) # Set final properties and save figure gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.05, hspace=0.05) gl.set_fontSizes(ax = [ax1,ax2,ax3,ax4], title = 20, xlabel = 20, ylabel = 20, legend = 15, xticks = 12, yticks = 12)
############## Average and Window ################ ax1 = gl.subplot2grid((1, 5), (0, 0), rowspan=1, colspan=3) title = "Price and SMA. " + str( symbols[0]) + "(" + ul5.period_dic[timeData.period] + ")" gl.plot(dates, [price, SMA], AxesStyle="Normal", labels=[title, "", r"Price ($\$$)"], legend=["Price", "SMA(%i)" % nMA1]) ax2 = gl.subplot2grid((1, 5), (0, 3), rowspan=1, colspan=2) gl.stem([], SMAw, nf=0, AxesStyle="Normal2", labels=["SMA Window", "lag", ""], legend=["SMAw(%i)" % nMA1], xlimPad=[0.1, 0.3], ylimPad=[0.1, 0.4], marker=[".", 10, None]) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.35, hspace=0) gl.savefig(folder_images + 'basicSMA.png', dpi=100, sizeInches=[14, 5]) """ 2nd GRAPH """ ############## PLOTTING ################ gl.set_subplots(3, 2)
Y = (np.sign(np.diff(X,n=1,axis = 0)) +1)/2.0 Y_noisy = (np.sign(np.diff(X_noisy,n=1,axis = 0)) +1)/2.0 ## Subselect both the signals X and the labels Y since we cannot know the prediction of the last sample. if (plot_labelling_signal and plot_flag): gl.set_subplots(2,1) # Plot the original signal and its labelling ! ax1 = gl.scatter(tgrid,X, lw = 1, alpha = 0.9, color = "k", nf = 1, labels = ["Original signal","",r"$\mu(t)$"]) gl.plot(tgrid,X, lw = 2, color = "k", ls = "--") gl.set_fontSizes( title = 20, xlabel = 15, ylabel = 20, legend = 12, xticks = 12, yticks = 12) gl.stem(tgrid[:-1,0], Y, sharex = ax1, nf = 1, labels = ["", "t","Y(t)"], bottom = 0.5) # Plot noisy part # gl.scatter(tgrid,X_noisy, lw = 1, alpha = 0.9, color = "k", nf = 1, # labels = ["Noisy signal","","X(t)"]) # gl.plot(tgrid,X_noisy, lw = 2, color = "k", ls = "--") # gl.stem(tgrid[:-1,0], Y_noisy, sharex = ax1, nf = 1, labels = ["", "t","Y_noise(t)"]) # gl.set_fontSizes( title = 20, xlabel = 15, ylabel = 20, legend = 12, xticks = 12, yticks = 12) gl.savefig(folder_images +'GP_labelling_of_the_signal.png', dpi = 100, sizeInches = [2*6.5, 2*2]) ## It would be nice to see !! # Generate a lot of random signals and compute the mean prediction of Y
SMA = timeData.SMA(n = nMA1) """ 1st GRAPH """ ############## Average and Window ################ ax1 = gl.subplot2grid((1,5), (0,0), rowspan=1, colspan=3) title = "Price and SMA. " + str(symbols[0]) + "(" + ul.period_dic[timeData.period]+ ")" gl.plot(dates, [price, SMA] ,AxesStyle = "Normal", labels = [title,"",r"Price ($\$$)"], legend = ["Price", "SMA(%i)"%nMA1]) ax2 = gl.subplot2grid((1,5), (0,3), rowspan=1, colspan=2) gl.stem([], SMAw, nf = 0, AxesStyle = "Normal2", labels = ["SMA Window","lag",""], legend = ["SMAw(%i)"%nMA1], xlimPad = [0.1,0.3], ylimPad = [0.1,0.4], marker = [".",10,None]) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.35, hspace=0) gl.savefig(folder_images +'basicSMA.png', dpi = 100, sizeInches = [14,5]) """ 2nd GRAPH """ ############## PLOTTING ################ gl.set_subplots(3,2) marker = [".",10,None] # Plotting the 3 of them at the same time. ax1 = gl.stem([], SMAw, nf = 1, labels = ["Windows L = %i"%nMA1,"","SMA"], legend = ["SMA(%i)"%nMA1],
gl.barchart(dates, dataHLOC) gl.plot(dates, EMAslow, legend=["Slow"], lw=1, color="b") gl.plot(dates, EMAfast, legend=["fast"], lw=1, color="r", xaxis_mode="hidden") ## Entry Axes ax2 = gl.plot(dates, ul.scale(EMAfast - EMAslow), legend=["Difference"], nf=1, sharex=ax1, labels=["", "", "Events"], fill=1, alpha=0.3) gl.stem(dates, crosses, legend=["TradeSignal"]) gl.scatter(dates, ul.scale(EMAfast - EMAslow), lw=0.5, alpha=0.5) gl.plot(dates, np.zeros(crosses.shape)) ## Exit Axes gl.add_hlines(datesExit, all_stops, ax=ax1, legend=["TrailingStop"], alpha=0.8, lw=0.2) ax3 = gl.plot(datesExit, ul.scale(-(all_stops - pCheckCross)), legend=["TrailingStop"], nf=1, sharex=ax1,
title = "CLOSE Price, Volume and Return evolution" ax1 = gl.subplot2grid((4,1), (0,0), rowspan=1, colspan=1) gl.tradingBarChart(Cartera.get_timeData(symbolIDs[symbol_ID_indx1],periods[0]), ax = ax1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", color = "k", labels = [title,"",symbolIDs[symbol_ID_indx1] +"(" +str(periods[0])+"M)"]) ax2 = gl.subplot2grid((4,1), (1,0), rowspan=1, colspan=1, sharex = ax1) gl.tradingBarChart(Cartera.get_timeData(symbolIDs[symbol_ID_indx2],periods[0]), ax = ax2, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", color = "k", labels = ["","",symbolIDs[symbol_ID_indx2] +"(" +str(periods[0])+"M)"]) ax3 = gl.subplot2grid((4,1), (2,0), rowspan=1, colspan=1) gl.stem(dates, ret1, ax = ax3, dataTransform = dataTransform, AxesStyle = "Normal", labels = ["","",symbolIDs[symbol_ID_indx1] +"("+ str(periods[0])+ "M)"], legend = ["Return"]) ax4 = gl.subplot2grid((4,1), (3,0), rowspan=1, colspan=1, sharex = ax1, sharey = ax3) gl.stem(dates, ret2, ax = ax4, dataTransform = dataTransform, AxesStyle = "Normal", labels = ["","",symbolIDs[symbol_ID_indx2] +"("+ str(periods[0])+ "M)"], legend = ["Return"]) # gl.set_fontSizes(ax = [ax1,ax2,ax3,ax4], title = 20, xlabel = 20, ylabel = 20, legend = 20, xticks = 10, yticks = 10) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.01, hspace=0.01) gl.savefig(folder_images +'PriceAndReturns2Symbol_EM.png', dpi = 100, sizeInches = [22, 12])
type_graph = 2 folder_images = "../pics/gl/" dpi = 100 sizeInches = [2*8, 2*3] # Subplot Type 1 if (type_graph == 1): gl.set_subplots(nr = 1, nc = 2) gl.plot(X,Y, nf = 1, color = "k", lw = 5, alpha = 0.7, labels = ["Sine chart","Time (s)", "Voltage(V)"], legend = ["Rolling measurement"]) gl.stem(X2,Y2, nf = 1, color = "k", lw = 2, alpha = 0.7, labels = ["Discrete window","Sample (k)", "Amplitud"], legend = ["Window values"]) gl.savefig(folder_images +'subplot1.png', dpi = dpi, sizeInches = sizeInches) # Subplot Type 2 if (type_graph == 2): ax1 = gl.subplot2grid((1,4), (0,0), rowspan=1, colspan=3) gl.plot(X,Y, nf = 0, color = "k", lw = 5, alpha = 0.7, labels = ["Sine chart","Time (s)", "Voltage(V)"], legend = ["Rolling measurement"]) # ax2 = gl.subplot2grid((1,4), (0,3), rowspan=1, colspan=1) gl.plot(X2,Y2, nf = 0, color = "k", lw = 2, alpha = 0.7,
########## Plotting ! #################### gl.set_subplots(3,1) ## Price Axes ax1 = gl.plot(dates,price, legend = ["Price"], labels = ["Crossing MA Strategy", "","Price"], alpha = 0, nf = 1) gl.barchart(dates, dataHLOC) gl.plot(dates,EMAslow, legend = ["Slow"], lw = 1, color = "b") gl.plot(dates,EMAfast, legend = ["fast"], lw = 1, color = "r", xaxis_mode = "hidden") ## Entry Axes ax2 = gl.plot(dates, ul.scale(EMAfast - EMAslow), legend = ["Difference"] ,nf = 1, sharex = ax1, labels = ["","","Events"], fill = 1, alpha = 0.3) gl.stem(dates,crosses, legend = ["TradeSignal"] ) gl.scatter(dates, ul.scale(EMAfast - EMAslow), lw = 0.5, alpha = 0.5) gl.plot(dates,np.zeros(crosses.shape)) ## Exit Axes gl.add_hlines(datesExit, all_stops, ax = ax1, legend = ["TrailingStop"], alpha = 0.8, lw = 0.2) ax3 = gl.plot(datesExit, ul.scale(-(all_stops - pCheckCross)), legend = ["TrailingStop"] ,nf = 1, sharex = ax1, labels = ["","","TrailingStop"], lw = 0.5, alpha = 0.5, fill = 1) gl.stem(datesExit,exitcrosses, legend = ["TradeSignal"] ) gl.scatter(datesExit, ul.scale(-(all_stops - pCheckCross)), lw = 0.5, alpha = 0.5) gl.add_hlines(datesExit2, all_stops2, ax = ax1, legend = ["TrailingStop2"], alpha = 0.8, lw = 0.2) gl.plot(datesExit2, ul.scale(all_stops2 - pCheckCross2), legend = ["TrailingStop2"], lw = 0.5, alpha = 0.5, fill = 1) gl.stem(datesExit2,exitcrosses2, legend = ["TradeSignal"] ) gl.scatter(datesExit2, ul.scale(all_stops2 - pCheckCross2), lw = 0.5, alpha = 0.5)
marker_stem = [".",1,None] train_color = "b" test_color = "r" gl.init_figure(); ax1 = gl.subplot2grid((4,1), (0,0), rowspan=1, colspan=1) ax2 = gl.subplot2grid((4,1), (1,0), rowspan=1, colspan=1, sharex = ax1) ax3 = gl.subplot2grid((4,1), (2,0), rowspan=1, colspan=1, sharex = ax1) ax4 = gl.subplot2grid((4,1), (3,0), rowspan=1, colspan=1, sharex = ax1) ## Ax1 = Close price at the end of the sessions gl.plot(days_keys, C, ax = ax1, labels = ["Results " + key_classifier,"","Close Rate"], AxesStyle = "Normal - No xaxis", legend = ["Close Rate"]) ## Ax2 = 1 if the stock has gone up, zero if it has gone down gl.stem(dates_train, Ytrain_reg, ax = ax2, labels = ["","","Target_reg"], bottom = 0.0, AxesStyle = "Normal - No xaxis", alpha = alpha_stem, marker = marker_stem, color = train_color, legend = ["tr"]) gl.stem(dates_test, Ytest_reg, ax = ax2, labels = ["","","Target_reg"],bottom = 0.0,AxesStyle = "Normal - No xaxis", color = test_color , alpha = alpha_stem, marker = marker_stem, legend = ["tst"]) # Ax3 = The estimates probability for train and test gl.stem(dates_train,Ypredict_train_proba ,bottom = 0.5, ax = ax3, labels = ["","",r"$\hat{Y}$"],AxesStyle = "Normal - No xaxis", alpha =alpha_stem, marker = marker_stem, color = train_color, legend = ["tr"]) gl.stem(dates_test, Ypredict_test_proba,bottom = 0.5, ax = ax3, labels = ["","",r"$\hat{Y}$"],color = test_color,ylim = [0.0,1.0],alpha = alpha_stem, AxesStyle = "Normal - No xaxis", marker = marker_stem, legend = ["tst"]) # ylim = [0.0,1.0] ## Ax4 = Cross Entropy of the samples for train and test gl.stem(dates_train,train_cross_entropy ,bottom = 0.0, ax = ax4, labels = ["","","CE"],AxesStyle = "Normal", alpha = alpha_stem, marker = marker_stem, color = train_color, legend = ["tr"]) gl.stem(dates_test, test_cross_entropy,bottom = 0.0, ax = ax4, color = test_color,AxesStyle = "Normal", alpha = alpha_stem,marker = marker_stem, legend = ["tst"])
Returns = timeData.get_timeSeriesReturn(seriesNames = ["Close"]); CumReturns = timeData.get_timeSeriesCumReturn(seriesNames = ["Close"]); nSMA = 10 SMA = timeData.SMA(n = nSMA) ax1 = gl.plot(dates, SMA, labels = [timeData.symbolID + str(timeData.period), "Time", "Price"], legend = ["SMA(%i)" % nSMA], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", color = "cobalt blue") gl.barchart(dates, dataHLOC, lw = 2, dataTransform = dataTransform, color = "k", AxesStyle = "Normal - No xaxis", legend = ["OHCL"]) # Notice the Weekends and the displacement between bars and step ############# 2: Volume gl.stem(dates, volume, sharex = ax1, labels = ["", "Time", "Volume"], legend = ["Volume"], nf = 1, alpha = 0.8, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis") ############# 3: Returns gl.stem(dates, Returns, sharex = ax1, labels = ["", "Time", "Return"], legend = ["Return"], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis") ############# 4: Commulative Returns seriesNames = ["Close"] gl.plot(dates, CumReturns, sharex = ax1,labels = ["", "Time", "Cum Return"], legend = ["Cum Return"], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal") ############## Dayly things obtaining #################################### # We separate the data into a list of days in order to be able to analyze it easier
ax1 = gl.subplot2grid((5, 1), (0, 0), rowspan=2, colspan=1) gl.tradingBarChart( Cartera.get_timeData(symbolIDs[symbol_ID_indx1], periods[0]), ax=ax1, dataTransform=dataTransform, AxesStyle="Normal - No xaxis", labels=[ title, "", symbolIDs[symbol_ID_indx1] + "(" + str(periods[0]) + ")" ]) ax2 = gl.subplot2grid((5, 1), (2, 0), rowspan=1, colspan=1, sharex=ax1) gl.stem(dates, volume, ax=ax2, dataTransform=dataTransform, AxesStyle="Normal - No xaxis - Ny:4", labels=["", "", symbolIDs[0] + "(" + str(periods[0]) + "M)"], legend=["Volume"]) ax3 = gl.subplot2grid((5, 1), (3, 0), rowspan=2, colspan=1, sharex=ax1) gl.stem(dates, ret1, ax=ax3, dataTransform=dataTransform, AxesStyle="Normal", labels=["", "", symbolIDs[0] + "(" + str(periods[0]) + "M)"], legend=["Return"]) # gl.set_fontSizes(ax=[ax1, ax2, ax3], title=20,
############################################################ periods = mySymbol.get_periods() gl.set_subplots(4, 1, sharex=True) # TODO: Be able to automatize the shareX thing for period in periods: myTimeData = mySymbol.get_timeDataObject(period) price = myTimeData.get_timeSeries(["Close"]) volume = myTimeData.get_timeSeries(["Volume"]) dates = myTimeData.get_dates() gl.plot(dates, price, labels=["", "", mySymbol.symbol], legend=[str(period)]) gl.stem(dates, volume, legend=[str(period)], na=1, nf=0) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0) # TODO: We can also use the library of indicators especifing the period. # If no period specified, we use the dayly or the bigges one. #######################
## Ax1 = Close price at the end of the sessions gl.plot(days_keys, C, ax=ax1, labels=["Time variables", "", "Close Rate"], AxesStyle="Normal - No xaxis", legend=["Close Price"], color="k") ## Ax2 = days gl.stem(days_keys, day_of_week, ax=ax2, labels=["", "", "Day"], bottom=0.0, AxesStyle="Normal - No xaxis", alpha=alpha_stem, marker=marker_stem, color="k", legend=["Day"]) # Ax3 = week gl.stem(days_keys, week_of_year, bottom=0.0, ax=ax3, labels=["", "", "Week"], AxesStyle="Normal - No xaxis", alpha=alpha_stem, marker=marker_stem, color="k",
dates = timeData.get_dates() df = timeData.get_timeData() # Momentum and Rate of convergence nAD = 5 ACCDIST = timeData.ACCDIST(n=nAD) # Plotting gl.set_subplots(2, 1) gl.plot(dates, price, nf=1, labels=["Momentum Indicators ACC DIST", "", "Price"], legend=["Price", " Momentum", "ROC"]) vol = timeData.get_timeSeries(["Volume"]) gl.stem(dates, vol, nf=0, na=1, legend=["Volume"]) gl.plot(dates, ACCDIST, nf=1, na=0, legend=["ACCDIST(%i)" % nMOM]) gl.plot(dates, np.zeros((dates.size, 1)), nf=0, na=0) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0) gl.savefig(folder_images + 'AC.png', dpi=100, sizeInches=[2 * 8, 2 * 2]) ######################################################### # Oscillators
# Set the timeSeries to operate with. mySymbol.set_seriesNames(["Close"]) ############################################################ ###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############ ############################################################ periods = mySymbol.get_periods() gl.set_subplots(4,1, sharex = True) # TODO: Be able to automatize the shareX thing for period in periods: myTimeData = mySymbol.get_timeDataObject(period) price = myTimeData.get_timeSeries(["Close"]) volume = myTimeData.get_timeSeries(["Volume"]) dates = myTimeData.get_dates() gl.plot(dates, price, labels = ["", "", mySymbol.symbol], legend = [str(period)]) gl.stem(dates, volume, legend = [str(period)], na = 1, nf = 0) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0) # TODO: We can also use the library of indicators especifing the period. # If no period specified, we use the dayly or the bigges one. #######################
EMAw = indl.get_EMA(delta, nHMA, cval = 1) dEMAw = bMA.convolve(EMAw, diff_final) # EMAEMA = bMA.diff(EMAEMA, cval = np.nan) # EMAEMA = indl.get_EMA(diffw1, nHMA, cval = 1) ## Plotting just the 3 windows gl.set_subplots(1,3) marker = [".",20,"r"] lw = 4 # Plotting the 3 of them at the same time. ax1 = gl.stem([], diffw1, nf = 1, lw = lw, labels = ["MOMw(%i)"%ndiff1,"lag","Value"], xlimPad = [0.1,0.3], ylimPad = [0.1,0.1], marker = marker, AxesStyle = "Normal2") gl.stem([], diffw2, nf = 1, sharex = ax1, sharey = ax1,lw = lw, labels = ["MOMw(%i)"%ndiff2,"lag",""], xlimPad = [0.1,0.3], ylimPad = [0.1,0.1], marker = marker, AxesStyle = "Normal2 - No yaxis") gl.stem([], diffw3, nf = 1,sharex = ax1, sharey = ax1,lw = lw, labels = ["MOMw(%i)"%ndiff3,"lag",""], xlimPad = [0.1,0.3], ylimPad = [0.1,0.1], marker = marker, AxesStyle = "Normal2 - No yaxis") gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.050, hspace=0.01) gl.savefig(folder_images +'MOMw.png',
alpha=0.9, color="k", nf=1, labels=["Original signal", "", r"$\mu(t)$"]) gl.plot(tgrid, X, lw=2, color="k", ls="--") gl.set_fontSizes(title=20, xlabel=15, ylabel=20, legend=12, xticks=12, yticks=12) gl.stem(tgrid[:-1, 0], Y, sharex=ax1, nf=1, labels=["", "t", "Y(t)"], bottom=0.5) # Plot noisy part # gl.scatter(tgrid,X_noisy, lw = 1, alpha = 0.9, color = "k", nf = 1, # labels = ["Noisy signal","","X(t)"]) # gl.plot(tgrid,X_noisy, lw = 2, color = "k", ls = "--") # gl.stem(tgrid[:-1,0], Y_noisy, sharex = ax1, nf = 1, labels = ["", "t","Y_noise(t)"]) # gl.set_fontSizes(title=20, xlabel=15, ylabel=20, legend=12, xticks=12, yticks=12)
x = np.array(range(C.size)) + cumulated_samples cumulated_samples += C.size gl.plot(x, C, ax=ax1, legend=legend, color="k", alpha=alpha, labels=[title, "", r"Rate"], AxesStyle="Normal - No xaxis") gl.stem(x, V, ax=ax2, legend=legend, color="k", alpha=alpha, labels=[title, "", r"Rate"], AxesStyle="Normal - No xaxis") gl.set_fontSizes(ax=[ax1], title=20, xlabel=20, ylabel=20, legend=10, xticks=10, yticks=10) image_name = "dayly_examples" gl.savefig(folder_images + image_name, dpi=100, sizeInches=[20, 7])
print ("Computing batch %i/%i"%(step, model.input.epoch_size)) vals = session.run(fetches, feed_dict) state = vals["final_state"] output = vals["output"] input_i = vals["input"] outputs.append(output) inputs.append(input_i) targets.append(vals["targets"]) if (step == 100): break; if (plot_data): batch_i = 5 data = np.array(inputs[batch_i][0])[:,[0]] labels = np.array(targets[batch_i][0])[:] predicted = np.array(outputs[batch_i][0])[:,[1]] #print(data) #print(labels) #print (predicted) labels_chart = ["Example output for medium noise level", "","X[n]"] gl.set_subplots(3,1) ax1 = gl.plot(np.array(range(data.size)), data, nf = 1, labels = labels_chart, legend = ["X[n]"]) ax2 = gl.stem(np.array(range(data.size)),labels, nf = 1, sharex = ax1, labels = ["","","Y[n]"], bottom = 0.5, legend = ["Targets Y[n]"]) gl.stem(np.array(range(data.size)),predicted, nf = 1, sharex = ax1, sharey = ax2, labels = ["","n","O[n]"],bottom = 0.5, legend = ["Predictions O[n]"]) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.2, hspace=0.01)
title = "Price evolution for 2 securities" ax1 = gl.tradingBarChart(Cartera.get_timeData(symbolIDs[0],15), nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", labels = [title,"",symbolIDs[0] +"(15M)"]) gl.tradingBarChart(Cartera.get_timeData(symbolIDs[1],15), nf = 1, sharex = ax1, dataTransform = dataTransform, AxesStyle = "Normal", labels = ["","",symbolIDs[1] +"(15M)"]) gl.savefig(folder_images +'PriceEvolution2Symb15.png', dpi = 100, sizeInches = [14, 7]) # Returns stem plot of the points gl.set_subplots(2,1) title = "Return for 2 securities" ax1 = gl.stem(dates, ret1, nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", labels = [title,"",symbolIDs[0] +"(15M)"]) gl.stem(dates, ret2, nf = 1, dataTransform = dataTransform, sharex = ax1, AxesStyle = "Normal", labels = ["","",symbolIDs[1] +"(15M)"]) gl.savefig(folder_images +'Returns2Symb15.png', dpi = 100, sizeInches = [14, 7]) ########################################################################## ################# PREPROCESS DATA ###################################### ########################################################################## ## Set GAP return as NAN gap_ret = np.where(dates.time == dates[0].time())[0] ret1[gap_ret,:] = np.NaN
price = timeData.get_timeSeries(["Close"]); dates = timeData.get_dates() df = timeData.get_timeData() # Momentum and Rate of convergence nAD = 5 ACCDIST = timeData.ACCDIST(n = nAD) # Plotting gl.set_subplots(2,1) gl.plot(dates, price , nf = 1, labels = ["Momentum Indicators ACC DIST","","Price"], legend = ["Price", " Momentum", "ROC"]) vol = timeData.get_timeSeries(["Volume"]) gl.stem(dates, vol , nf = 0, na = 1, legend = ["Volume"]) gl.plot(dates, ACCDIST , nf = 1, na = 0, legend = ["ACCDIST(%i)"%nMOM]) gl.plot(dates, np.zeros((dates.size,1)) , nf = 0, na = 0) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0) gl.savefig(folder_images +'AC.png', dpi = 100, sizeInches = [2*8, 2*2]) ######################################################### # Oscillators
nf=1, sharex=ax1, dataTransform=dataTransform, AxesStyle="Normal", labels=["", "", symbolIDs[1] + "(15M)"]) gl.savefig(folder_images + 'PriceEvolution2Symb15.png', dpi=100, sizeInches=[14, 7]) # Returns stem plot of the points gl.set_subplots(2, 1) title = "Return for 2 securities" ax1 = gl.stem(dates, ret1, nf=1, dataTransform=dataTransform, AxesStyle="Normal - No xaxis", labels=[title, "", symbolIDs[0] + "(15M)"]) gl.stem(dates, ret2, nf=1, dataTransform=dataTransform, sharex=ax1, AxesStyle="Normal", labels=["", "", symbolIDs[1] + "(15M)"]) gl.savefig(folder_images + 'Returns2Symb15.png', dpi=100, sizeInches=[14, 7]) ##########################################################################
# Subplot Type 1 if (type_graph == 1): gl.set_subplots(nr=1, nc=2) gl.plot(X, Y, nf=1, color="k", lw=5, alpha=0.7, labels=["Sine chart", "Time (s)", "Voltage(V)"], legend=["Rolling measurement"]) gl.stem(X2, Y2, nf=1, color="k", lw=2, alpha=0.7, labels=["Discrete window", "Sample (k)", "Amplitud"], legend=["Window values"]) gl.savefig(folder_images + 'subplot1.png', dpi=dpi, sizeInches=sizeInches) # Subplot Type 2 if (type_graph == 2): ax1 = gl.subplot2grid((1, 4), (0, 0), rowspan=1, colspan=3) gl.plot(X, Y, nf=0, color="k", lw=5, alpha=0.7, labels=["Sine chart", "Time (s)", "Voltage(V)"],
gl.tradingBarChart( Cartera.get_timeData(symbolIDs[symbol_ID_indx2], periods[0]), ax=ax2, dataTransform=dataTransform, AxesStyle="Normal - No xaxis", color="k", labels=[ "", "", symbolIDs[symbol_ID_indx2] + "(" + str(periods[0]) + "M)" ]) ax3 = gl.subplot2grid((4, 1), (2, 0), rowspan=1, colspan=1) gl.stem(dates, ret1, ax=ax3, dataTransform=dataTransform, AxesStyle="Normal", labels=[ "", "", symbolIDs[symbol_ID_indx1] + "(" + str(periods[0]) + "M)" ], legend=["Return"]) ax4 = gl.subplot2grid((4, 1), (3, 0), rowspan=1, colspan=1, sharex=ax1, sharey=ax3) gl.stem(dates, ret2, ax=ax4, dataTransform=dataTransform, AxesStyle="Normal",
labels=["Crossing MA Strategy", "", "Price"], nf=1) gl.plot(dates, EMAslow, legend=["Slow"], lw=3) gl.plot(dates, EMAfast, legend=["fast"]) ax2 = gl.plot(dates, ul.scale(EMAfast - EMAslow), legend=["Difference"], nf=1, sharex=ax1, labels=["", "", "Events"], fill=1, alpha=0.3) gl.stem( dates, crosses, legend=["TradeSignal"], ) gl.scatter(dates, ul.scale(EMAfast - EMAslow), lw=0.5, alpha=0.5) gl.plot(dates, np.zeros(crosses.shape)) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.10, hspace=0.01) trade_events = myEstrategia.get_TradeEvents() # We can observe the apparent delay !
dates = Cartera.symbols[symbol1].TDs[period1].get_dates() ########## Plotting ! #################### gl.set_subplots(4,1) ## Plot both prices and EMAs ax1 = gl.plot(dates,price, legend = ["Price"], labels = ["Crossing MA Strategy", "","Price"], alpha = 0, nf = 1) title = "Bar Chart. " + str(symbols[0]) + "(" + ul.period_dic[timeData.period]+ ")" timeData = Cartera.symbols[] gl.tradingBarChart(timeData, ax = ax1, legend = ["Close price"], color = "k", labels = [title,"",r"Price ($\$$)"], AxesStyle = "Normal - No xaxis") gl.plot(dates,EMAslow, legend = ["Slow"], lw = 1, color = "b") gl.plot(dates,EMAfast, legend = ["fast"], lw = 1, color = "r", xaxis_mode = "hidden") ## Entry Axes ax2 = gl.plot(dates, ul.scale(EMAfast - EMAslow), legend = ["Difference"] ,nf = 1, sharex = ax1, labels = ["","","Events"], fill = 1, alpha = 0.3) gl.stem(dates,crosses, legend = ["TradeSignal"] ) gl.scatter(dates, ul.scale(EMAfast - EMAslow), lw = 0.5, alpha = 0.5) gl.plot(dates,np.zeros(crosses.shape)) # We can observe the apparent delay ! #crosses, dates = Hitler.RobustXingAverages(symbols[0], Ls_list,Ll_list) #
symbolID = symbolIDs_pf[i] myTimeData = myPortfolio.get_symbols([symbolID])[0].get_timeData(period) returns = myTimeData.get_timeSeriesReturn(["Close"]) dates = myTimeData.get_dates() AxesStyle = " - No xaxis" if (i == len(symbolIDs_pf) -1): AxesStyle = "" if (i == 0): title = "Bar Chart. " + str(symbolIDs) + r" . Price ($\$$)" title2 = "Return" else: title = "" title2 = "" ylabel = symbolID + " (" + ul.period_dic[myTimeData.period] + ")" ax = gl.tradingBarChart(myTimeData, legend = ["Close price"], color = "k", nf = 1, sharex = axeshare, labels = [title,"",ylabel], AxesStyle = "Normal" + AxesStyle) # dataTransform = dataTransform) ax = gl.stem(dates, returns, legend = ["Return"], color = "k", nf = 1, sharex = axeshare, labels = [title2,"",""], AxesStyle = "Normal" + AxesStyle + " - No yaxis") # dataTransform = dataTransform) axeshare = ax gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.10, hspace=0) image_name = "differentSymbols.png" gl.savefig(folder_images + image_name, dpi = 100, sizeInches = [30, 12])
volume = timeData.get_timeSeries(["Volume"]); Returns = timeData.get_timeSeriesReturn(seriesNames = ["Close"]); CumReturns = timeData.get_timeSeriesCumReturn(seriesNames = ["Close"]); nSMA = 10 SMA = timeData.SMA(n = nSMA) ax1 = gl.plot(dates, SMA, labels = [timeData.symbolID + str(timeData.period), "Time", "Price"], legend = ["SMA(%i)" % nSMA], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", color = "cobalt blue") gl.barchart(dates, dataHLOC, lw = 2, dataTransform = dataTransform, color = "k", AxesStyle = "Normal - No xaxis") # Notice the Weekends and the displacement between bars and step ############# 2: Volume gl.stem(dates, volume, sharex = ax1, labels = [timeData.symbolID + str(timeData.period), "Time", "Volume"], legend = ["Volume"], nf = 1, alpha = 0.5, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis") ############# 3: Returns gl.stem(dates, Returns, sharex = ax1, labels = [timeData.symbolID + str(timeData.period), "Time", "Return"], legend = ["Return"], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis") ############# 4: Commulative Returns seriesNames = ["Close"] gl.plot(dates, CumReturns, sharex = ax1,labels = [timeData.symbolID + str(timeData.period), "Time", "Cum Return"], legend = ["Cum Return"], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal") gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0)
ax4 = gl.subplot2grid((4, 1), (3, 0), rowspan=1, colspan=1, sharex=ax1) ## Ax1 = Close price at the end of the sessions gl.plot(days_keys, C, ax=ax1, labels=["Results " + key_classifier, "", "Close Rate"], AxesStyle="Normal - No xaxis", legend=["Close Rate"]) ## Ax2 = 1 if the stock has gone up, zero if it has gone down gl.stem(dates_train, Ytrain_reg, ax=ax2, labels=["", "", "Target_reg"], bottom=0.0, AxesStyle="Normal - No xaxis", alpha=alpha_stem, marker=marker_stem, color=train_color, legend=["tr"]) gl.stem(dates_test, Ytest_reg, ax=ax2, labels=["", "", "Target_reg"], bottom=0.0, AxesStyle="Normal - No xaxis", color=test_color, alpha=alpha_stem, marker=marker_stem, legend=["tst"])