def plot(outright_index, fly_index, hedged_index): date = m["DateTime"].tolist() outright_prices = m[outright_index].values.tolist() fly_prices = m[fly_index].values.tolist() hedged_prices = m[hedged_index].values.tolist() upper_band = (m[hedged_index+"_mean"]+EntryStd*m[hedged_index+"_std"]).values.tolist() lower_band = (m[hedged_index+"_mean"]-EntryStd*m[hedged_index+"_std"]).values.tolist() buy_dates = [x[0] for x in trade_recorder[hedged_index].trades if x[2]>0] buy_prices = [x[1] for x in trade_recorder[hedged_index].trades if x[2]>0] sell_dates = [x[0] for x in trade_recorder[hedged_index].trades if x[2]<0] sell_prices = [x[1] for x in trade_recorder[hedged_index].trades if x[2]<0] fig, (ax1, ax2, ax3) = plt.subplots(3, sharex = True) mondays = WeekdayLocator(MONDAY) mondays.MAXTICKS = 2000 alldays = DayLocator() # minor ticks on the days alldays.MAXTICKS = 2000 weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 ax1.xaxis.set_major_locator(mondays) ax1.xaxis.set_minor_locator(alldays) ax1.xaxis.set_major_formatter(weekFormatter) ax1.plot(date, outright_prices) ax2.plot(date, fly_prices) ax3.plot(date, hedged_prices) ax3.plot(date, upper_band, color='k') ax3.plot(date, lower_band, color='k') ax3.plot(buy_dates, buy_prices, "^", markersize = 5, color='m') ax3.plot(sell_dates, sell_prices, "v", markersize = 5, color='k') ax1.xaxis_date() ax1.autoscale_view()
def plot_trade(self, symbol, init_index = None, end_index=None, PnL=False, ATR=False): if init_index == None: init_index = 0 init_date = b.bars[symbol][init_index]["D"] if end_index == None: end_index = len(b.bars[symbol]) end_date = b.bars[symbol][end_index-1]["D"] mondays = WeekdayLocator(MONDAY) mondays.MAXTICKS = 2000 alldays = DayLocator() # minor ticks on the days alldays.MAXTICKS = 2000 weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 history = [(date2num(x["D"]), x["O"], x["H"], x["L"], x["C"]) for x in b.bars[symbol][init_index:end_index]] if PnL or ATR: fig, (ax, ax2) = plt.subplots(2, sharex = True) else: fig, ax = plt.subplots() ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) candlestick_ohlc(ax, history) buys = [(x["Date"], x["Price"]) for x in self.trades[symbol] if (x["Lots"] > 0 and x["Date"] > init_date and x["Date"]<end_date) ] buy_dates, buy_values = zip(*buys) ax.plot(buy_dates, buy_values, "^", markersize = 5, color='m') sells = [(x["Date"], x["Price"]) for x in self.trades[symbol] if (x["Lots"] < 0 and x["Date"] > init_date and x["Date"]<end_date)] sell_dates, sell_values = zip(*sells) ax.plot(sell_dates, sell_values, "v", markersize = 5, color='k') ax.xaxis_date() ax.autoscale_view() if PnL: equity_history = [(date, record["equity"], record["drawdown"]) for date, record in self.history.items()] dates, values, drawdowns = zip(*equity_history) ax2 = fig.add_subplot(212) ax2.plot(dates, values, 'b-') elif ATR: equity_history = [(x["D"], x["ATR"]) for x in self.bars[symbol][init_index:end_index]] dates, values = zip(*equity_history) ax2 = fig.add_subplot(212) ax2.plot(dates, values, 'b-') ## ax3 = ax2.twinx() ## ax3.plot(dates, drawdowns, 'r-') plt.show()
def draw(self): if self.th != None: self.fig, (self.ax1, self.ax2, self.ax3) = plt.subplots(3, 1, sharex=True) else: self.fig, (self.ax1, self.ax2) = plt.subplots(2, 1, sharex=True) self.ax1_1 = self.ax1.twinx() # set figure self.fig.suptitle(self.title, fontsize=18) #self.fig.autofmt_xdate(rotation=70) self.draw_basic(self.ax1, self.ax1_1) # plot the KD self.ax2_lines = dict() self.ax2_lines['k'] = self.ax2.plot(self.df['Date'], self.df['k'])[0] self.ax2_lines['d'] = self.ax2.plot(self.df['Date'], self.df['d'])[0] # plot RSI self.ax2_lines['RSI'] = self.ax2.plot(self.df['Date'], self.df['RSI'])[0] self.ax2_lines['RSI'].set_linewidth(0.3) self.ax2.legend(['K', 'D', 'RSI'], loc='upper left') plt.connect('motion_notify_event', self.mouse_move) #plt.connect('scroll_event', cursor.on_scroll) plt.connect('button_press_event', self.on_scroll) plt.connect('key_press_event', self.on_key) ymin = np.min(self.df['k']) if np.min(self.df['k']) < np.min( self.df['d']) else np.min(self.df['d']) ymax = np.max(self.df['k']) if np.max(self.df['k']) > np.max( self.df['d']) else np.max(self.df['d']) ymin = ymin - 5 if (ymax - 5) > 0 else 0 ymax = ymax + 5 if (ymax + 5) < 100 else 100 self.ax2.set_ylim(ymin, ymax) # set mouse scroll event # draw lines for cursor focus self.lx1 = self.ax1.axhline(color='k', y=self.y1_df.loc[0], linewidth=0.5, linestyle='--') # the horiz line self.ly1 = self.ax1.axvline(color='k', x=self.x_df.loc[0], linewidth=0.5, linestyle='--') # the vert line self.lx2_k = self.ax2.axhline(color='k', y=self.y2_k_df.loc[0], linewidth=0.5, linestyle='--') # the horiz line self.ly2_k = self.ax2.axvline(color='k', x=self.x_df.loc[0], linewidth=0.5, linestyle='--') # the vert line self.lx2_d = self.ax2.axhline(color='k', y=self.y2_k_df.loc[0], linewidth=0.5, linestyle='--') # the horiz line self.ly2_d = self.ax2.axvline(color='k', x=self.x_df.loc[0], linewidth=0.5, linestyle='--') # the vert line # text location in axes coords self.txt1 = self.ax1.text(0, 1.05, "", transform=self.ax1.transAxes) self.txt2 = self.ax2.text(0, 1.05, "", transform=self.ax2.transAxes) if self.th != None: self.ax3_lines = [] for (th_title, th) in self.th: marks = th['Date'][th['Buy'] != 0].index.tolist() #marks = [1, 3, 5, 7, 9] _line = self.ax3.plot(self.df['Date'], th['Total'], label=th_title, marker='.', markevery=marks) self.ax3_lines.append(_line[0]) _line[0].set_linestyle('--') _line[0].set_linewidth(0.5) self.ax3_lines[self.focus_th_idx].set_linestyle('-') self.ax3_lines[self.focus_th_idx].set_linewidth(1.5) lines, labels = self.ax3.get_legend_handles_labels() self.ax3.legend(lines, labels, loc='upper left') #self.ax3.legend(self.focus_th_title, loc='upper right') self.ax3.grid() th = self.th[self.focus_th_idx][1] self.ly3 = self.ax3.axvline(color='k', x=th['Date'].loc[0], linewidth=0.5, linestyle='--') # the vert line self.txt3 = self.ax3.text(0, 1.05, "", transform=self.ax3.transAxes) self.ax2.grid() # for x-axis tick label if len(self.df) < 40: self.ax1.xaxis.set_major_locator(DayLocator()) elif len(self.df) < 100: self.ax1.xaxis.set_major_locator(WeekdayLocator()) self.ax1.xaxis.set_minor_locator(DayLocator()) else: self.ax1.xaxis.set_major_locator(MonthLocator()) self.ax1.xaxis.set_minor_locator(WeekdayLocator()) self.ax1.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) self.ax1.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') if self.pngName == None: plt.show() else: plt.savefig(self.pngName)
def pandas_candlestick_ohlc(dat, stick="day", otherseries=None): """ :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo" :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed. """ mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days dayFormatter = DateFormatter('%d') # e.g., 12 # Create a new DataFrame which includes OHLC data for each period specified by stick input transdat = dat.loc[:, ["Open", "High", "Low", "Close"]] if (type(stick) == str): if stick == "day": plotdat = transdat stick = 1 # Used for plotting elif stick in ["week", "month", "year"]: if stick == "week": transdat["week"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[1]) # Identify weeks elif stick == "month": transdat["month"] = pd.to_datetime(transdat.index).map( lambda x: x.month) # Identify months transdat["year"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[0]) # Identify years grouped = transdat.groupby(list(set( ["year", stick]))) # Group by year and other appropriate variable plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) # Create empty data frame containing what will be plotted for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { "Open": group.iloc[0, 0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1, 3] }, index=[group.index[0]])) if stick == "week": stick = 5 elif stick == "month": stick = 30 elif stick == "year": stick = 365 elif (type(stick) == int and stick >= 1): transdat["stick"] = [ np.floor(i / stick) for i in range(len(transdat.index)) ] grouped = transdat.groupby("stick") plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) # Create empty data frame containing what will be plotted for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { "Open": group.iloc[0, 0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1, 3] }, index=[group.index[0]])) else: raise ValueError( 'Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer' ) # Set plot parameters, including the axis object ax used for plotting fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'): weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) else: weekFormatter = DateFormatter('%b %d, %Y') ax.xaxis.set_major_formatter(weekFormatter) ax.grid(True) # Create the candelstick chart candlestick_ohlc(ax, list( zip(list(mdates.date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(), plotdat["Low"].tolist(), plotdat["Close"].tolist())), colorup="black", colordown="red", width=stick * .4) # Plot other series (such as moving averages) as lines if otherseries != None: if type(otherseries) != list: otherseries = [otherseries] dat.loc[:, otherseries].plot(ax=ax, lw=1.3, grid=True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
from pylab import * from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo, candlestick, plot_day_summary, candlestick2 from matplotlib.font_manager import FontProperties if __name__ == '__main__': font = FontProperties(fname=r"t:\Windows\Fonts\simsun.ttc",size=18) # 定义起始、终止日期和股票代码 date1 = ( 2013, 1, 1 ) date2 = ( 2013, 8, 1 ) date3 = ( 2013, 5, 1 ) stock_num = '600036.ss' # 定义日期格式 mondays = WeekdayLocator(MONDAY) #major ticks on the mondays alldays = DayLocator() #minor ticks on the days weekFormatter = DateFormatter('%b %d') # Jan 12 dayFormatter = DateFormatter('%d') # 12 # 获取股票数据 quotes = quotes_historical_yahoo(stock_num, date1, date2) quotes2 = quotes_historical_yahoo(stock_num, date1, date3) if len(quotes) == 0: raise SystemExit # 绘制蜡烛线或美国线 fig = figure(facecolor='gray') fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) ax2 = fig.add_subplot(111) #fig, ax = plt.subplots() #fig.subplots_adjust(bottom=0.2)
import matplotlib.pyplot as plt from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange from numpy import arange date1 = datetime.datetime(2000, 3, 2) date2 = datetime.datetime(2000, 3, 6) delta = datetime.timedelta(hours=6) dates = drange(date1, date2, delta) y = arange(len(dates) * 1.0) fig, ax = plt.subplots() ax.plot_date(dates, y * y) # this is superfluous, since the autoscaler should get it right, but # use date2num and num2date to convert between dates and floats if # you want; both date2num and num2date convert an instance or sequence ax.set_xlim(dates[0], dates[-1]) # The hour locator takes the hour or sequence of hours you want to # tick, not the base multiple ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_minor_locator(HourLocator(arange(0, 25, 6))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() plt.show()
# get all those error values and make them into a new series ye = np.where(y > 400)[0] xe = x[ye] ye = np.random.uniform(-1, 0, ye.shape[0]) y[y > 400] = np.nan fig, ax = plt.subplots() plt.plot(x, y, 'r-', label='Readings') # plt.plot(xe, ye, 'bo', label='Errors') plt.legend(prop={'size': 23}) fig.subplots_adjust(bottom=0.125) majorFormatter = DateFormatter('%a') ax.xaxis.set_major_formatter(majorFormatter) majorLocator = DayLocator() ax.xaxis.set_major_locator(majorLocator) minorLocator = HourLocator(interval=3) minorFormatter = DateFormatter('%-I %p') ax.xaxis.set_minor_formatter(minorFormatter) ax.xaxis.set_minor_locator(minorLocator) # # # # for the minor ticks, use no labels; default NullFormatter # ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45) # print (ax.xaxis.get_majorticklabels()) # ax.set_xticks(ax.get_xticks()[::2]) # plt.setp(ax.xaxis.get_ticklabels(which='both'), rotation=90) # labels = ax.get_xticklabels() # plt.setp(ax.get_xticks('both'), rotation=30)
def hallarPatrones(fechaInicio, fechaFin, archivo, procedencia, contador): terminado = False suma = contador vela = False nombreVela = "no-vela" fechaInicio = str(fechaInicio) fechaFin = str(fechaFin) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 if procedencia == "csv": quotes = pd.read_csv(archivo, index_col="Date", parse_dates=True) if procedencia == "menu": quotes = archivo quotes = quotes[(quotes.index >= fechaInicio) & (quotes.index <= fechaFin)] quotes_numpy = { 'Open': np.array(quotes['Open'], dtype='float'), 'High': np.array(quotes['High'], dtype='float'), 'Low': np.array(quotes['Low'], dtype='float'), 'Close': np.array(quotes['Close'], dtype='float'), 'Volume': np.array(quotes['Volume'], dtype='int') } fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) #ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) ax.xaxis.set_minor_formatter(dayFormatter) candlestick_ohlc(ax, zip(mdates.date2num(quotes.index.to_pydatetime()), quotes['Open'], quotes['High'], quotes['Low'], quotes['Close']), width=0.9, colorup='g', colordown='r') ax.xaxis_date() ax.autoscale_view() plt.rcParams["figure.figsize"] = [16.0, 4.8] plt.setp(plt.gca().get_xticklabels(), rotation=90, horizontalalignment='right') #Leyenda l1 = Patch(facecolor='maroon', label='Formación con Gap Bajista', alpha=0.8) l2 = Patch(facecolor='brown', label='Formación con Gap Alcista', alpha=0.8) l3 = Patch(facecolor='sienna', label='MatHold', alpha=0.8) l4 = Patch(facecolor='chocolate', label='Triple Formación Alcista', alpha=0.8) l5 = Patch(facecolor='sandybrown', label='Triple Formación Bajista', alpha=0.8) l6 = Patch(facecolor='navy', label='Pequeña Golondrina Oculta', alpha=0.75) l7 = Patch(facecolor='mediumseagreen', label='Dos Cuervos en Gap Alcista', alpha=0.7) l8 = Patch(facecolor='olive', label='Tres Soldados Blancos', alpha=0.7) l9 = Patch(facecolor='springgreen', label='Tres Cuervos Negros', alpha=0.7) l10 = Patch(facecolor='green', label='Bebe Abandonado Alcista', alpha=0.7) l11 = Patch(facecolor='forestgreen', label='Bebe Abandonado Bajista', alpha=0.7) l12 = Patch(facecolor='lime', label='Estrella Vespertina Doji', alpha=0.7) l13 = Patch(facecolor='darkseagreen', label='Estrella de la Mañana Doji', alpha=0.7) l14 = Patch(facecolor='greenyellow', label='Estrella de la Mañana', alpha=0.7) l15 = Patch(facecolor='darkcyan', label='Estrella Vespertina', alpha=0.7) l16 = Patch(facecolor='pink', label='Coz Alcista', alpha=0.6) l17 = Patch(facecolor='hotpink', label='Coz Bajista', alpha=0.6) l18 = Patch(facecolor='magenta', label='Ventana Bajista', alpha=0.6) l19 = Patch(facecolor='purple', label='Ventana Alcista', alpha=0.6) l20 = Patch(facecolor='indigo', label='Envolvente Alcista', alpha=0.6) l21 = Patch(facecolor='plum', label='Envolvente Bajista', alpha=0.6) l22 = Patch(facecolor='g', label='Vela Alcista Grande', alpha=0.5) l23 = Patch(facecolor='r', label='Vela Bajista Grande', alpha=0.5) l24 = Patch(facecolor='yellow', label='Hombre Colgado', alpha=0.5) l25 = Patch(facecolor='orange', label='Doji Sombrilla', alpha=0.5) l26 = Patch(facecolor='gray', label='Doji Sombrilla Invertida', alpha=0.5) #Situar la leyenda plt.legend(loc='upper center', ncol=8, handles=[ l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24, l25, l26 ], borderaxespad=-6.0, shadow=True, fontsize='x-small') #Analisis de Patrones i = 0 delta = float(0.0) while i < len(quotes['Open']) and vela == False and terminado == False: encontrado = False if i > 3: if patrones.formacionConGapBajista( aper1=quotes['Open'][i - 4], cierre1=quotes['Close'][i - 4], aper2=quotes['Open'][i - 3], cierre2=quotes['Close'][i - 3], aper3=quotes['Open'][i - 2], cierre3=quotes['Close'][i - 2], aper4=quotes['Open'][i - 1], cierre4=quotes['Close'][i - 1], aper5=quotes['Open'][i], cierre5=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Formación con Gap Bajista") print("Tendencia Bajista (Continuación)") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "fgb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday( ) == 0 or quotes.index[i - 3].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=4.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='maroon', alpha=0.8) if patrones.formacionConGapAlcista( aper1=quotes['Open'][i - 4], cierre1=quotes['Close'][i - 4], aper2=quotes['Open'][i - 3], cierre2=quotes['Close'][i - 3], aper3=quotes['Open'][i - 2], cierre3=quotes['Close'][i - 2], aper4=quotes['Open'][i - 1], cierre4=quotes['Close'][i - 1], aper5=quotes['Open'][i], cierre5=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Formación con Gap Alcista") print("Tendencia Alcista (Continuación)") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "fga" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday( ) == 0 or quotes.index[i - 3].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=4.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='brown', alpha=0.8) if patrones.matHold(aper1=quotes['Open'][i - 4], cierre1=quotes['Close'][i - 4], aper2=quotes['Open'][i - 3], cierre2=quotes['Close'][i - 3], aper3=quotes['Open'][i - 2], cierre3=quotes['Close'][i - 2], aper4=quotes['Open'][i - 1], cierre4=quotes['Close'][i - 1], aper5=quotes['Open'][i], cierre5=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Mat Hold") print("Tendencia Alcista (Continuación)") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "mh" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday( ) == 0 or quotes.index[i - 3].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=4.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='sienna', alpha=0.8) if patrones.tripleFormacionAlcista( aper1=quotes['Open'][i - 4], cierre1=quotes['Close'][i - 4], aper2=quotes['Open'][i - 3], cierre2=quotes['Close'][i - 3], aper3=quotes['Open'][i - 2], cierre3=quotes['Close'][i - 2], aper4=quotes['Open'][i - 1], cierre4=quotes['Close'][i - 1], aper5=quotes['Open'][i], cierre5=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Triple Formacion Alcista") print("Tendencia Alcista (Continuación)") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "tfa" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday( ) == 0 or quotes.index[i - 3].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=4.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='chocolate', alpha=0.8) if patrones.tripleFormacionBajista( aper1=quotes['Open'][i - 4], cierre1=quotes['Close'][i - 4], aper2=quotes['Open'][i - 3], cierre2=quotes['Close'][i - 3], aper3=quotes['Open'][i - 2], cierre3=quotes['Close'][i - 2], aper4=quotes['Open'][i - 1], cierre4=quotes['Close'][i - 1], aper5=quotes['Open'][i], cierre5=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Triple Formacion Alcista") print("Tendencia Alcista (Continuación)") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "tfb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday( ) == 0 or quotes.index[i - 3].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=4.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='sandybrown', alpha=0.8) if i > 2 and encontrado == False: if patrones.pequeniaGolondrinaOcultada( aper1=quotes['Open'][i - 3], cierre1=quotes['Close'][i - 3], alto1=quotes['High'][i - 3], bajo1=quotes['Low'][i - 3], aper2=quotes['Open'][i - 2], cierre2=quotes['Close'][i - 2], alto2=quotes['High'][i - 2], bajo2=quotes['Low'][i - 2], aper3=quotes['Open'][i - 1], cierre3=quotes['Close'][i - 1], alto3=quotes['High'][i - 1], bajo3=quotes['Low'][i - 1], aper4=quotes['Open'][i], cierre4=quotes['Close'][i], alto4=quotes['High'][i], bajo4=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Pequeña Golondrina Oculta: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "pgo" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0 or quotes.index[i - 2].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=3.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='navy', alpha=0.75) if i > 1 and encontrado == False: if patrones.dosCuervosEnGapAlcista( aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Dos Cuervos en Gap Alcista: ") print("Tendencia Bajista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "dcga" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='mediumseagreen', alpha=0.7) if patrones.tresSoldadosBlancos(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Tres Soldados Blancos: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "tsb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='olive', alpha=0.7) if patrones.tresCuervosNegros(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Tres Cuervos Negros: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "tcn" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='springgreen', alpha=0.7) if patrones.bebeAbandonadoAlcista(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Bebe Abandonado Alcista: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "baa" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='green', alpha=0.7) if patrones.bebeAbandonadoBajista(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Bebe Abandonado Bajista: ") print("Tendencia Bajista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "bab" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='forestgreen', alpha=0.7) #Cambiar color de la sombra if patrones.estrellaVespertinaDoji( aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Estrella Vespertina Doji: ") print("Tendencia Bajista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "evd" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='lime', alpha=0.7) #Cambiar color de la sombra if patrones.estrellaDeLaManianaDoji( aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Estrella de la Mañana Doji: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "emd" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='darkseagreen', alpha=0.7) #Cambiar color de la sombra if patrones.estrellaDeLaManiana(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Estrella de la Mañana: ") print("Tendencia Alcista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "em" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='greenyellow', alpha=0.7) #Cambiar color de la sombra if patrones.estrellaVespertina(aper1=quotes['Open'][i - 2], cierre1=quotes['Close'][i - 2], alto1=quotes['High'][i - 2], bajo1=quotes['Low'][i - 2], aper2=quotes['Open'][i - 1], cierre2=quotes['Close'][i - 1], alto2=quotes['High'][i - 1], bajo2=quotes['Low'][i - 1], aper3=quotes['Open'][i], cierre3=quotes['Close'][i], alto3=quotes['High'][i], bajo3=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Estrella Vespertina: ") print("Tendencia Bajista ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "ev" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0 or quotes.index[ i - 1].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=2.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='darkcyan', alpha=0.7) if i > 0 and encontrado == False: if patrones.cozAlcista(aperturaAct=quotes['Open'][i], cierreAct=quotes['Close'][i], aperturaAnt=quotes['Open'][i - 1], cierreAnt=quotes['Close'][i - 1], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Coz Alcista el día:") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "ca" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='pink', alpha=0.6) if patrones.cozBajista(aperturaAct=quotes['Open'][i], cierreAct=quotes['Close'][i], aperturaAnt=quotes['Open'][i - 1], cierreAnt=quotes['Close'][i - 1], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Coz Bajista el día:") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "cb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='hotpink', alpha=0.6) if patrones.ventanaBajista(aper1=quotes['Open'][i - 1], cierre1=quotes['Close'][i - 1], alto1=quotes['High'][i - 1], bajo1=quotes['Low'][i - 1], aper2=quotes['Open'][i], cierre2=quotes['Close'][i], alto2=quotes['High'][i], bajo2=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Ventana Bajista: ") print("Tendencia Bajista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "vb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='magenta', alpha=0.6) if patrones.ventanaAlcita(aper1=quotes['Open'][i - 1], cierre1=quotes['Close'][i - 1], alto1=quotes['High'][i - 1], bajo1=quotes['Low'][i - 1], aper2=quotes['Open'][i], cierre2=quotes['Close'][i], alto2=quotes['High'][i], bajo2=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Ventana Alcista: ") print("Tendencia Alcista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "va" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='purple', alpha=0.6) if patrones.envolventeAlcista(aper1=quotes['Open'][i - 1], cierre1=quotes['Close'][i - 1], alto1=quotes['High'][i - 1], bajo1=quotes['Low'][i - 1], aper2=quotes['Open'][i], cierre2=quotes['Close'][i], alto2=quotes['High'][i], bajo2=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Envolvente Alcista: ") print("Tendencia Alcista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "ea" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='indigo', alpha=0.6) #Cambiar color de la sombra if patrones.envolventeBajista(aper1=quotes['Open'][i - 1], cierre1=quotes['Close'][i - 1], alto1=quotes['High'][i - 1], bajo1=quotes['Low'][i - 1], aper2=quotes['Open'][i], cierre2=quotes['Close'][i], alto2=quotes['High'][i], bajo2=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True: ''' print("Detectada Envolvente Bajista: ") print("Tendencia Bajista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "eb" if i <= contador: vela = False fechaInt = quotes.index[i] if quotes.index[i].weekday() == 0: delta = float(2.0) inter = datetime.timedelta(days=0.4) interNeg = datetime.timedelta(days=1.4 + delta) plt.axvspan(fechaInt - interNeg, fechaInt + inter, facecolor='plum', alpha=0.6) if patrones.velaAlcistaGrande( apertura=quotes['Open'][i], cierre=quotes['Close'][i], alto=quotes['High'][i], bajo=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True and encontrado == False: ''' print("Detectada Vela Alcista Grande el día: ") print(quotes.index[i]) ''' fechaInt = quotes.index[i] encontrado = True vela = True nombreVela = "vag" if i <= contador: vela = False inter = datetime.timedelta(days=0.4) plt.axvspan(fechaInt - inter, fechaInt + inter, facecolor='g', alpha=0.5) if patrones.velaBajistaGrande( apertura=quotes['Open'][i], cierre=quotes['Close'][i], alto=quotes['High'][i], bajo=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True and encontrado == False: ''' print("Detectada Vela Bajista Grande el día: ") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "vbg" if i <= contador: vela = False fechaInt = quotes.index[i] inter = datetime.timedelta(days=0.4) plt.axvspan(fechaInt - inter, fechaInt + inter, facecolor='r', alpha=0.5) if patrones.hombreColgado( aper1=quotes['Open'][i], cierre1=quotes['Close'][i], alto1=quotes['High'][i], bajo1=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True and encontrado == False: ''' print("Detectada Vela Hombre Colgado: ") print("Tendencia Bajista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "hc" if i <= contador: vela = False fechaInt = quotes.index[i] inter = datetime.timedelta(days=0.4) plt.axvspan(fechaInt - inter, fechaInt + inter, facecolor='yellow', alpha=0.5) #Cambiar color de la sombra if patrones.dojiSombrilla( aper1=quotes['Open'][i], cierre1=quotes['Close'][i], alto1=quotes['High'][i], bajo1=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True and encontrado == False: ''' print("Detectada Vela Doji Sombrilla: ") print("Tendencia Alcista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "ds" if i <= contador: vela = False fechaInt = quotes.index[i] inter = datetime.timedelta(days=0.4) plt.axvspan(fechaInt - inter, fechaInt + inter, facecolor='orange', alpha=0.5) #Cambiar color de la sombra if patrones.dojiSombrillaInvertida( aper1=quotes['Open'][i], cierre1=quotes['Close'][i], alto1=quotes['High'][i], bajo1=quotes['Low'][i], fechaInicio=fechaInicio, fechaFin=fechaFin, archivo=archivo, procedencia=procedencia) == True and encontrado == False: ''' print("Detectada Vela Doji Sombrilla Invertida: ") print("Tendencia Bajista") print(quotes.index[i]) ''' encontrado = True vela = True nombreVela = "dsi" if i <= contador: vela = False fechaInt = quotes.index[i] inter = datetime.timedelta(days=0.4) plt.axvspan(fechaInt - inter, fechaInt + inter, facecolor='gray', alpha=0.5) suma = i i = i + 1 if i == len(quotes['Open']): terminado = True contador = suma if len(quotes['Open']) == suma: terminado = True if procedencia == "csv": archivo = archivo.replace(".csv", "") archivo = archivo.replace(dir, "") archivo = archivo.replace("/", "") imagen = "grafica" imagen += archivo imagen += "analisis" imagen += ".png" else: imagen = "grafica" imagen += "analisis" imagen += ".png" plt.savefig(imagen) return imagen, terminado, contador, nombreVela
ford_stock['Volume'].plot(label='Ford', ax=axes[0, 1]) gm_stock['Volume'].plot(label='GM', ax=axes[0, 1]) plt2.set_ylabel('Number of stocks') plt2.legend() plt3 = tesla_stock['Total Traded'].plot(label='Tesla', figsize=(12, 8), title='Total Traded', ax=axes[1, 0]) ford_stock['Total Traded'].plot(label='Ford', ax=axes[1, 0]) gm_stock['Total Traded'].plot(label='GM', ax=axes[1, 0]) plt3.set_ylabel('US Dollars, in billions') plt3.legend() mondays = WeekdayLocator(MONDAY) # major ticks on Monday alldays = DayLocator() # minor ticks on every other day beside Mondays week_formatter = DateFormatter('%b %d') # format e.g., Jan 12 day_formatter = DateFormatter('%b %d') # e.g., 12 '''Set candle chart as plot #4''' plt4_axes = axes[1, 1] plt4_axes.xaxis.set_major_locator(mondays) plt4_axes.xaxis.set_minor_locator(alldays) plt4_axes.xaxis.set_major_formatter(week_formatter) plt4_axes.set_xlabel('Date') plt4_axes.set_ylabel('US Dollars/share') candlestick_ohlc(plt4_axes, tesla_values, width=0.6, colorup='g', colordown='r')
# print(bars) # xtick_pos = np.arange(0, bars+1) # # print(bars) # fig, ax = plt.subplots() # print(var1.size) delta = dt.timedelta(days=1) dates = pd.date_range(begin_date1, end_date1, freq='1D') print(dates) fig, ax = plt.subplots() ax.bar(dates, var1) ax.set_xlim(dates[0], dates[-1] + delta) ax.xaxis.set_major_locator(DayLocator(interval=7)) Axis.set_minor_locator(ax.xaxis, DayLocator()) ax.xaxis.set_major_formatter(DateFormatter('%d.%m')) ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S') fig.autofmt_xdate() fig.suptitle( "Диаграмма изменчивости суточного гидротермического коэффициента Селянинова\n" + r"%s год" % (begin_date1.strftime("%Y")) + "\n" + r"вегетационный период с %s по %s" % (begin_date1.strftime("%d.%m"), end_date1.strftime("%d.%m")), fontsize=12, fontweight='bold') plt.show()
fecha1 = (2014, 10, 13) fecha2 = (2014, 11, 13) # Vamos a la web y nos traemos la información de la cotización valores = quotes_historical_yahoo_ohlc('AAPL', fecha1, fecha2) if len(valores) == 0: raise SystemExit # Definimos el aspecto de la gráfica fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) # Ponemos marcas mayores para los lunes lunes = WeekdayLocator(MONDAY) ax.xaxis.set_major_locator(lunes) # Ponemos marcas menores para el resto de días resto_dias = DayLocator() ax.xaxis.set_minor_locator(resto_dias) # Damos formato a los días formato_semana = DateFormatter('%b %d') # e.g., Ene 12 ax.xaxis.set_major_formatter(formato_semana) ax.xaxis_date() candlestick_ohlc(ax, valores, width=0.6) ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def candleLinePlots(candleData, candleTitle='a', **kwargs): Date = [date2num(date) for date in candleData.index] candleData.loc[:, 'Date'] = Date listData = [] for i in range(len(candleData)): a = [candleData.Date[i],\ candleData.Open[i],candleData.High[i],\ candleData.Low[i],candleData.Close[i]] listData.append(a) # 如 果 不 定 長 參 數 無 取 值 , 只 畫 蠟 燭 圖 ax = plt.subplot() # 如 果 不 定 長 參 數 有 值 , 則 分 成 兩 個 子 圖 flag = 0 if kwargs: if kwargs['splitFigures']: ax = plt.subplot(211) ax2 = plt.subplot(212) flag = 1 for key in kwargs: if key == 'title': ax2.set_title(kwargs[key]) if key == 'ylabel': ax2.set_ylabel(kwargs[key]) if key == 'grid': ax2.grid(kwargs[key]) if key == 'Data': plt.sca(ax) if flag: plt.sca(ax2) #一維數據 if kwargs[key].ndim == 1: plt.plot(kwargs[key],\ color='k',\ label=kwargs[key].name) plt.legend(loc='best') #二維數據有兩個columns elif all([kwargs[key].ndim==2,\ len(kwargs[key].columns)==2]): plt.plot(kwargs[key].iloc[:, 0], color='k', label=kwargs[key].iloc[:, 0].name) plt.plot(kwargs[key].iloc[:,1],\ linestyle='dashed',\ label=kwargs[key].iloc[:,1].name) plt.legend(loc='best') #二維數據有3個columns elif all([kwargs[key].ndim==2,\ len(kwargs[key].columns)==3]): plt.plot(kwargs[key].iloc[:, 0], color='k', label=kwargs[key].iloc[:, 0].name) plt.plot(kwargs[key].iloc[:, 1], linestyle='dashed', label=kwargs[key].iloc[:, 1].name) plt.bar(left=kwargs[key].iloc[:, 2].index, height=kwargs[key].iloc[:, 2], color='r', label=kwargs[key].iloc[:, 2].name) plt.legend(loc='best') mondays = WeekdayLocator(MONDAY) weekFormatter = DateFormatter('%y %b %d') ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(DayLocator()) ax.xaxis.set_major_formatter(weekFormatter) plt.sca(ax) candlestick_ohlc(ax,listData, width=0.7,\ colorup='r',colordown='g') ax.set_title(candleTitle) plt.setp(ax.get_xticklabels(),\ rotation=20,\ horizontalalignment='center') ax.autoscale_view() return (plt.show())
def plot( x, y, x2=None, y2=None, subplots=1, title='Plot', title2=None, xlabel=None, ylabel=None, xlabel2=None, ylabel2=None, xlim_low=None, ylim_low=None, xlim2_low=None, ylim2_low=None, xlim_high=None, ylim_high=None, xlim2_high=None, ylim2_high=None, color='#ce5f5f', color2='#66A7C5', sharex=False, sharey=False, extra=False, extray=False, show=False, save=None, dates=False, major='days', minor=None, interval=1, ): """ Wrapper of matplotlib.pyplot. Makes a plot. Only two inputs are required: x and y. However, some inputs require other inputs. :param: x (list/np.array) - main x array :param: y (list/np.array) - main y array :param: x2 (list/np.array) - secondary x array :param: y2 (list/np.array) - secondary y array :param: subplots (int) - number of subplots (max 2) :param: title (str) - main title :param: title2 (str) - secondary title :param: xlabel (str) - main x axis label :param: ylabel (str) - main y axis label :param: xlabel2 (str) - secondary x axis label :param: ylabel2 (str) - secondary y axis label :param: xlim_low (int/float) - main x axis lower limit :param: ylim_low (int/float) - main y axis lower limit :param: xlim2_low (int/float) - secondary x axis lower limit :param: ylim2_low (int/float) - secondary y axis lower limit :param: xlim_high (int/float) - main x axis upper limit :param: ylim_high (int/float) - main y axis upper limit :param: xlim2_high (int/float) - secondary x axis upper limit :param: ylim2_high (int/float) - secondary y axis upper limit :param: color (str) - main line color, hexcode or matplotlib color :param: color2 (str) - secondary line color, hexcode or matplotlib color :param: sharex (boolean) - share x axis trigger :param: sharey (boolean) - share y axis trigger :param: extra (boolean) - plot y2 on same plot :param: extray (boolean) - plot y2 on secondary axis :param: show (boolean) - shows plot :param: save (str) - name of output plot :param: dates (boolean) - indicates whether x axis are datetime objects :param: major (str) - time scale to put tick marks and label :param: minor (str) - time scale to put tick marks and label (buggy) :param: interval (int) - intervals between tick marks :return: fig (matplotlib.figure) - plot figure Optional inputs requirements - subplots: x2 (if not sharex), y2 (if not sharey) ylim_high: ylim_low (vice-versa) xlim_high: xlim_low (vice-versa) extra: y2 extray: extra=True dates: x=arr. of [datetime.datetime] or x2=arr of [datetime.datetime] """ if subplots == 2 and x2 is None and sharex is False: print('\nMissing input "x2" to create second plot!\n') raise (MissingInput) if subplots == 2 and y2 is None and sharey is False: print('\nMissing input "y2" to create second plot!\n') raise (MissingInput) if ylim_high is not None and ylim_low is None: print('\nMissing input "ylim_low" to set upper y limit!\n') raise (MissingInput) if ylim_low is not None and ylim_high is None: print('\nMissing input "ylim_high" to set lower y limit!\n') raise (MissingInput) if ylim2_high is not None and ylim2_low is None: print('\nMissing input "ylim2_low" to set secondary upper y limit!\n') raise (MissingInput) if ylim2_low is not None and ylim2_high is None: print('\nMissing input "ylim2_high" to set secondary lower y limit!\n') raise (MissingInput) if extra and y2 is None: print('\nMissing a "y2" to use "extra" input!\n') raise (MissingInput) if extray and extra is False: print('Input "extra" automatically set to True because "of extray"') extra = True if subplots > 1: if sharey: fig, ax = plt.subplots(1, subplots, sharex=sharex, sharey=sharey, figsize=(20, 15)) else: fig, ax = plt.subplots(subplots, sharex=sharex, sharey=sharey, figsize=(20, 15)) if dates: ax[0].plot_date(x, y, color) else: ax[0].plot(x, y, color) # Here's some logic to reduce redundancy if sharex: if xlabel is None: if xlabel2 is not None: xlabel = xlabel2 else: print('No xlabel found, defaulting to "x"') xlabel = 'x' elif xlabel2 is None: if xlabel is not None: xlabel2 = xlabel else: print('No xlabel2 found, defaulting to "x2"') xlabel2 = 'x2' ax[0].set_ylabel(ylabel, fontsize=16.5) if dates: ax[1].plot_date(x, y2, color2) else: ax[1].plot(x, y2, color2) ax[1].set_ylabel(ylabel2, fontsize=16.5) elif sharey: if ylabel is None: if ylabel2 is not None: ylabel = ylabel2 else: print('No ylabel found, defaulting to "y"') ylabel = 'y' elif ylabel2 is None: if ylabel is not None: ylabel2 = ylabel else: print('No ylabel2 found, defaulting to "y2"') ylabel2 = 'y2' ax[0].set_xlabel(xlabel, fontsize=16.5) ax[0].set_ylabel(ylabel, fontsize=16.5) if dates: ax[1].plot_date(x2, y, color2) else: ax[1].plot(x2, y, color2) else: if xlabel is None: print('No xlabel found, defaulting to "x"') xlabel = 'x' if xlabel2 is None: print('No xlabel2 found, defaulting to "x2"') xlabel2 = 'x2' if ylabel is None: print('No ylabel found, defaulting to "y"') ylabel = 'y' if ylabel2 is None: print('No ylabel2 found, defaulting to "y2"') ylabel2 = 'y2' ax[0].set_xlabel(xlabel, fontsize=16.5) ax[0].set_ylabel(ylabel, fontsize=16.5) if dates: ax[1].plot_date(x2, y2, color2) else: ax[1].plot(x2, y2, color2) ax[1].set_ylabel(ylabel2, fontsize=16.5) ax[1].set_xlabel(xlabel2, fontsize=16.5) ax[0].set_title(title, fontsize=23, y=1.03, color='.50') if title2 is not None: ax[1].set_title(title2, fontsize=23, y=1.03, color='.50') if dates: if major == 'years': major = YearLocator(interval=interval) majorFmt = DateFormatter('%Y') elif major == 'months': major = MonthLocator(interval=interval) majorFmt = DateFormatter('%m%Y') elif major == 'days': major = DayLocator(interval=interval) majorFmt = DateFormatter('%m/%d') elif major == 'hours': major = HourLocator(interval=interval) majorFmt = DateFormatter('\n%H') if minor is not None: if minor == 'years': minor = YearLocator(interval=interval) minorFmt = DateFormatter('\n%Y') elif minor == 'months': minor = MonthLocator(interval=interval) minorFmt = DateFormatter('\n%m') elif minor == 'days': minor = DayLocator(interval=interval) minorFmt = DateFormatter('\n%d') elif minor == 'hours': minor = HourLocator(interval=interval) minorFmt = DateFormatter('\n%H') for i in range(subplots): if major is not None: ax[i].xaxis.set_major_locator(major) ax[i].xaxis.set_major_formatter(majorFmt) if minor is not None: ax[i].xaxis.set_minor_locator(minor) ax[i].xaxis.set_minor_formatter(minorFmt) plt.gcf() fig.autofmt_xdate() if ylim_high is not None and ylim_low is not None: ax[0].set_ylim(ylim_low, ylim_high) if xlim_high is not None and xlim_low is not None: ax[0].set_xlim(xlim_low, xlim_high) if ylim2_high is not None and ylim2_low is not None: ax[1].set_ylim(ylim2_low, ylim2_high) if xlim2_high is not None and xlim2_low is not None: ax[1].set_xlim(xlim2_low, xlim2_high) # Apply some prettifying for i in range(subplots): prettify_plot(ax[i]) elif subplots == 1: fig, ax = plt.subplots(figsize=(21, 13)) if dates: ax.plot_date(x, y, color) if major == 'years': major = YearLocator() majorFmt = DateFormatter('%Y') elif major == 'months': major = MonthLocator() majorFmt = DateFormatter('%m') elif major == 'days': major = DayLocator() majorFmt = DateFormatter('%d') elif major == 'hours': major = HourLocator() majorFmt = DateFormatter('%H') if minor is not None: if minor == 'years': minor = YearLocator() minorFmt = DateFormatter('\n%Y') elif minor == 'months': minor = MonthLocator() minorFmt = DateFormatter('\n%m') elif minor == 'days': minor = DayLocator() minorFmt = DateFormatter('\n%d') elif minor == 'hours': minor = HourLocator() minorFmt = DateFormatter('\n%H') ax.xaxis.set_major_locator(major) ax.xaxis.set_major_formatter(majorFmt) if minor is not None: ax.xaxis.set_minor_locator(minor) ax.xaxis.set_minor_formatter(minorFmt) fig.autofmt_xdate() else: ax.plot(x, y, color) if ylim_high is not None and ylim_low is not None: ax.set_ylim(ylim_low, ylim_high) if xlim_high is not None and xlim_low is not None: ax.set_xlim(xlim_low, xlim_high) if xlabel is None: print('No xlabel found, defaulting to "x"') xlabel = 'x' if ylabel is None: print('No ylabel found, defaulting to "y"') ylabel = 'y' ax.set_title(title, fontsize=21, y=1.03, color='.50') ax.set_xlabel(xlabel, fontsize=16.5) ax.set_ylabel(ylabel, fontsize=16.5) if extra: if extray: ax2 = ax.twinx() ax2.plot(x, y2, color2) if ylabel2 is None: print('No ylabel2 found, defaulting to "y2"') ylabel2 = 'y2' ax2.set_ylabel(ylabel2, fontsize=16.5) if ylim2_high is not None and ylim2_low is not None: ax2.set_ylim(ylim2_low, ylim2_high) if xlim_high is not None and xlim_low is not None: ax2.set_xlim(xlim_low, xlim_high) ax2.spines["top"].set_visible(False) ax2.spines["bottom"].set_visible(False) ax2.spines["right"].set_visible(False) ax2.spines["left"].set_visible(False) ax2.get_yaxis().tick_right() ax2.yaxis.label.set_color(color2) ax2.tick_params(axis='y', colors=color2) ax2.grid(b=True, which='major', color=color2, linestyle='--') else: ax.plot(x, y2, color2) # Prettify it! prettify_plot(ax) if extray: ax.yaxis.label.set_color(color) ax.tick_params(axis='y', colors=color) ax.yaxis.grid(b=True, which='major', color=color, linestyle='--') else: ax.yaxis.label.set_color('.4') ax.tick_params(axis='y', colors='.5') ax.yaxis.grid(b=True, which='major', color='.55', linestyle='--') else: print('Sorry, this function only supports two subplots\n!') raise (Unsupported) if save is not None: fig.savefig(save) if show: fig.show() return fig
def plot_station_data(date,site,sitetitle,df): '''Given site station ID, the title of that site, and a dataframe of ASOS observation data from the last 3 days, returns a plot of the last 3-days of weather at that site. Parameters: site (str): string of ASOS station ID sitetitle (str): string of ASOS station full name df (dataframe): dataframe containing last 72 hours (3 days) of ASOS station data Returns: None *saves plots to plot_dir listed near top of script* ''' if isinstance(df, int): #Returns if the station is not reporting return lower_site = site.lower() timestamp_end=str(df.index[-1].strftime('%Y%m%d%H%M')) dt = df.index[:] dt_array = np.array(dt.values) graphtimestamp_start=dt[0].strftime("%m/%d/%y") graphtimestamp=dt[-1].strftime("%m/%d/%y") #now = datetime.datetime.utcnow() now = datetime.strptime(date,'%Y%m%d') today_date = dt[-1].strftime('%Y%m%d') markersize = 1.5 linewidth = 1.0 #make figure and axes fig = plt.figure() fig.set_size_inches(18,10) if 'snow_depth_set_1' in df.keys(): #six axes if snow depth ax1 = fig.add_subplot(6,1,1) ax2 = fig.add_subplot(6,1,2,sharex=ax1) ax3 = fig.add_subplot(6,1,3,sharex=ax1) ax4 = fig.add_subplot(6,1,4,sharex=ax1) ax5 = fig.add_subplot(6,1,5,sharex=ax1) ax6 = fig.add_subplot(6,1,6,sharex=ax1) ax6.set_xlabel('Time (UTC)') else: ax1 = fig.add_subplot(5,1,1) #five axes if no snow depth ax2 = fig.add_subplot(5,1,2,sharex=ax1) ax3 = fig.add_subplot(5,1,3,sharex=ax1) ax4 = fig.add_subplot(5,1,4,sharex=ax1) ax5 = fig.add_subplot(5,1,5,sharex=ax1) ax5.set_xlabel('Time (UTC)') #ax1.set_title(site+' '+sitetitle+' '+graphtimestamp_start+' - '+graphtimestamp+' '+now.strftime("%H:%MZ")) ax1.set_title(site+' '+sitetitle+' '+graphtimestamp_start+' - '+graphtimestamp) #------------------ #plot airT and dewT #------------------ if 'tmpc' in df.keys(): airT = df['tmpc'] airT_new = airT.dropna() airT_list = list(airT_new.values) airT_dt_list = [] for i in range(0,len(airT)): if pd.isnull(airT[i]) == False: airT_dt_list.append(dt[i]) ax1.plot_date(airT_dt_list,airT_list,'o-',label="Temp",color="blue",linewidth=linewidth,markersize=markersize) #ax1.plot_date(dt,airT,'-',label="Temp",color="blue",linewidth=linewidth) if 'dwpc' in df.keys(): dewT = df['dwpc'] dewT_new = dewT.dropna() dewT_list = list(dewT_new.values) dewT_dt_list = [] for i in range(0,len(dewT)): if pd.isnull(dewT[i]) == False: dewT_dt_list.append(dt[i]) ax1.plot_date(dewT_dt_list,dewT_list,'o-',label="Dew Point",color="black",linewidth=linewidth,markersize=markersize) if ax1.get_ylim()[0] < 0 < ax1.get_ylim()[1]: ax1.axhline(0, linestyle='-', linewidth = 1.0, color='deepskyblue') trans = transforms.blended_transform_factory(ax1.get_yticklabels()[0].get_transform(), ax1.transData) ax1.text(0,0,'0C', color="deepskyblue", transform=trans, ha="right", va="center") #light blue line at 0 degrees C ax1.set_ylabel('Temp ($^\circ$C)') ax1.legend(loc='best',ncol=2) axes = [ax1] #begin axes #---------------------------- #plotting wind speed and gust #---------------------------- if 'sknt' in df.keys(): wnd_spd = df['sknt'] ax2.plot_date(dt,wnd_spd,'o-',label='Speed',color="forestgreen",linewidth=linewidth,markersize=markersize) if 'gust' in df.keys(): wnd_gst = df['gust'] max_wnd_gst = wnd_gst.max(skipna=True) ax2.plot_date(dt,wnd_gst,'o-',label='Gust (Max ' + str(round(max_wnd_gst,1)) + 'kt)',color="red",linewidth=0.0,markersize=markersize) ax2.set_ylabel('Wind (kt)') ax2.legend(loc='best',ncol=2) axes.append(ax2) #----------------------- #plotting wind direction #----------------------- if 'drct' in df.keys(): wnd_dir = df['drct'] ax3.plot_date(dt,wnd_dir,'o-',label='Direction',color="purple",linewidth=0.2, markersize=markersize) ax3.set_ylim(-10,370) ax3.set_ylabel('Wind Direction') ax3.set_yticks([0,90,180,270,360]) axes.append(ax3) #------------- #plotting MSLP #------------- if 'mslp' in df.keys(): mslp = df['mslp'] mslp_new = mslp.dropna() mslp_list = list(mslp_new.values) mslp_dt_list = [] for i in range(0,len(mslp)): if pd.isnull(mslp[i]) == False: mslp_dt_list.append(dt[i]) max_mslp = mslp.max(skipna=True) min_mslp = mslp.min(skipna=True) labelname = 'Min ' + str(round(min_mslp,1)) + 'hPa, Max ' + str(round(max_mslp,2)) + 'hPa' ax4.plot_date(mslp_dt_list,mslp_list,'o-',label=labelname,color='darkorange',linewidth=linewidth,markersize=markersize) ax4.legend(loc='best') ax4.set_ylabel('MSLP (hPa)') ax4.set_xlabel('Time (UTC)') axes.append(ax4) #------------------------------------------- #plotting precip accumulation & precip types #------------------------------------------- # Move date_time from index to column df = df.reset_index() # MODIFY THIS SO THAT WHEN READINGS COME IN WE KEEP THEM INSTEAD OF JUST ACCEPTING HOURLY ACCUMS # WILL MAKE PLOT LESS CHOPPY # Plot precip time series (use only values at minute 53) if 'p01m' in df.keys(): df['p01m'] = df['p01m'].fillna(0) precip_inc = list(df['p01m'].values) precip_inc_dt = list(df['date_time'].values) precip_accum = 0.0 precip_accum_list = [] precip_dt_list = [] precip_accum_indices = [] for i in range(0,len(precip_inc)): time_obj = pd.to_datetime(precip_inc_dt[i]) minutes = time_obj.strftime('%M') if minutes == '53': precip_accum = precip_accum + precip_inc[i] precip_accum_list.append(precip_accum) precip_dt_list.append(precip_inc_dt[i]) precip_accum_indices.append(i) times = precip_dt_list precip_accums = precip_accum_list """ precip_accum = 0.0 precip_accum_list = [] last_increment = df.loc[0].p01m precip_accum_indices = [] for index in range(1,len(df)): if df.loc[index].p01m < last_increment: precip_accum = precip_accum + last_increment precip_accum_list.append(precip_accum) precip_accum_indices.append(index) else: precip_accum_list.append(precip_accum) last_increment = df.loc[index].p01m # append last element in dataframe in case there's some precip there precip_accum = precip_accum + last_increment precip_accum_list.append(precip_accum) # values to use for the plot times = [precip_dt_list[i] for i in precip_accum_indices] precip_accums = [precip_accum_list[i] for i in precip_accum_indices] """ max_precip = max(precip_accum_list) labelname = 'Precip (' + str(round(max_precip,2)) + 'mm)' ax5.plot_date(precip_dt_list,precip_accum_list,'o-',label=labelname,color='navy',linewidth=linewidth,markersize=markersize) if max_precip > 0: ax5.set_ylim(-0.1*max_precip,max_precip+max_precip*0.2) else: ax5.set_ylim(-0.5,5) # Add weather_code info to plot if 'wxcodes' in df.keys(): df['wxcodes'] = df['wxcodes'].fillna('') wxcodes_list = list(df['wxcodes'].values) #wxcodes_dt_list = list(df['date_time'].values) wxcodes_num_list = [] for i in range(0,len(wxcodes_list)): wxcodes = wxcodes_list[i] if len(wxcodes) > 0: wxcode_wto = wx_code_map[wxcodes.split()[0]] else: wxcode_wto = 0 wxcodes_num_list.append(wxcode_wto) wxcodes = [wxcodes_num_list[i] for i in precip_accum_indices] # Set y values for weather symbols on plot dummy_y_vals = np.ones(len(wxcodes)) * (0.10*max_precip) sp = StationPlot(ax5, times, dummy_y_vals) #ax.plot(dates, temps) #sp.plot_symbol('C', wxcodes, current_weather, fontsize=16, color='red') sp.plot_symbol('C', wxcodes, current_weather, fontsize=14, color='red') """ wxcodes_num_list_hrly = [] wxcodes_dt_list_hrly = [] for i in range(0,len(wxcodes_num_list)): time_obj = pd.to_datetime(wxcodes_dt_list[i]) minutes = time_obj.strftime('%M') if minutes == '00': wxcodes_num_list_hrly.append(wxcodes_num_list[i]) wxcodes_dt_list_hrly.append(wxcodes_dt_list[i]) dummy_y_vals = np.zeros(len(wxcodes_num_list_hrly)) # only to place on plot sp = StationPlot(ax5, wxcodes_dt_list_hrly, dummy_y_vals) #ax5.plot(precip_dt_list,precip_accum_list) sp.plot_symbol('C', wxcodes_num_list_hrly, current_weather, fontsize=16, color='red') """ ax5.legend(loc='best') ax5.set_ylabel('Precip (mm)') axes.append(ax5) """ #------------------- #plotting snow depth #------------------- if 'snow_depth_set_1' in df.keys(): snow_depth = df['snow_depth_set_1'] snow_depth_new = snow_depth.dropna() snow_depth_dt_list = [] for i in range(0,len(snow_depth)): if pd.isnull(snow_depth[i]) == False: snow_depth_dt_list.append(dt[i]) max_snow_depth = snow_depth.max(skipna=True) min_snow_depth = snow_depth.min(skipna=True) labelname = 'Min Depth ' + str(round(min_snow_depth,2)) + 'mm, Max Depth ' + str(round(max_snow_depth,2)) + 'mm' ax6.plot_date(snow_depth_dt_list,snow_depth_new,'o-',label=labelname,color='deepskyblue',linewidth=linewidth,markersize=markersize) if max_snow_depth > 0: ax6.set_ylim(-0.1*max_snow_depth,max_snow_depth+max_snow_depth*0.2) else: ax6.set_ylim(-0.5,5) ax6.legend(loc='best') ax6.set_ylabel('Snow Depth (mm)') axes.append(ax6) """ # Axes formatting for ax in axes: ax.spines["top"].set_visible(False) #darker borders on the grids of each subplot ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis='x',which='both',bottom='on',top='off') #add ticks at labeled times ax.tick_params(axis='y',which='both',left='on',right='off') ax.xaxis.set_major_locator( DayLocator() ) ax.xaxis.set_major_formatter( DateFormatter('%b-%d') ) ax.xaxis.set_minor_locator( HourLocator(np.linspace(6,18,3)) ) ax.xaxis.set_minor_formatter( DateFormatter('%H') ) ax.fmt_xdata = DateFormatter('Y%m%d%H%M%S') ax.yaxis.grid(linestyle = '--') ax.get_yaxis().set_label_coords(-0.06,0.5) # Write plot to file plot_path = plot_dir+'/'+today_date if not os.path.exists(plot_path): os.makedirs(plot_path) try: plt.savefig(plot_path+'/ops.asos.'+timestamp_end+'.'+lower_site+'.png',bbox_inches='tight') except: print("Problem saving figure for %s. Usually a maxticks problem" %site) plt.close()
def pandas_candlestick_ohlc(self, share, fechasNum, window, stick="day", otherseries=["20d", "50d"], adj=False): """ :param share: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo" :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period :param adj: A boolean indicating whether to use adjusted prices :param otherseries: An iterable that will be coerced into a list, containing the columns of share that hold other series to be plotted as lines This will show a Japanese candlestick plot for stock data stored in share, also plotting other series if passed. """ share["20d"] = np.round( share["Adj. Close"].rolling(window=20, center=False).mean(), 2) share["50d"] = np.round( share["Adj. Close"].rolling(window=50, center=False).mean(), 2) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days dayFormatter = DateFormatter('%d') # e.g., 12 # Create a new DataFrame which includes OHLC data for each period specified by stick input fields = ["Open", "High", "Low", "Close"] if adj: fields = ["Adj. " + s for s in fields] transdat = share.loc[:, fields] transdat.columns = pd.Index(["Open", "High", "Low", "Close"]) if (type(stick) == str): if stick == "day": plotdat = transdat stick = 1 # Used for plotting elif stick in ["week", "month", "year"]: if stick == "week": transdat["week"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[1]) # Identify weeks elif stick == "month": transdat["month"] = pd.to_datetime(transdat.index).map( lambda x: x.month) # Identify months transdat["year"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[0]) # Identify years grouped = transdat.groupby(list(set( ["year", stick]))) # Group by year and other appropriate variable plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) # Create empty data frame containing what will be plotted for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { "Open": group.iloc[0, 0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1, 3] }, index=[group.index[0]])) if stick == "week": stick = 5 elif stick == "month": stick = 30 elif stick == "year": stick = 365 elif (type(stick) == int and stick >= 1): transdat["stick"] = [ np.floor(i / stick) for i in range(len(transdat.index)) ] grouped = transdat.groupby("stick") plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) # Create empty data frame containing what will be plotted for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { "Open": group.iloc[0, 0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1, 3] }, index=[group.index[0]])) else: raise ValueError( 'Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer' ) # Set plot parameters, including the axis object ax used for plotting fig = Figure(figsize=(7.5, 4.5), dpi=100) self.ax = fig.add_subplot(111) self.ax.clear() self.ax.grid(True) # Create the candelstick chart candlestick_ohlc(self.ax, list( zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(), plotdat["Low"].tolist(), plotdat["Close"].tolist())), colorup="black", colordown="red", width=stick * .4) # Plot other series (such as moving averages) as lines if otherseries != None: if type(otherseries) != list: otherseries = [otherseries] share.loc[:, otherseries].plot(ax=self.ax, lw=1.3, grid=True) self.ax.xaxis_date() self.ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') # estadis = Estadisticas() # desviEstandar = estadis.desviacionEstadar(share["Adj. Close"].data.obj) # media = estadis.regresionLineal(share,fechasNum) # mediaMasDE = estadis.cambiarValorPrecios(media.copy(),desviEstandar*2) # mediaMenosDE = estadis.cambiarValorPrecios(media.copy(),-desviEstandar*2) # ax.plot(plotdat.index.tolist(),media,"r",label = "regression") # ax.plot(plotdat.index.tolist(),mediaMasDE,"b",label = "+DE") # ax.plot(plotdat.index.tolist(),mediaMenosDE,"b",label = "-DE") #navigation tool if self.grafico: self.canvas.get_tk_widget().destroy() if ~self.grafico: self.canvas = FigureCanvasTkAgg(fig, master=window) self.canvas.get_tk_widget().pack() self.toolbar = NavigationToolbar2Tk(self.canvas, window) self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=True) self.canvas.draw() self.grafico = True
def pandas_candlestick_ohlc(dat, days='day', adj=False, otherseries=None): mondays = WeekdayLocator(MONDAY) all_days = DayLocator() fields = ['Open', 'High', 'Low', 'Close'] transdat = dat.loc[:, fields] # Selects single column or subset of columns by label transdat.columns = pd.Index(['Open', 'High', 'Low', 'Close']) if (type(days) == str): if days == "day": plotdat = transdat days = 1 elif days in ['week', 'month', 'year']: if days == 'week': transdat['week'] = pd.to_datetime(transdat.index).map( lambda x: x.isocalender()[1] ) #Return a 3-tuple, (ISO year, ISO week number, ISO weekday). elif days == 'month': transdat['month'] = pd.to_datetime( transdat.index).map(lambda x: x.month) transdat['year'] = pd.to_datetime( transdat.index).map(lambda x: x.isocalendar()[0]) grouped = transdat.groupby(list({'year', days})) plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { 'Open': group.iloc[0, 0], 'High': max(group.High), 'Low': min(group.Low), 'Close': group.iloc[-1, 3] }, index=[group.index[0]])) if days == 'week': days = 5 elif days == 'month': days = 30 elif days == 'year': days = 365 elif (type(days) == int and days >= 1): transdat['stick'] = [ pd.np.floor(i / days) for i in range(len(transdat.index)) ] grouped = transdat.groupby('stick') plotdat = pd.DataFrame({ "Open": [], "High": [], "Low": [], "Close": [] }) for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { 'Open': group.iloc[0, 0], 'High': max(group.High), 'Low': min(group.Low), 'Close': group.iloc[-1, 3] }, index=[group.index[0]])) else: raise ValueError( 'Valid inputs - "days" include the strings or a positive integer') # Set plot parameters, including the axis object ax used for plotting fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'): weekFormatter = DateFormatter('%b %d') # for example Jan 12 ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(all_days) else: weekFormatter = DateFormatter('%b %d, %Y') ax.xaxis.set_major_formatter(weekFormatter) ax.grid(True) # Create the candelstick chart candlestick_ohlc(ax, list( zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(), plotdat["Low"].tolist(), plotdat["Close"].tolist())), colorup="black", colordown="red", width=days * .4) # Plot other series (such as moving averages) as lines if otherseries != None: if type(otherseries) != list: otherseries = [otherseries] dat.loc[:, otherseries].plot(ax=ax, lw=1.3, grid=True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def plot_station_data(site_data): '''Given a pandas dataframe containing all weather data for a specific station, this function saves a plot with the last 3 days worth of weather data for that station (or as much data as available if not yet 3-days). Parameters: site_data (dataframe): pandas dataframe containing all data, both directly observed and calculated, for a specific station Returns: None *saves plots to plot_dir listed near top of script* ''' latest = site_data.index[-1] site = site_data['station'][0] lower_site = site.lower() site_slice = site_data.loc[site_data.index >= ( latest - timedelta(hours=72))] #slice data to last 72hrs timestamp_end = site_slice.index[-1].strftime( '%Y%m%d%H%M') #timestamp end for saving .csv files dt = site_slice.index[:] #define dt for making subplots sitetitle = site_slice['name'][0] #define sitetitle for fig title graphtimestamp_start = dt[0].strftime( "%m/%d/%y") #start date, for fig title graphtimestamp = dt[-1].strftime("%m/%d/%y") #end date, for fig title markersize = 1.5 #markersize, for subplots linewidth = 1.0 #linewidth, for subplots fig = plt.figure() #create figure fig.set_size_inches(10, 10) #size figure if max(site_slice['snow_depth [cm]'] ) > 0: #six axes if there is snow depth ax1 = fig.add_subplot(6, 1, 1) ax2 = fig.add_subplot(6, 1, 2, sharex=ax1) ax3 = fig.add_subplot(6, 1, 3, sharex=ax1) ax4 = fig.add_subplot(6, 1, 4, sharex=ax1) ax5 = fig.add_subplot(6, 1, 5, sharex=ax1) ax6 = fig.add_subplot(6, 1, 6, sharex=ax1) ax6.set_xlabel('Time (UTC)') else: #five axes if no snow depth ax1 = fig.add_subplot(5, 1, 1) ax2 = fig.add_subplot(5, 1, 2, sharex=ax1) ax3 = fig.add_subplot(5, 1, 3, sharex=ax1) ax4 = fig.add_subplot(5, 1, 4, sharex=ax1) ax5 = fig.add_subplot(5, 1, 5, sharex=ax1) ax5.set_xlabel('Time (UTC)') ax1.set_title(site + ' ' + sitetitle + ', NY ' + graphtimestamp_start + ' - ' + graphtimestamp) #title figure #plot airT and dewT if 'temp_2m [degC]' in site_slice.keys(): airT = site_slice['temp_2m [degC]'] ax1.plot_date(dt, airT, 'o-', label="Temp", color="blue", linewidth=linewidth, markersize=markersize) if 'dew_point_temp_2m [degC]' in site_slice.keys(): Td = site_slice['dew_point_temp_2m [degC]'] ax1.plot_date(dt, Td, 'o-', label="Dew Point", color="black", linewidth=linewidth, markersize=markersize) if ax1.get_ylim()[0] < 0 < ax1.get_ylim()[1]: ax1.axhline(0, linestyle='-', linewidth=1.0, color='deepskyblue') trans = transforms.blended_transform_factory( ax1.get_yticklabels()[0].get_transform(), ax1.transData) ax1.text(0, 0, '0C', color="deepskyblue", transform=trans, ha="right", va="center") #light blue line at 0 degrees C ax1.set_ylabel('2m Temp ($^\circ$C)') ax1.legend(loc='best', ncol=2) axes = [ax1] #begin axes list #plot wind speed and gust if 'avg_wind_speed_merge [m/s]' in site_slice.keys(): wnd_spd = site_slice[ 'avg_wind_speed_merge [m/s]'] * 1.94384 #convert to knots ax2.plot_date(dt, wnd_spd, 'o-', label='Speed', color="forestgreen", linewidth=linewidth, markersize=markersize) if 'max_wind_speed_merge [m/s]' in site_slice.keys(): wnd_gst = site_slice[ 'max_wind_speed_merge [m/s]'] * 1.94384 #convert to knots max_wnd_gst = wnd_gst.max(skipna=True) ax2.plot_date(dt, wnd_gst, 'o-', label='Gust (Max ' + str(round(max_wnd_gst, 1)) + 'kt)', color="red", linewidth=linewidth, markersize=markersize) ax2.set_ylabel('Wind (kt)') ax2.legend(loc='best', ncol=2) axes.append(ax2) #plot wind direction if 'wind_direction_merge [degree]' in site_slice.keys(): wnd_dir = site_slice['wind_direction_merge [degree]'] ax3.plot_date(dt, wnd_dir, 'o-', label='Direction', color="purple", linewidth=0.2, markersize=markersize) ax3.set_ylim(-10, 370) ax3.set_ylabel('Wind Direction') ax3.set_yticks([0, 90, 180, 270, 360]) #locking y-ticks for wind direction axes.append(ax3) #plot MSLP (or station pressure, if MSLP unavailable) if 'mean_sea_level_pressure [mbar]' in site_slice.keys(): mslp = site_slice['mean_sea_level_pressure [mbar]'] min_mslp = mslp.min(skipna=True) #min 3-day mslp value max_mslp = mslp.max(skipna=True) #max 3-day mslp value labelname = 'Min ' + str(round(min_mslp, 2)) + 'hPa, Max ' + str( round(max_mslp, 2)) + 'hPa' ax4.plot_date(dt, mslp, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) ax4.set_ylabel('MSLP (hPa)') elif 'station_pressure [mbar]' in site_slice.keys(): sp = site_slice['station_pressure [mbar]'] min_sp = sp.min(skipna=True) #min 3-day station pressure value max_sp = sp.max(skipna=True) #max 3-day station pressure value labelname = 'Min ' + str(round(min_sp, 2)) + 'hPa, Max ' + str( round(max_sp, 2)) + 'hPa' ax4.plot_date(dt, sp, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) ax4.set_ylabel('STATION Pressure (hPa)') print('unable to get mslp, used station pressure instead') ax4.legend(loc='best') axes.append(ax4) #plot precip accum if 'precip_incremental [mm]' in site_slice.keys(): precip_inc = site_slice['precip_incremental [mm]'] precip_accum = 0.0 precip_accum_list = [] for increment in precip_inc: #calculate precip accumulation precip_accum = precip_accum + increment precip_accum_list.append(precip_accum) max_precip = max(precip_accum_list) labelname = 'Precip (' + str(round(max_precip, 2)) + 'mm)' ax5.plot_date(dt, precip_accum_list, 'o-', label=labelname, color='navy', linewidth=linewidth, markersize=markersize) if max_precip > 0: ax5.set_ylim(-0.1 * max_precip, max_precip + max_precip * 0.2) else: ax5.set_ylim(-0.5, 5) ax5.legend(loc='best') ax5.set_ylabel('Precip (mm)') axes.append(ax5) #plot snow depth if 'snow_depth [cm]' in site_slice.keys() and max( site_slice['snow_depth [cm]']) > 0: snow_depth = site_slice['snow_depth [cm]'] * 10 #convert to mm max_snow_depth = snow_depth.max(skipna=True) min_snow_depth = snow_depth.min(skipna=True) labelname = 'Min Depth ' + str(round( min_snow_depth, 2)) + 'mm, Max Depth ' + str( round(max_snow_depth, 2)) + 'mm' ax6.plot_date(dt, snow_depth, 'o-', label=labelname, color='deepskyblue', linewidth=linewidth, markersize=markersize) ax6.set_ylim(-0.1 * max_snow_depth, max_snow_depth + max_snow_depth * 0.2) if max_snow_depth > 0: ax5.set_ylim(-0.1 * max_snow_depth, max_snow_depth + max_snow_depth * 0.2) ax6.legend(loc='best') ax6.set_ylabel('Snow Depth (mm)') axes.append(ax6) for ax in axes: ax.spines["top"].set_visible(False) #remove dark borders on subplots ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis='x', which='both', bottom='on', top='off') #add ticks at labeled times ax.tick_params(axis='y', which='both', left='on', right='off') ax.xaxis.set_major_locator(DayLocator()) #one date written per day ax.xaxis.set_major_formatter( DateFormatter('%b-%d')) #show date, written as 'Jul-12' ax.xaxis.set_minor_locator(HourLocator(np.linspace( 6, 18, 3))) #hour labels every 6 hours ax.xaxis.set_minor_formatter(DateFormatter('%H')) #show hour labels ax.fmt_xdata = DateFormatter('Y%m%d%H%M%S') #fixes labels ax.yaxis.grid(linestyle='--') #adds y-axis grid lines ax.get_yaxis().set_label_coords( -0.06, 0.5) #properly places y-labels away from figure #define dates in YYYYmmdd format (for saving and finding files) three_days_ago_date = (latest - timedelta(hours=72)).strftime('%Y%m%d') two_days_ago_date = (latest - timedelta(hours=48)).strftime('%Y%m%d') yesterday_date = (latest - timedelta(hours=24)).strftime('%Y%m%d') today_date = latest.strftime('%Y%m%d') plot_path = plot_dir + '/' + today_date if not os.path.exists(plot_path): os.mkdir(plot_path) plt.savefig(plot_path + '/ops.nys_ground.' + timestamp_end + '.' + lower_site + '.png', bbox_inches='tight') plt.close() print('plotted ' + site)
def plot_station_data(site, site_long, dt, time_start, time_end, site_data, logo_path): '''Given a pandas dataframe containing all weather data for a specific station, this function saves a plot with the last 3 days worth of weather data for that station (or as much data as available if not yet 3-days). Parameters: site: 4 letter site identifier site_long: long name of site dt: dataframe contain all datetimes being plotted time_start: first datetime in dt; redundant time_end: last datetime in dt; redundant site_data (dataframe): pandas df containing all site data for 3 days to be plotted logo_path: path to png file containing NYS Mesonet logo Returns: Saves plots to plot_dir listed near top of MAIN CODE* plot_dir = '/home/disk/funnel/impacts/archive/ops/nys_ground' plot_dir = '/home/disk/bob/impacts/images/NYSM_standard'+'/'+site ''' time_start_string = datetime.strftime(time_start, '%H UTC %m/%d/%y') time_end_string = datetime.strftime(time_end, '%H UTC %m/%d/%y') markersize = 1.5 #markersize, for subplots linewidth = 1.5 #linewidth, for subplots fig = plt.figure() #create figure fig.set_size_inches(10, 10) #size figure ax1 = fig.add_subplot(6, 1, 1) ax2 = fig.add_subplot(6, 1, 2, sharex=ax1) ax3 = fig.add_subplot(6, 1, 3, sharex=ax1) ax4 = fig.add_subplot(6, 1, 4, sharex=ax1) ax5 = fig.add_subplot(6, 1, 5, sharex=ax1) ax6 = fig.add_subplot(6, 1, 6, sharex=ax1) ax1.set_title('{}, NY ({}) Meteogram\n{} - {}'.format( site_long, site, time_start_string, time_end_string), fontsize=16) #ax1.set_title('{}, NY ({}) Meteogram\n{} - {}'.format(site_data['name'][0], site, # time_start_string, time_end_string), fontsize=16) #plot airT and dewT #if 'temp_2m [degC]' in site_data.keys(): if 'tair' in site_data.keys(): #airT = site_data['temp_2m [degC]'] airT = site_data['tair'] ax1.plot_date(dt, airT, 'o-', label="Temp", color="red", linewidth=linewidth, markersize=markersize) ax1.set_xlim(time_start, time_end) #if 'dew_point_temp_2m [degC]' in site_data.keys(): #if 'dew_point_temp_2m [degC]' in site_data.keys(): if 'dewpt_temp' in site_data.keys(): #Td = site_data['dew_point_temp_2m [degC]'] Td = site_data['dewpt_temp'] ax1.plot_date(dt, Td, 'o-', label="Dew Point", color="forestgreen", linewidth=linewidth, markersize=markersize) # REDUNDANT?? #ax1.set_xlim(time_start, time_end) # draw 0 degC line if y limits go from negative to positive values if ax1.get_ylim()[0] < 0 < ax1.get_ylim()[1]: ax1.axhline(0, linestyle='-', linewidth=1.0, color='deepskyblue') # USED FOR PLACING TEXT THAT WE DON'T NEED - drawing '0 degC' in light blue on y axis ##trans = transforms.blended_transform_factory(ax1.get_yticklabels()[0].get_transform(), ax1.transData) ##ax1.text(0, 0, '0$^\circ$C', color="deepskyblue", transform=trans, ha="right", va="center") #light blue line at 0 degrees C ax1.set_ylabel('2-m Temp ($^\circ$C)') ax1.legend(loc='best', ncol=2) axes = [ax1] #begin axes list #plot wind speed and gust #if 'avg_wind_speed_merge [m/s]' in site_data.keys(): if 'wspd_merge' in site_data.keys(): #wnd_spd = site_data['avg_wind_speed_merge [m/s]'] * 1.94384 #convert to knots wnd_spd = mps_to_kts(site_data['wspd_merge']) #convert to knots ax2.plot_date(dt, wnd_spd, 'o-', label='Speed', color="black", linewidth=linewidth, markersize=markersize) #if 'max_wind_speed_merge [m/s]' in site_data.keys(): if 'wmax_merge' in site_data.keys(): #wnd_gst = site_data['max_wind_speed_merge [m/s]'] * 1.94384 #convert to knots wnd_gst = mps_to_kts(site_data['wmax_merge']) #convert to knots max_wnd_gst = wnd_gst.max(skipna=True) ax2.plot_date(dt, wnd_gst, 'o-', label='Gust [Max=' + str(round(max_wnd_gst, 1)) + ' kt]', color="blue", linewidth=linewidth, markersize=markersize) ax2.set_ylabel('Wind (kt)') ax2.legend(loc='best', ncol=2) axes.append(ax2) #plot wind direction #if 'wind_direction_merge [degree]' in site_data.keys(): if 'wdir_merge' in site_data.keys(): #wnd_dir = site_data['wind_direction_merge [degree]'] wnd_dir = site_data['wdir_merge'] ax3.plot_date(dt, wnd_dir, 'o-', label='Direction', color="purple", linewidth=0.2, markersize=markersize) ax3.set_ylim(-10, 370) ax3.set_ylabel('Wind Direction') ax3.set_yticks([0, 90, 180, 270, 360]) #locking y-ticks for wind direction axes.append(ax3) #plot MSLP (or station pressure, if MSLP unavailable) #if 'mean_sea_level_pressure [mbar]' in site_data.keys(): if 'mslp' in site_data.keys(): #mslp = site_data['mean_sea_level_pressure [mbar]'] mslp = site_data['mslp'] min_mslp = mslp.min(skipna=True) #min 3-day mslp value max_mslp = mslp.max(skipna=True) #max 3-day mslp value labelname = 'Min=' + str(round(min_mslp, 1)) + ' | Max=' + str( round(max_mslp, 1)) + ' hPa' ax4.plot_date(dt, mslp, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) ax4.set_ylabel('MSLP (hPa)') #elif 'station_pressure [mbar]' in site_data.keys(): elif 'pres' in site_data.keys(): #sp = site_data['station_pressure [mbar]'] sp = site_data['pres'] min_sp = sp.min(skipna=True) #min 3-day station pressure value max_sp = sp.max(skipna=True) #max 3-day station pressure value labelname = 'Min=' + str(round(min_sp, 1)) + ' | Max=' + str( round(max_sp, 1)) + ' hPa' ax4.plot_date(dt, sp, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) ax4.set_ylabel('Station Pressure (hPa)') print('unable to get mslp, used station pressure instead') ax4.legend(loc='best') axes.append(ax4) #plot precip accum #if 'precip_incremental [mm]' in site_data.keys(): if 'precip' in site_data.keys() and 'precip_total' in site_data.keys(): #precip_inc = site_data['precip_incremental [mm]'] #precip_accum = np.nancumsum(precip_inc) precip_offset = site_data['precip_total'][0] precip_accum = site_data['precip_total'] - precip_offset labelname = 'Max=' + str(round(precip_accum[-1], 2)) + ' mm' ax5.plot_date(dt, precip_accum, 'o-', label=labelname, color='navy', linewidth=linewidth, markersize=markersize) if precip_accum[-1] > 0: ax5.set_ylim(0, precip_accum[-1] * 1.2) else: ax5.set_ylim(0, 1) ax5.legend(loc='best') ax5.set_ylabel('Precip (mm)') axes.append(ax5) #plot snow depth #if 'snow_depth [cm]' in site_data.keys(): if 'snow_depth' in site_data.keys(): #snow_depth_mm = site_data['snow_depth [cm]'] * 10 # input data in cm; convert to mm snow_depth_mm = site_data[ 'snow_depth'] * 1000 # input data in m; convert to mm max_snow_depth_mm = snow_depth_mm.max(skipna=True) min_snow_depth_mm = snow_depth_mm.min(skipna=True) labelname = 'Min=' + str(round(min_snow_depth_mm, 2)) + ' | Max=' + str( round(max_snow_depth_mm, 2)) + ' mm' ax6.plot_date(dt, snow_depth_mm, 'o-', label=labelname, color='deepskyblue', linewidth=linewidth, markersize=markersize) if max_snow_depth_mm > 0: ax6.set_ylim(-0.1 * max_snow_depth_mm, max_snow_depth_mm * 1.2) else: ax6.set_ylim(0, 1) ax6.legend(loc='best') ax6.set_ylabel('Snow Depth (mm)') axes.append(ax6) for item, ax in enumerate(axes): # remove dark borders on all subplots except bottom border ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(True) # set x & y axis params ax.tick_params(axis='both', which='major', length=8) ax.tick_params(axis='both', which='minor', length=4) ax.xaxis.set_major_locator(DayLocator()) #one date written per day ax.xaxis.set_major_formatter( DateFormatter('%b-%d')) #show date, written as 'Jul-12' ax.xaxis.set_minor_locator(HourLocator(np.linspace( 3, 21, 7))) #hour labels every 3 hours ax.xaxis.set_minor_formatter(DateFormatter('%H')) #show hour labels ax.yaxis.grid(linestyle='--') #adds y-axis grid lines ax.get_yaxis().set_label_coords( -0.06, 0.5) #properly places y-labels away from figure # Add mesonet logo fig.subplots_adjust(bottom=0.1, left=.05, right=1.1) im = plt.imread(get_sample_data(logo_path)) new_ax = fig.add_axes([1, 0, 0.1, 0.1]) new_ax.imshow(im) new_ax.axis('off') # Get warning on next line: # "This figure includes Axes that are not compatible with tight_layout, so results might be incorrect." plt.tight_layout() # Save the plot plot_path = plot_dir + '/' + current_date_string if not os.path.exists(plot_path): os.mkdir(plot_path) catName = 'surface.Meteogram.' + current_dt_filestring + '.NYSM_' + site_long + '_NY' + '.png' plt.savefig(plot_path + '/' + catName, bbox_inches='tight') plt.clf(), plt.cla(), plt.close() # Open ftp connection if test: catalogFTP = FTP(ftpCatalogServer, ftpCatalogUser, ftpCatalogPassword) catalogFTP.cwd(catalogDestDir) else: catalogFTP = FTP(ftpCatalogServer, ftpCatalogUser) catalogFTP.cwd(catalogDestDir) # ftp plot to catalog ftpFile = open(plot_path + '/' + catName, 'rb') catalogFTP.storbinary('STOR ' + catName, ftpFile) ftpFile.close() # Close ftp connection catalogFTP.quit()
def pandas_candlestick_ohlc(dat, stick = "day", otherseries = None): mondays = WeekdayLocator(MONDAY) alldays = DayLocator() dayFormatter = DateFormatter('%d') transdat = dat.loc[:,["Open", "High", "Low", "Close"]] if (type(stick) == str): if stick == "day": plotdat = transdat stick = 1 elif stick in ["week", "month", "year"]: if stick == "week": transdat["week"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[1]) elif stick == "month": transdat["month"] = pd.to_datetime(transdat.index).map(lambda x: x.month) transdat["year"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[0]) grouped = transdat.groupby(list(set(["year",stick]))) plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) for name, group in grouped: plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1,3]}, index = [group.index[0]])) if stick == "week": stick = 5 elif stick == "month": stick = 30 elif stick == "year": stick = 365 elif (type(stick) == int and stick >= 1): transdat["stick"] = [np.floor(i / stick) for i in range(len(transdat.index))] grouped = transdat.groupby("stick") plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) for name, group in grouped: plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0], "High": max(group.High), "Low": min(group.Low), "Close": group.iloc[-1,3]}, index = [group.index[0]])) else: raise ValueError('Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer') fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'): weekFormatter = DateFormatter('%b %d') ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) else: weekFormatter = DateFormatter('%b %d, %Y') ax.xaxis.set_major_formatter(weekFormatter) ax.grid(True) candlestick_ohlc(ax, list(zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(), plotdat["Low"].tolist(), plotdat["Close"].tolist())), colorup = "black", colordown = "red", width = stick * .4) if otherseries != None: if type(otherseries) != list: otherseries = [otherseries] dat.loc[:,otherseries].plot(ax = ax, lw = 1.3, grid = True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
corrPrecip[exptNum,periodNum] = float(line[42]) #print rmsePrecip #------------------------------------------------------------------------------ # Start plotting the data #------------------------------------------------------------------------------ #Create doc to host several plots (now defined near top) #pp = PdfPages('Precip-RMSE_Microphys.pdf') #Precip plots #fig = plt.figure() for exptNum in range(numExpts): plt.gca().xaxis.set_major_locator(DayLocator()) plt.gca().xaxis.set_major_formatter(DateFormatter('%m/%d-%HZ')) plt.plot_date(allDates, rmsePrecip[exptNum,:], 'o-', label=exptLabels[exptNum], color=myColors[exptNum], linewidth=2) plt.gcf().autofmt_xdate() #Use this to get min/max of plot and then reset y-range to include 0 x1,x2,y1,y2 = plt.axis() plt.axis((x1,x2,0,y2)) plt.ylabel('24-hr Precipitation RMSE (mm)') plt.title('24-hr Precip RMSE Time Series ') plt.legend(loc='best', shadow=True, fontsize='x-small', fancybox=True) #plt.show() pp.savefig() pylab.savefig('Precip_RMSE.png')
def plot_station_data(site, sitetitle, df): '''Given site station ID, the title of that site, and a dataframe of ASOS observation data from the last 3 days, returns a plot of the last 3-days of weather at that site. Parameters: site (str): string of ASOS station ID sitetitle (str): string of ASOS station full name df (dataframe): dataframe containing last 72 hours (3 days) of ASOS station data Returns: None *saves plots to plot_dir listed near top of script* ''' if isinstance(df, int): #Returns if the station is not reporting return lower_site = site.lower() timestamp_end = str(df.index[-1].strftime('%Y%m%d%H%M')) dt = df.index[:] graphtimestamp_start = dt[0].strftime("%m/%d/%y") graphtimestamp = dt[-1].strftime("%m/%d/%y") now = datetime.datetime.utcnow() today_date = dt[-1].strftime('%Y%m%d') markersize = 1.5 linewidth = 1.0 #make figure and axes fig = plt.figure() fig.set_size_inches(18, 10) if 'snow_depth_set_1' in df.keys(): #six axes if snow depth ax1 = fig.add_subplot(6, 1, 1) ax2 = fig.add_subplot(6, 1, 2, sharex=ax1) ax3 = fig.add_subplot(6, 1, 3, sharex=ax1) ax4 = fig.add_subplot(6, 1, 4, sharex=ax1) ax5 = fig.add_subplot(6, 1, 5, sharex=ax1) ax6 = fig.add_subplot(6, 1, 6, sharex=ax1) ax6.set_xlabel('Time (UTC)') else: ax1 = fig.add_subplot(5, 1, 1) #five axes if no snow depth ax2 = fig.add_subplot(5, 1, 2, sharex=ax1) ax3 = fig.add_subplot(5, 1, 3, sharex=ax1) ax4 = fig.add_subplot(5, 1, 4, sharex=ax1) ax5 = fig.add_subplot(5, 1, 5, sharex=ax1) ax5.set_xlabel('Time (UTC)') #ax1.set_title(site+' '+sitetitle+' '+graphtimestamp_start+' - '+graphtimestamp+' '+now.strftime("%H:%MZ")) ax1.set_title(site + ' ' + sitetitle + ' ' + graphtimestamp_start + ' - ' + graphtimestamp) #plot airT and dewT if 'air_temp_set_1' in df.keys(): airT = df['air_temp_set_1'] ax1.plot_date(dt, airT, 'o-', label="Temp", color="blue", linewidth=linewidth, markersize=markersize) if 'dew_point_temperature_set_1d' in df.keys(): dewT = df['dew_point_temperature_set_1d'] ax1.plot_date(dt, dewT, 'o-', label="Dew Point", color="black", linewidth=linewidth, markersize=markersize) elif 'dew_point_temperature_set_1' in df.keys(): dewT = df['dew_point_temperature_set_1'] dewT_new = dewT.dropna() dewT_dt_list = [] for i in range(0, len(dewT)): if pd.isnull(dewT[i]) == False: dewT_dt_list.append(dt[i]) ax1.plot_date(dewT_dt_list, dewT_new, 'o-', label="Dew Point", color="black", linewidth=linewidth, markersize=markersize) if ax1.get_ylim()[0] < 0 < ax1.get_ylim()[1]: ax1.axhline(0, linestyle='-', linewidth=1.0, color='deepskyblue') trans = transforms.blended_transform_factory( ax1.get_yticklabels()[0].get_transform(), ax1.transData) ax1.text(0, 0, '0C', color="deepskyblue", transform=trans, ha="right", va="center") #light blue line at 0 degrees C ax1.set_ylabel('Temp ($^\circ$C)') ax1.legend(loc='best', ncol=2) axes = [ax1] #begin axes #plotting wind speed and gust if 'wind_speed_set_1' in df.keys(): wnd_spd = df['wind_speed_set_1'] ax2.plot_date(dt, wnd_spd, 'o-', label='Speed', color="forestgreen", linewidth=linewidth, markersize=markersize) if 'wind_gust_set_1' in df.keys(): wnd_gst = df['wind_gust_set_1'] max_wnd_gst = wnd_gst.max(skipna=True) ax2.plot_date(dt, wnd_gst, 'o-', label='Gust (Max ' + str(round(max_wnd_gst, 1)) + 'kt)', color="red", linewidth=0.0, markersize=markersize) ax2.set_ylabel('Wind (kt)') ax2.legend(loc='best', ncol=2) axes.append(ax2) #plotting wind direction if 'wind_direction_set_1' in df.keys(): wnd_dir = df['wind_direction_set_1'] ax3.plot_date(dt, wnd_dir, 'o-', label='Direction', color="purple", linewidth=0.2, markersize=markersize) ax3.set_ylim(-10, 370) ax3.set_ylabel('Wind Direction') ax3.set_yticks([0, 90, 180, 270, 360]) axes.append(ax3) #plotting MSLP if 'sea_level_pressure_set_1d' in df.keys(): mslp = df['sea_level_pressure_set_1d'] max_mslp = mslp.max(skipna=True) min_mslp = mslp.min(skipna=True) labelname = 'Min ' + str(round(min_mslp, 1)) + 'hPa, Max ' + str( round(max_mslp, 2)) + 'hPa' ax4.plot_date(dt, mslp, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) elif 'sea_level_pressure_set_1' in df.keys(): mslp = df['sea_level_pressure_set_1'] mslp_new = mslp.dropna() mslp_dt_list = [] for i in range(0, len(mslp)): if pd.isnull(mslp[i]) == False: mslp_dt_list.append(dt[i]) max_mslp = mslp.max(skipna=True) min_mslp = mslp.min(skipna=True) labelname = 'Min ' + str(round(min_mslp, 2)) + 'hPa, Max ' + str( round(max_mslp, 2)) + 'hPa' ax4.plot_date(mslp_dt_list, mslp_new, 'o-', label=labelname, color='darkorange', linewidth=linewidth, markersize=markersize) ax4.legend(loc='best') ax4.set_ylabel('MSLP (hPa)') ax4.set_xlabel('Time (UTC)') axes.append(ax4) #plotting precip accumulation if 'precip_intervals_set_1d' in df.keys(): precip_inc = df['precip_intervals_set_1d'] precip_inc_new = precip_inc.dropna() precip_inc_new = list(precip_inc_new.values) precip_accum = 0.0 precip_accum_list = [] for increment in precip_inc_new: precip_accum = precip_accum + increment precip_accum_list.append(precip_accum) precip_dt_list = [] for i in range(0, len(precip_inc)): if pd.isnull(precip_inc[i]) == False: precip_dt_list.append(dt[i]) max_precip = max(precip_accum_list) labelname = 'Precip (' + str(round(max_precip, 2)) + 'mm)' ax5.plot_date(precip_dt_list, precip_accum_list, 'o-', label=labelname, color='navy', linewidth=linewidth, markersize=markersize) if max_precip > 0: ax5.set_ylim(-0.1 * max_precip, max_precip + max_precip * 0.2) else: ax5.set_ylim(-0.5, 5) ax5.legend(loc='best') ax5.set_ylabel('Precip (mm)') axes.append(ax5) #plotting snow depth if 'snow_depth_set_1' in df.keys(): snow_depth = df['snow_depth_set_1'] snow_depth_new = snow_depth.dropna() snow_depth_dt_list = [] for i in range(0, len(snow_depth)): if pd.isnull(snow_depth[i]) == False: snow_depth_dt_list.append(dt[i]) max_snow_depth = snow_depth.max(skipna=True) min_snow_depth = snow_depth.min(skipna=True) labelname = 'Min Depth ' + str(round( min_snow_depth, 2)) + 'mm, Max Depth ' + str( round(max_snow_depth, 2)) + 'mm' ax6.plot_date(snow_depth_dt_list, snow_depth_new, 'o-', label=labelname, color='deepskyblue', linewidth=linewidth, markersize=markersize) if max_snow_depth > 0: ax6.set_ylim(-0.1 * max_snow_depth, max_snow_depth + max_snow_depth * 0.2) else: ax6.set_ylim(-0.5, 5) ax6.legend(loc='best') ax6.set_ylabel('Snow Depth (mm)') axes.append(ax6) for ax in axes: ax.spines["top"].set_visible( False) #darker borders on the grids of each subplot ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis='x', which='both', bottom='on', top='off') #add ticks at labeled times ax.tick_params(axis='y', which='both', left='on', right='off') ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter('%b-%d')) ax.xaxis.set_minor_locator(HourLocator(np.linspace(6, 18, 3))) ax.xaxis.set_minor_formatter(DateFormatter('%H')) ax.fmt_xdata = DateFormatter('Y%m%d%H%M%S') ax.yaxis.grid(linestyle='--') ax.get_yaxis().set_label_coords(-0.06, 0.5) plot_path = plot_dir + '/' + today_date if not os.path.exists(plot_path): os.makedirs(plot_path) try: plt.savefig(plot_path + '/ops.asos.' + timestamp_end + '.' + lower_site + '.png', bbox_inches='tight') except: print("Problem saving figure for %s. Usually a maxticks problem" % site) plt.close()
def plot_station_data(date, site, sitetitle, df): '''Given site station ID, the title of that site, and a dataframe of ASOS observation data from the last 3 days, returns a plot of the last 3-days of weather at that site. Parameters: site (str): string of ASOS station ID sitetitle (str): string of ASOS station full name df (dataframe): dataframe containing last 72 hours (3 days) of ASOS station data Returns: None *saves plots to plot_dir listed near top of script* ''' #if isinstance(df, int): #Returns if the station is not reporting # return if df.empty: print('dataframe is empty -- go to next plot') return lower_site = site.lower() timestamp_end = str(df.index[-1].strftime('%Y%m%d%H%M')) dt = df.index[:] dt_array = np.array(dt.values) graphtimestamp_start = dt[0].strftime("%m/%d/%y") graphtimestamp = dt[-1].strftime("%m/%d/%y") #now = datetime.datetime.utcnow() now = datetime.strptime(date, '%Y%m%d') today_date = dt[-1].strftime('%Y%m%d') markersize = 1.5 linewidth = 1.0 #make figure and axes fig = plt.figure() fig.set_size_inches(18, 10) if 'snow_depth_set_1' in df.keys(): #six axes if snow depth ax1 = fig.add_subplot(6, 1, 1) ax2 = fig.add_subplot(6, 1, 2, sharex=ax1) ax3 = fig.add_subplot(6, 1, 3, sharex=ax1) ax4 = fig.add_subplot(6, 1, 4, sharex=ax1) ax5 = fig.add_subplot(6, 1, 5, sharex=ax1) ax6 = fig.add_subplot(6, 1, 6, sharex=ax1) ax6.set_xlabel('Time (UTC)') else: ax1 = fig.add_subplot(5, 1, 1) #five axes if no snow depth ax2 = fig.add_subplot(5, 1, 2, sharex=ax1) ax3 = fig.add_subplot(5, 1, 3, sharex=ax1) ax4 = fig.add_subplot(5, 1, 4, sharex=ax1) ax5 = fig.add_subplot(5, 1, 5, sharex=ax1) ax5.set_xlabel('Time (UTC)') #ax1.set_title(site+' '+sitetitle+' '+graphtimestamp_start+' - '+graphtimestamp+' '+now.strftime("%H:%MZ")) ax1.set_title(site + ' ' + sitetitle + ' ' + graphtimestamp_start + ' - ' + graphtimestamp) #------------------ #plot airT and dewT #------------------ if 'tmpc' in df.keys(): airT = df['tmpc'] airT_new = airT.dropna() airT_list = list(airT_new.values) airT_dt_list = [] for i in range(0, len(airT)): if pd.isnull(airT[i]) == False: airT_dt_list.append(dt[i]) #ax1.plot_date(airT_dt_list,airT_list,'o-',label="Temp",color="blue",linewidth=linewidth,markersize=markersize) ax1.plot_date(airT_dt_list, airT_list, linestyle='solid', label="Temp", color="blue", linewidth=linewidth, marker='None') #ax1.plot_date(dt,airT,'-',label="Temp",color="blue",linewidth=linewidth) if 'dwpc' in df.keys(): dewT = df['dwpc'] dewT_new = dewT.dropna() dewT_list = list(dewT_new.values) dewT_dt_list = [] for i in range(0, len(dewT)): if pd.isnull(dewT[i]) == False: dewT_dt_list.append(dt[i]) #ax1.plot_date(dewT_dt_list,dewT_list,'o-',label="Dew Point",color="black",linewidth=linewidth,markersize=markersize) ax1.plot_date(dewT_dt_list, dewT_list, linestyle='solid', label="Dew Point", color="black", linewidth=linewidth, marker='None') if ax1.get_ylim()[0] < 0 < ax1.get_ylim()[1]: ax1.axhline(0, linestyle='-', linewidth=1.0, color='deepskyblue') trans = transforms.blended_transform_factory( ax1.get_yticklabels()[0].get_transform(), ax1.transData) ax1.text(0, 0, '0C', color="deepskyblue", transform=trans, ha="right", va="center") #light blue line at 0 degrees C ax1.set_ylabel('Temp ($^\circ$C)') ax1.legend(loc='best', ncol=2) axes = [ax1] #begin axes #---------------------------- #plotting wind speed and gust #---------------------------- if 'sknt' in df.keys(): wnd_spd = df['sknt'] #ax2.plot_date(dt,wnd_spd,'o-',label='Speed',color="forestgreen",linewidth=linewidth,markersize=markersize) ax2.plot_date(dt, wnd_spd, linestyle='solid', label='Speed', color="forestgreen", linewidth=linewidth, marker='None') if 'gust' in df.keys(): wnd_gst = df['gust'] max_wnd_gst = wnd_gst.max(skipna=True) ax2.plot_date(dt, wnd_gst, 'o-', label='Gust (Max ' + str(round(max_wnd_gst, 1)) + 'kt)', color="red", linewidth=0.0, markersize=markersize) ax2.set_ylabel('Wind (kt)') ax2.legend(loc='best', ncol=2) axes.append(ax2) #----------------------- #plotting wind direction #----------------------- if 'drct' in df.keys(): wnd_dir = df['drct'] wnd_dir_new = wnd_dir.dropna() wnd_dir_list = list(wnd_dir_new.values) wnd_dir_dt_list = [] for i in range(0, len(wnd_dir)): if pd.isnull(wnd_dir[i]) == False: wnd_dir_dt_list.append(dt[i]) #ax3.plot_date(dt,wnd_dir,'o-',label='Direction',color="purple",linewidth=0.2, markersize=markersize) #ax3.plot_date(wnd_dir_dt_list,wnd_dir_list,'o-',label='Direction',color="purple",linewidth=0.2, markersize=markersize) ax3.plot_date(wnd_dir_dt_list, wnd_dir_list, linestyle='solid', label='Direction', color="purple", linewidth=linewidth, marker='None') ax3.set_ylim(-10, 370) ax3.set_ylabel('Wind Direction') ax3.set_yticks([0, 90, 180, 270, 360]) axes.append(ax3) #------------- #plotting MSLP #------------- if 'mslp' in df.keys(): mslp = df['mslp'] mslp_new = mslp.dropna() mslp_list = list(mslp_new.values) mslp_dt_list = [] for i in range(0, len(mslp)): if pd.isnull(mslp[i]) == False: mslp_dt_list.append(dt[i]) max_mslp = mslp.max(skipna=True) min_mslp = mslp.min(skipna=True) labelname = 'Min ' + str(round(min_mslp, 1)) + 'hPa, Max ' + str( round(max_mslp, 2)) + 'hPa' #ax4.plot_date(mslp_dt_list,mslp_list,'o-',label=labelname,color='darkorange',linewidth=linewidth,markersize=markersize) ax4.plot_date(mslp_dt_list, mslp_list, linestyle='solid', label=labelname, color='darkorange', linewidth=linewidth, marker='None') ax4.legend(loc='best') ax4.set_ylabel('MSLP (hPa)') ax4.set_xlabel('Time (UTC)') axes.append(ax4) #------------------------------------------- #plotting precip accumulation & precip types #------------------------------------------- # Move date_time from index to column df = df.reset_index() if 'p01m' in df.keys(): df['p01m'] = df['p01m'].fillna(0) last_val = df.iloc[0]['p01m'] last_time = df.iloc[0]['time'] last_hour = last_time.strftime('%H') last_minute = last_time.strftime('%M') precip_inc = [last_val] precip_accum = 0.0 precip_accum_list = [last_val] num_ge_55_for_curr_hour = 0 for index in range(1, len(df)): #for index in range(1,12): val = df.iloc[index]['p01m'] time = df.iloc[index]['time'] hour = time.strftime('%H') minute = time.strftime('%M') #print('LAST: val=',last_val,' hour=',last_hour,' minute=',last_minute) #print('CURR: val=',val,' hour=',hour,' minute=',minute) if hour != last_hour: num_ge_55_for_curr_hour = 0 #if val == last_val: # increment = 0.0 #else: # #if last_minute == '53': # if last_minute > '50' and last_minute < '55': # increment = val # else: # increment = val-last_val if minute >= '55': if num_ge_55_for_curr_hour == 0: increment = val else: if val > last_val: increment = val - last_val else: increment = 0 num_ge_55_for_curr_hour = num_ge_55_for_curr_hour + 1 else: if val == last_val: increment = 0 else: if val > last_val: increment = val - last_val else: increment = 0 precip_accum = precip_accum + increment precip_accum_list.append(precip_accum) precip_inc.append(increment) last_val = val last_hour = hour last_minute = minute #df['p01m_mod'] = precip_inc max_precip = sum(precip_inc) # max_precip is also precip_accum_list[-1] #p01m_mod = list(df['p01m_mod'].values) p01m_mod_dt = list(df['time'].values) #max_precip = max(precip_accum_list) labelname = 'Precip (' + str(round(max_precip, 2)) + 'mm)' #ax5.plot_date(p01m_mod_dt,precip_accum_list,'o-',label=labelname,color='navy',linewidth=linewidth,markersize=markersize) ax5.plot_date(p01m_mod_dt, precip_accum_list, linestyle='solid', label=labelname, color='navy', linewidth=linewidth, marker='None') if max_precip > 0: ax5.set_ylim(-0.1 * max_precip, max_precip + max_precip * 0.2) else: ax5.set_ylim(-0.1, 0.5) # Add weather_code info to plot if 'wxcodes' in df.keys(): df['wxcodes'] = df['wxcodes'].fillna('') wxcodes_wto = [] for index in range(0, len(df)): time = df.iloc[index]['time'] minute = time.strftime('%M') #if minute == '53': if minute > '50' and minute < '55': # convert alphanumeric code to wto code number wxcodes = df.iloc[index]['wxcodes'] # Added in a check in case of unexpected weather codes # Used to resolve case when code set to -FZRAGR instead of -FZRA GR # Unidata says this will work as well: # wxcode_num = wx_code_map.get(wxcodes.split()[0], 0) # Here is reference: https://docs.python.org/3/library/stdtypes.html#dict.get if len(wxcodes) > 0 and wxcodes.split()[0] in wx_codes.keys(): wxcode_num = wx_code_map[wxcodes.split()[0]] else: wxcode_num = 0 else: wxcode_num = 0 wxcodes_wto.append(wxcode_num) #df['wxcodes_wto'] = wxcode_wto #wxcodes_wto = list(df['wxcodes_wto'].values) wxcodes_wto_dt = list(df['time'].values) if max_precip > 0: dummy_y_vals = np.ones(len(wxcodes_wto)) * (0.10 * max_precip) else: dummy_y_vals = np.ones(len(wxcodes_wto)) * (0.10 * 0.5) sp = StationPlot(ax5, wxcodes_wto_dt, dummy_y_vals) #ax.plot(dates, temps) sp.plot_symbol('C', wxcodes_wto, current_weather, fontsize=16, color='red') #sp.plot_symbol('C', wxcodes_wto, current_weather, fontsize=14, color='red') ax5.legend(loc='best') ax5.set_ylabel('Precip (mm)') axes.append(ax5) # Axes formatting for ax in axes: ax.spines["top"].set_visible( False) #darker borders on the grids of each subplot ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.tick_params(axis='x', which='both', bottom='on', top='off') #add ticks at labeled times ax.tick_params(axis='y', which='both', left='on', right='off') ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter('%b-%d')) ax.xaxis.set_minor_locator(HourLocator(np.linspace(6, 18, 3))) ax.xaxis.set_minor_formatter(DateFormatter('%H')) ax.fmt_xdata = DateFormatter('Y%m%d%H%M%S') ax.yaxis.grid(linestyle='--') ax.get_yaxis().set_label_coords(-0.06, 0.5) # Write plot to file plot_path = plot_dir + '/' + today_date if not os.path.exists(plot_path): os.makedirs(plot_path) try: catalogName = 'surface.Meteogram.' + timestamp_end + '.ASOS_' + asos_sites[ lower_site] + '.png' #plt.savefig(plot_path+'/ops.asos.'+timestamp_end+'.'+lower_site+'.png',bbox_inches='tight') plt.savefig(plot_path + '/' + catalogName, bbox_inches='tight') except: print("Problem saving figure for %s. Usually a maxticks problem" % site) plt.close() # DON'T NEED THIS CHECK FOR RT PROCESSING # ftp plot if in asos_for_cat list #if lower_site in asos_for_cat: # Open ftp connection if test: catalogFTP = FTP(ftpCatalogServer, ftpCatalogUser, ftpCatalogPassword) catalogFTP.cwd(catalogDestDir) else: catalogFTP = FTP(ftpCatalogServer, ftpCatalogUser) catalogFTP.cwd(catalogDestDir) catalogFTP.set_pasv(False) # ftp image ftpFile = open(os.path.join(plot_path, catalogName), 'rb') catalogFTP.storbinary('STOR ' + catalogName, ftpFile) ftpFile.close() # Close ftp connection catalogFTP.quit()
def new_plot(timezone, plot_title, figname, times_utc, height, bs_final, ML_height=0, tick_every=12, save=False, show=True): ## Creates a plot of backscatter # convert DateTime array to matplotlib.dates format plot_dates = mdates.date2num(times_utc) # set plotting grids ptt = np.zeros(bs_final.shape) phh = np.zeros(bs_final.shape) for i in range(ptt.shape[0]): ptt[i, :] = plot_dates[i] for j in range(phh.shape[1]): phh[:, j] = height[j] # Set plotting range minv = -7.4 maxv = -6.8 #fig = plt.figure(1, figsize=(20,8)) # Long plot fig = plt.figure(1, figsize=(12, 6)) # Short Plot ax = fig.add_subplot(111) qmesh = ax.pcolormesh(ptt, phh, bs_final, cmap=plt.cm.jet, vmin=minv, vmax=maxv) # Colorbar cb = fig.colorbar(qmesh, ax=ax, shrink=0.8, pad=0.02) cb.ax.set_ylabel('Backscatter [log10 m-1 sr-1]', fontsize=14) tv = np.linspace(minv, maxv, 7) cb.ax.set_yticklabels(tv, fontsize=14) cb.set_ticks(tv) # Labels plt.ylabel('Height (m)', fontsize=16) plt.xlabel('Hour:Minute (' + timezone + ')', fontsize=16) #plt.xlabel('Time ('+timezone+')') plt.title(plot_title, fontsize=21) # Format Ticks if tick_every == 12: # Place a major tick and label every 12 hours, place minor tick every hour. days = DayLocator(interval=2) days_each = DayLocator() hours = HourLocator(byhour=[0, 12]) hours_each = HourLocator() mins = MinuteLocator(byminute=[10, 20, 30, 40, 50]) #mins = MinuteLocator(byminute=30) mins_each = MinuteLocator() dateFmt = DateFormatter('%H:%M') ax.xaxis.set_major_locator(hours_each) ax.xaxis.set_major_formatter(dateFmt) ax.xaxis.set_minor_locator(mins) #increase size of tick marks ax.tick_params('both', length=8, width=1.2, which='major') ax.tick_params('both', length=4, width=1, which='minor') plt.xticks(rotation=30, fontsize=14) plt.yticks(fontsize=14) ## Plot mixed layer height if provided: #if ML_height!=0: if len(ML_height) > 0: plt.plot(times_utc, ML_height, 'k', linewidth=2) plt.tight_layout() if show == True: plt.show() if save == True: save_plot(figname, fig) return fig
def plot_factor_info(factor_name, the_dates, signature, signature_avg, signature_std, \ signature_th04, signature_th04_avg, signature_th04_std,\ signature_th06, signature_th06_avg, signature_th06_std,\ signature_th08, signature_th08_avg, signature_th08_std,\ scores, scores_avg, scores_std, \ basepath, TIME_SLOTS_PER_DAY, plot_scores=True, \ whole_series_std_dev=None, \ whole_series_std_dev_th04=None, \ whole_series_std_dev_th06=None, \ whole_series_std_dev_th08=None): ''' Plot all the cluster signatures in a single plot ''' max_figs_per_line = 4 if plot_scores: max_rows_per_page = 7 else: max_rows_per_page = 5 f = plt.figure() f.set_size_inches(10 * max_figs_per_line, 4 * max_rows_per_page) ax = plt.subplot(max_rows_per_page, 1, 1) base_line, = ax.plot_date(x=the_dates, y=signature, fmt="-", linewidth=2) ax.xaxis.grid(True, which='major', color='gray', linestyle='-', alpha=1.0) ax.xaxis.grid(True, which='minor', color='gray', linestyle='--', alpha=0.4) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d (%a)')) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MONDAY)) ax.xaxis.set_minor_locator(DayLocator()) ax.set_xlim([the_dates[0], the_dates[-1]]) ax.set_xlabel('Signature') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) if whole_series_std_dev is not None: base_c = base_line.get_color() ax.fill_between(the_dates, np.array(signature) - np.array(whole_series_std_dev), np.array(signature) + np.array(whole_series_std_dev), alpha=0.4, edgecolor=base_c, facecolor=base_c) ax = plt.subplot(max_rows_per_page, 1, 2) base_line, = ax.plot_date(x=the_dates, y=signature_th04, fmt="-", linewidth=2) ax.xaxis.grid(True, which='major', color='gray', linestyle='-', alpha=1.0) ax.xaxis.grid(True, which='minor', color='gray', linestyle='--', alpha=0.4) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d (%a)')) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MONDAY)) ax.xaxis.set_minor_locator(DayLocator()) ax.set_xlim([the_dates[0], the_dates[-1]]) ax.set_xlabel('Signature with th. 0.4') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) if whole_series_std_dev is not None: base_c = base_line.get_color() ax.fill_between( the_dates, np.array(signature_th04) - np.array(whole_series_std_dev_th04), np.array(signature_th04) + np.array(whole_series_std_dev_th04), alpha=0.4, edgecolor=base_c, facecolor=base_c) ax = plt.subplot(max_rows_per_page, 1, 3) ax.plot_date(x=the_dates, y=signature_th06, fmt="-", linewidth=2) ax.xaxis.grid(True, which='major', color='gray', linestyle='-', alpha=1.0) ax.xaxis.grid(True, which='minor', color='gray', linestyle='--', alpha=0.4) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d (%a)')) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MONDAY)) ax.xaxis.set_minor_locator(DayLocator()) ax.set_xlim([the_dates[0], the_dates[-1]]) ax.set_xlabel('Signature with th. 0.6') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) if whole_series_std_dev is not None: base_c = base_line.get_color() ax.fill_between( the_dates, np.array(signature_th06) - np.array(whole_series_std_dev_th06), np.array(signature_th06) + np.array(whole_series_std_dev_th06), alpha=0.4, edgecolor=base_c, facecolor=base_c) ax = plt.subplot(max_rows_per_page, 1, 4) ax.plot_date(x=the_dates, y=signature_th08, fmt="-", linewidth=2) ax.xaxis.grid(True, which='major', color='gray', linestyle='-', alpha=1.0) ax.xaxis.grid(True, which='minor', color='gray', linestyle='--', alpha=0.4) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d (%a)')) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MONDAY)) ax.xaxis.set_minor_locator(DayLocator()) ax.set_xlim([the_dates[0], the_dates[-1]]) ax.set_xlabel('Signature with th. 0.8') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) if whole_series_std_dev is not None: base_c = base_line.get_color() ax.fill_between( the_dates, np.array(signature_th08) - np.array(whole_series_std_dev_th08), np.array(signature_th08) + np.array(whole_series_std_dev_th08), alpha=0.4, edgecolor=base_c, facecolor=base_c) ax = plt.subplot(max_rows_per_page, max_figs_per_line, 17) plotAverageSeries(signature_avg, signature_std, TIME_SLOTS_PER_DAY, ax=ax) ax.set_xlabel('Average Signature') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) ax = plt.subplot(max_rows_per_page, max_figs_per_line, 18) plotAverageSeries(signature_th04_avg, signature_th04_std, TIME_SLOTS_PER_DAY, ax=ax) ax.set_xlabel('Average Signature with th. 0.4') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) ax = plt.subplot(max_rows_per_page, max_figs_per_line, 19) plotAverageSeries(signature_th06_avg, signature_th06_std, TIME_SLOTS_PER_DAY, ax=ax) ax.set_xlabel('Average Signature with th. 0.6') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) ax = plt.subplot(max_rows_per_page, max_figs_per_line, 20) plotAverageSeries(signature_th08_avg, signature_th08_std, TIME_SLOTS_PER_DAY, ax=ax) ax.set_xlabel('Average Signature with th. 0.8') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) if plot_scores: ax = plt.subplot(max_rows_per_page, 1, 6) ax.plot_date(x=the_dates, y=scores, fmt="-", linewidth=2) ax.xaxis.grid(True, which='major', color='gray', linestyle='-', alpha=1.0) ax.xaxis.grid(True, which='minor', color='gray', linestyle='--', alpha=0.4) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d (%a)')) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MONDAY)) ax.xaxis.set_minor_locator(DayLocator()) ax.set_xlim([the_dates[0], the_dates[-1]]) ax.set_xlabel('Scores') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) ax = plt.subplot(max_rows_per_page, max_figs_per_line, 25) plotAverageSeries(scores_avg, scores_std, TIME_SLOTS_PER_DAY, ax=ax) ax.set_xlabel('Average Scores') ax.xaxis.set_label_coords(0.5, 0.96) for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(18) plt.tight_layout() if plot_scores: plt.savefig('%s%s_signatures_and_scores.pdf' % (basepath, factor_name)) else: plt.savefig('%s%s_signatures.pdf' % (basepath, factor_name)) plt.close()
except Exception as e: print(e) #蜡烛图 from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY, date2num from matplotlib.finance import candlestick_ohlc, candlestick2_ochl import datetime from datetime import date import pylab #怎么使用candlestick_ohlc(candlestick2_ochl) #matplotlib.finance.candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0) #https://matplotlib.org/api/finance_api.html mondays = WeekdayLocator(MONDAY) #用于横坐标设定,每个显示的横坐标都是周一 alldays = DayLocator() #横坐标的最小单位为一天 %pylab inline pylab.rcParams['figure.figsize'] = (15, 9) #设置图片的大小 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) weekFormatter = DateFormatter('%b %d, %Y') #设置坐标显示的日期格式Jun 5, 2018 ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) ax.grid(True) candlestick_ohlc(ax, list(zip(list(date2num(apple.index.tolist())), apple["Open"].tolist(), apple["High"].tolist(), apple["Low"].tolist(), apple["Close"].tolist())), colorup = "red", colordown = "green", width = 1 * .4) # candlestick2_ochl(ax, apple["Open"].tolist(), apple["Close"].tolist(), apple["High"].tolist(), # apple["Low"].tolist(),
yen_data = pd.read_csv( 'http://research.stlouisfed.org/fred2/data/EXJPUS.txt', skiprows=28, index_col=0, delim_whitespace=True, converters={0: lambda x: datetime.strptime(x, "%Y-%m-%d")}) ############## Creation of Top Chart ########### fig, axes = plt.subplots( 2, 1) # Create a grid of 2 rows and 1 column of charts (2 charts total) # Let's define x-axis date interval sizes: year, month, week, or day year = YearLocator() month = MonthLocator(bymonth=range(1, 13), bymonthday=1, interval=1) week = WeekdayLocator(byweekday=dateutil.rrule.MO) # Every MOnday day = DayLocator(bymonthday=range(1, 32), interval=1) axes[0] = fig.add_axes([0, 1.3, 1.5, 1]) # left, bottom, width, height # Let's define x-axis formatting axes[0].xaxis.set_major_locator(year) axes[0].xaxis.grid(which='major') # Let's define y-axis formatting y_major_ticks = MultipleLocator(50) axes[0].yaxis.set_major_locator(y_major_ticks) axes[0].yaxis.grid(which='major') # Now plot the data... axes[0].plot_date(yen_data.index, yen_data.values, 'r') axes[0].set_title("Yen-to-US$ Exchange Rate Since 1971", weight="bold")
# Checking if there is a relationship between these stocks using # a scatter matrix plot. Rearranging the Open columns into a new dataframe. car_comp = pd.concat([tesla['Open'], gm['Open'], ford['Open']], axis=1) car_comp.columns = ['Tesla Open', 'GM Open', 'Ford Open'] scatter_matrix(car_comp, figsize=(8, 8), alpha=0.2, hist_kwds={'bins': 50}) # Creating a candlestick chart for Ford in January 2012 ford_reset = ford.loc['2012-01'].reset_index() ford_reset['date_ax'] = ford_reset['Date'].apply(lambda date: date2num(date)) list_of_cols = ['date_ax', 'Open', 'High', 'Low', 'Close'] ford_values = [tuple(vals) for vals in ford_reset[list_of_cols].values] mondays = WeekdayLocator(MONDAY) alldays = DayLocator() weekFormatter = DateFormatter('%b %d') dayFormatter = DateFormatter('%d') fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) candlestick_ohlc(ax, ford_values, width=0.6, colorup='g', colordown='r') # Calculating daily percentage change tesla['returns'] = (tesla['Close'] / tesla['Close'].shift(1)) - 1
def drawPic(df, code, name): mondays = WeekdayLocator(MONDAY) # 主要刻度 alldays = DayLocator() # 次要刻度 # weekFormatter = DateFormatter('%b %d') # 如:Jan 12 mondayFormatter = DateFormatter('%m-%d-%Y') # 如:2-29-2015 dayFormatter = DateFormatter('%d') # 如:12 xx = [] t = 0 for DAT, DD in df.iterrows(): t = t + 10 xx.append(t) # -------------------------------------------------------------------- plt.figure(4) # 创建图表2 ax1 = plt.subplot(411) # 在图表2中创建子图1 ax2 = plt.subplot(412) # 在图表2中创建子图2 ax3 = plt.subplot(413) # 在图表2中创建子图2 ax4 = plt.subplot(414) # 在图表2中创建子图2 # --------------------------------------------(子图表1) plt.sca(ax1) ax1.xaxis.set_major_locator(mondays) ax1.xaxis.set_minor_locator(alldays) ax1.xaxis.set_major_formatter(mondayFormatter) _candlestick(ax1, df, width=0.6, colorup='r', colordown='g') ax1.xaxis_date() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') """ plt.plot( xx, df['ma5'], linewidth = 0.5 ) plt.plot( xx, df['ma10'], linewidth = 0.5 ) plt.plot( xx, df['ma20'], linewidth = 0.5 ) plt.plot( xx, df['ma30'], linewidth = 0.5 ) plt.plot( xx, df['ma40'], linewidth = 0.5 ) plt.plot( xx, df['ma60'], linewidth = 0.5 ) plt.plot( xx, df['ma89'], linewidth = 0.5 ) plt.plot( xx, df['ma144'], linewidth = 0.5 ) plt.plot( xx, df['ma233'], linewidth = 0.5 ) plt.plot( xx, df['ma377'], linewidth = 0.5 ) plt.plot( xx, df['ma610'], linewidth = 0.5 ) """ # ax.grid(True) # --------------------------------------------(子图表2) plt.sca(ax2) # plt.plot( xx[len(xx)-500:len(xx)], df['j1'].tail(500), linewidth = 0.5 ) plt.plot(xx, df['j1'], linewidth=0.5) plt.plot(xx, df['e1'], linewidth=0.5) plt.plot(xx, df['j2'], linewidth=0.5) plt.plot(xx, df['e2'], linewidth=0.5) plt.plot(xx, df['j3'], linewidth=0.5) plt.plot(xx, df['e3'], linewidth=0.5) plt.plot(xx, df['j4'], linewidth=0.5) plt.plot(xx, df['e4'], linewidth=0.5) plt.sca(ax3) plt.plot(xx, df['x1'], linewidth=0.5) plt.plot(xx, df['x2'] * 7, linewidth=0.5) plt.plot(xx, df['x3'] * 30, linewidth=0.5) plt.plot(xx, df['x4'] * 80, linewidth=0.5) plt.sca(ax4) plt.plot(xx, df['gain'], linewidth=0.5) plt.show()
def plot_incidence(self, X, Y): # Create plot fig, ax = plt.subplots() # Rotate datetimes plt.setp(ax.get_xticklabels(), rotation=90, ha='right') # plt.rc('xtick', labelsize=SMALL_SIZE) ax.xaxis.set_major_locator(DayLocator(interval=1)) ax.xaxis.set_major_formatter(DateFormatter('%d/%m')) ax.set_xlim([X[0], X[-1]]) ax.set_ylim(XLIMIT, YLIMIT) # Set risk masks Yl = np.ma.masked_inside(Y, 50, 5000) Ym = np.ma.masked_inside(Y, 0, 50) Yh = np.ma.masked_inside(Y, 0, 150) Ye = np.ma.masked_inside(Y, 0, 250) # Add data ax.bar(X, Yl, color=mcolors.CSS4_COLORS['green'], linewidth=1.8, label='Risc baix (IA14 inferior a 50)', align='center') ax.bar(X, Ym, color=mcolors.CSS4_COLORS['darkorange'], linewidth=1.8, label='Risc mitjà (IA14 entre 50 i 150)', align='center') ax.bar(X, Yh, color=mcolors.CSS4_COLORS['red'], linewidth=1.8, label='Risc alt (IA14 entre 150 i 250)', align='center') ax.bar(X, Ye, color=mcolors.CSS4_COLORS['darkred'], linewidth=1.8, label='Risc extrem (IA14 superior a 250)', align='center') # Turn region name into bold string bold = self.bold(self.region) # Labels ax.set_title(bold + ': Incidència acumulada en els últims 14 dies') ax.set_xlabel('Data') ax.set_ylabel('IA14') ax.legend(loc='upper left', framealpha=0.5) plt.figtext(0.03, 0, "Font: Dades Obertes de la Generalitat de Catalunya", ha="left", fontsize=7) plt.figtext(0.72, 0, "Bot de Telegram: t.me/CatalunyaCOVID19bot", ha="left", fontsize=7) # Use tight layout fig.tight_layout() # Save self.file_path = INCIDENCE_PATH + self.region + '.png' plt.savefig(self.file_path, dpi=DPI, bbox_inches='tight') plt.close()
for legobj in leg.legendHandles: legobj.set_linewidth(2.0) plt.ylabel(Ylabel) if LocatorInterval == 'multi_year': ax2.xaxis.set_major_locator(YearLocator()) ax2.xaxis.set_minor_locator(MonthLocator(bymonth=6)) ax2.xaxis.set_major_formatter(ticker.NullFormatter()) ax2.xaxis.set_minor_formatter(DateFormatter('%Y')) ax2.tick_params(axis='both', which='minor', labelsize=12) elif LocatorInterval == 'multi_day': ax2.xaxis.set_major_locator( MonthLocator(bymonth=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], bymonthday=15)) ax2.xaxis.set_minor_locator( DayLocator(bymonthday=[0, 5, 10, 15, 20, 25, 30])) ax2.xaxis.set_major_formatter(DateFormatter('%b')) ax2.xaxis.set_minor_formatter(DateFormatter('%d')) ax2.yaxis.set_minor_locator(ticker.MultipleLocator(1)) ax2.tick_params(axis='both', which='minor', labelsize=12) ax2.grid(which='both', color='k', linestyle='--', linewidth=0.25) elif LocatorInterval == 'multi_month': ax2.xaxis.set_major_locator(MonthLocator()) ax2.xaxis.set_minor_locator( MonthLocator(bymonth=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], bymonthday=15)) ax2.xaxis.set_major_formatter(ticker.NullFormatter()) ax2.xaxis.set_minor_formatter(DateFormatter('%b')) ax2.tick_params(axis='both', which='minor', labelsize=12) else: ax2.xaxis.set_major_locator(MonthLocator())
ssec2015 = ssec2015.iloc[:, 1:] ssec2015.head(n=3) ssec2015.iloc[-3:, :] ssec2015.Date=[date2num(datetime.strptime(date,"%Y-%m-%d"))\ for date in ssec2015.Date] type(ssec2015) ssec15list = list() for i in range(len(ssec2015)): ssec15list.append(ssec2015.iloc[i, :]) ax = plt.subplot() mondays = WeekdayLocator(MONDAY) weekFormatter = DateFormatter('%y %b %d') ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(DayLocator()) ax.xaxis.set_major_formatter(weekFormatter) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False ax.set_title("上证综指2015年3月份K线图") candlestick_ohlc(ax, ssec15list, width=0.7, colorup='r', colordown='g') plt.setp(plt.gca().get_xticklabels(), rotation=50, horizontalalignment='center') plt.show() #morning star ssec2012 = pd.read_csv('ssec2012.csv') ssec2012.index = ssec2012.iloc[:, 1] ssec2012.index = pd.to_datetime(ssec2012.index, format='%Y-%m-%d') ssec2012 = ssec2012.iloc[:, 2:]
def pandas_candlestick_ohlc(dat, stick="day", otherseries=None): """ :param dat: pandas DataFrame object with datetime64 index, and float columns "open", "high", "low", and "close" :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default) :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines """ mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator( ) # Make ticks on occurrences of each day of the month,minor ticks dayFormatter = DateFormatter('%d') # e.g., 12 transdat = dat.loc[:, ["open", "high", "low", "close"]] if (type(stick) == str): if stick == "day": plotdat = transdat stick = 1 # Used for plotting, defaul to 1 for day-plot elif stick in ["week", "month", "year"]: if stick == "week": transdat["week"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[1]) # Identify weeks elif stick == "month": transdat["month"] = pd.to_datetime(transdat.index).map( lambda x: x.month) # Identify months transdat["year"] = pd.to_datetime(transdat.index).map( lambda x: x.isocalendar()[0]) # Identify years grouped = transdat.groupby(list(set( ["year", stick]))) # Group by year and other appropriate variable plotdat = pd.DataFrame({ "open": [], "high": [], "low": [], "close": [] }) # Create empty data frame containing what will be plotted for name, group in grouped: plotdat = plotdat.append( pd.DataFrame( { "open": group.iloc[0, 0], "high": max(group.high), "low": min(group.low), "close": group.iloc[-1, 3] }, index=[group.index[0]])) if stick == "week": stick = 5 elif stick == "month": stick = 30 elif stick == "year": stick = 365 else: raise ValueError( 'Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer' ) # Set plot parameters, including the axis object ax used for plotting fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('365 days'): weekFormatter = DateFormatter('%b %d, %Y') # e.g., Jan 12,2007 ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) else: weekFormatter = DateFormatter('%b %d, %Y') ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xasix.set_major_formatter(weekFormatter) ax.grid(True) # Create the candelstick chart candlestick_ohlc(ax, list( zip(list(date2num(plotdat.index.tolist())), plotdat["open"].tolist(), plotdat["high"].tolist(), plotdat["low"].tolist(), plotdat["close"].tolist())), colorup="red", colordown="green", width=stick * .4) # Plot other series (such as moving averages) as lines if otherseries != None: if type(otherseries) != list: otherseries = [otherseries] dat.loc[:, otherseries].plot(ax=ax, lw=1.3, grid=True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show() return fig