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_contrast(self,moneyrecord1,moneyrecord2,date_ls,startdate,enddate): startdate=self.datetransfer(startdate) date_ls_change=[] for i in date_ls: if int(i)>=int(startdate) and int(i)<=int(enddate): date_ls_change.append(i) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") print(date_ls_change) #print(date_ls) date = [str(e) for e in date_ls_change] date_ls = [datetime.datetime.strptime(d,'%Y%m%d').date() for d in date] algo_pv=moneyrecord1['money'].tolist() print(algo_pv) bench_pv=moneyrecord2['moneybenchmark'].tolist() fig, ax = plt.subplots() plt.gca().set_color_cycle(['blue', 'red']) ax.plot_date(date_ls, algo_pv,'-') ax.plot_date(date_ls, bench_pv,'-') months.MAXTICKS=5000 mondays.MAXTICKS=5000 ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() plt.title('P&L') plt.legend(['strategy', 'benchmark'], loc='upper left') plt.show()
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 plot_alpha(self,alpha,date_ls,startdate,enddate): startdate=self.datetransfer(startdate) date_ls_change=[] for i in date_ls: if int(i)>=int(startdate) and int(i)<=int(enddate): date_ls_change.append(i) mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") #print(date_ls) date = [str(e) for e in date_ls_change] date_ls = [datetime.datetime.strptime(d,'%Y%m%d').date() for d in date] algo_pv=alpha['alpha'].tolist() #print(algo_pv) fig, ax = plt.subplots() plt.gca().set_color_cycle(['blue', 'red']) ax.plot_date(date_ls, algo_pv,'-') months.MAXTICKS=5000 mondays.MAXTICKS=5000 ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() plt.title('Alpha') plt.legend(['alpha'], loc='upper left') plt.show() #KJ_profit_df=pd.DataFrame(columns=[i/10 for i in range(1,121)]) #for K in list_K: #for J in list_J: #KJ=B(cash,account,startdate,enddate,K,J) #KJ_total_portfolio=KJ.test(startdate,enddate,K,J,cash) #KJ_profit_df.loc[10*J-1,K]=KJ_total_portfolio #KJ_profit_df.to_csv('KJ_finalprofit.csv')
data = sbi.copy() data.columns data.dtypes data.head() data.index data[['Open', 'High', 'Low', 'Close']] data[['Open', 'High', 'Low', 'Close', 'WAP']].plot() data[['Open', 'Close']].plot() #%%% #Libraries #pip install mpl_finance from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates import matplotlib.pyplot as plt from matplotlib.dates import MONDAY, DateFormatter, DayLocator, WeekdayLocator 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 #prepare OHLC sbi.head() data3 = sbi[['Open', 'High', 'Low', 'Close']].copy() data3.head() date1 = "2019-8-1" date2 = "2019-8-30" data3b = data3[(data3.index >= date1) & (data3.index <= date2)] data3b #%%% Plots #run together till plt.show fig, ax = plt.subplots(figsize=(10, 8))
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(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()
value + 0.5 * rect.get_height(), "{} - {:.2%}".format( int(width), float(width) / float(session_with_command)), ha='center', va='bottom') print("plotting") fig, ax = plt.subplots() ax.plot(dates_x, y, linestyle='None', marker='o') # every monday mondays = WeekdayLocator(MONDAY) months = MonthLocator(range(1, 13), bymonthday=1) days = DayLocator(interval=1) monthsFmt = DateFormatter("%d %b '%y") daysFmt = DateFormatter("%d/%m/%y") ax.xaxis.set_major_locator(mondays) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(days) ax.autoscale_view() fig.autofmt_xdate() ax.set_title( "Repartition of the credentials used during a telnet sessions over time (filtered: <" + str(thres_om) + ")") ax.yaxis.grid(True, which='both')
import datetime from pylab import * from matplotlib.dates import MONDAY, SATURDAY from matplotlib.finance import quotes_historical_yahoo from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter from matplotlib.ticker import FormatStrFormatter # the start and end date range for the financial plots date1 = datetime.date(2003, 1, 1) date2 = datetime.date(2004, 4, 12) # the tick locators and formatters mondays = WeekdayLocator(MONDAY) # every monday months = MonthLocator() # every month monthsFmt = DateFormatter('%b %d') # looks like May 01 dollarFmt = FormatStrFormatter('$%0.2f') # dollars! # get some financial data from the finance module quotes = quotes_historical_yahoo('INTC', date1, date2) if not quotes: raise SystemExit # failsafe # extract the date and opening prices from the quote tuples dates = [q[0] for q in quotes] opens = [q[1] for q in quotes] # plot_date will choose a default date ticker and formatter ax = subplot(111) plot_date(dates, opens, markeredgecolor='k') # but we'll override the default with our custom locators and # formatters
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 drawgraph(shcode, startdate=0, period=0, discover=None, pearson=None): # 1st parameter, shcode is stock code. # e.g., shcode = "000020" #동화약품(000020) # 2nd parameter, startdate is an index of DB data. # 3rd parameter, period is a number of DB data from startdate. default 0 means all period. # Fetch rows = shquery.getstockprice(shcode) # exception of function if len(rows) - 1 < startdate + period: return -1 # create List type array marketdate, openprice, closeprice, highprice, lowprice = [], [], [], [], [] for row in rows: marketdate.append(dates.date2num(row['marketdate'])) openprice.append(int(row['openprice'])) closeprice.append(int(row['closeprice'])) highprice.append(int(row['highprice'])) lowprice.append(int(row['lowprice'])) j = period if period != 0 else len(rows) - 1 - startdate # set period # create DataFrame k = startdate graph = { 'marketdate': marketdate[k:k + j], 'openprice': openprice[k:k + j], 'closeprice': closeprice[k:k + j], 'highprice': highprice[k:k + j], 'lowprice': lowprice[k:k + j] } graph = DataFrame(graph) quotes = zip(graph['marketdate'], graph['openprice'], graph['highprice'], graph['lowprice'], graph['closeprice']) # print(graph) # Graph Drawing mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d, %Y') # e.g., Jan 12, 2014 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_date() ax.autoscale_view() ax.grid(True) # print(graph['marketdate'][396]) if discover is not None: if len(discover) != len(pearson): return -1 j = -1 for i in discover: j += 1 ymin, ymax = graph['highprice'][i], graph['lowprice'][ i] # initialize for n in range(i, i + 30): ymin = min(ymin, graph['lowprice'][n]) # min value ymax = max(ymax, graph['highprice'][n]) # max value ax.set_title("Stock Code: " + shcode) # set graph title ax.text( graph['marketdate'][i], ymax, str(float("{0:.2f}".format(pearson[j] * 100))) + "%", fontsize=8 ) # print similarity percent (limiting floats to four decimal points) if i + (30 * 2) < len(rows) - 1: earning = ((int(graph['closeprice'][i + 50]) - int(graph['closeprice'][i + 30])) / int(graph['closeprice'][i + 30]) ) * 100 # calculate earning ratio earning = round(earning, 2) ax.text(graph['marketdate'][i + 50], graph['highprice'][i + 50] + 250, str(earning) + "%", color='green', fontsize=8) # print earning ratio # Draw Rectangle # ax.text(graph['marketdate'][i], ymax - ymin, str(pearson[j])+"%") # print earning ratio ax.add_patch( patches.Rectangle( (graph['marketdate'][i], ymin), # (x,y) graph['marketdate'][i + 30] - graph['marketdate'][i], # width ymax - ymin, # height fill=False, # remove background linewidth=1)) candlestick_ohlc(ax, quotes, colorup="red", colordown="blue", width=0.6) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right', size=10) # Save graph filename = datetime.today().strftime("%Y%m%d_") + str(shcode) + "_" + str( startdate) + "_" + str( period) + "_" + "temp.png" # e.g., 19931004_000020_0_0_temp.png filepath = "temp/" + filename if not os.path.isfile(filepath): plt.savefig(filepath, format='png') print("검색결과를 다음의 경로로 저장합니다. ", filename) else: print("기존의 검색결과가 존재하므로, 저장하지 않습니다. ", filename) plt.show() # End of function return filename
def visualize(self, elements="C,CL,LMK,PV,PVL,ODR", ylimits=None): """ elements: elements that should be plotted, see below. ylimits: range of y axis. e.g. (0, 100) { # element and its dependent columns # Basic "C" : ["Close",], # Mark the tick['Close'] value with point. "CL" : ["Close",], # Mark the tick['Close'] value as a line. "HLC" : ["High", "Low", "Close"], # Plot the HLC values in the tick. # Derived "ODR" : ["Open", "High", "Low", "Close", "Volume"], # One Day Reversal. Mark the ODR ticks. "PV" : ["Close", "Top", "Btm"], # Label the pivot point value. "PVL" : ["Close", "Top", "Btm"], # Plot a Line that connects the pivot points. "EE" : ["Buy", "Sell"], # Mark the idea Buy/Sell point. "BAND" : ["Band", "WM"], # Mark the point with its current LMK Band Level. "BANDL" : ["Band", "Buy", "Sell"], # Mark line segment according to its current band level. "WM" : ["Trend", "WM"], # Mark the current resistant or support line } """ h = self.history # -------------------------------------------------------------- # ---- Background and Limits ---- ax0 = plt.subplot2grid((5, 1), (0, 0), rowspan=4) ax0.set_xmargin(0.02) #http://stackoverflow.com/questions/3305865/what-is-the-difference-between-log-and-symlog #ax0.set_yscale("symlog", linthreshy=30) ax1 = plt.subplot2grid((5, 1), (4, 0), rowspan=1, sharex=ax0) ax1.yaxis.set_visible(False) #ax1.set_yscale("symlog", linthreshy=1000) self.figure = plt.gcf() #self.figure.clear() self.figure.suptitle("%s%s" % (self.symbol, "" if self.symbol == self.name else ("(%s)" % self.name))) self.figure.subplots_adjust(hspace=0) if ylimits is not None: ax0.set_ylim(*ylimits) else: close_min = min(h["Close"]) close_max = max(h["Close"]) height = close_min * .5 ymin = close_min * 0.98 ymax = close_min + (height * 1.02) if ymax < close_max: height = close_max - close_min ymax = close_min + height * 1.02 ax0.set_ylim(ymin, ymax) ax0.set_axis_bgcolor('white') ax1.set_axis_bgcolor('white') # -------------------------------------------------------------- # http://stackoverflow.com/questions/1166118/how-to-strip-decorators-from-a-function-in-python def plot_elements(*names): def decorated(f): @functools.wraps(f) def wrapper(*argv, **kargs): return f(*argv, **kargs) wrapper.elements = names return wrapper return decorated def columns(*names): def decorated(f): @functools.wraps(f) def wrapper(*argv, **kargs): h = argv[1] ensure_columns_exist(h, names) return f(*argv, **kargs) return wrapper return decorated # -- Basic Volume/Price -- @plot_elements("V") @columns("CC", "Volume") def plot_V(ax, h): up = h[h["CC"] >= 0] ax.bar(up.index, up["Volume"], width=1, color="black", edgecolor="black", linewidth=1, alpha=.3, align="center") dn = h[h["CC"] < 0] ax.bar(dn.index, dn["Volume"], width=1, color="red", edgecolor="red", linewidth=1, alpha=.3, align="center") @plot_elements("C") @columns("Close", "CC") def plot_C(ax, h): up = h[h["CC"] >= 0] ax.plot(up.index, up["Close"], "_", color="black", alpha=.5, markeredgewidth=2) dn = h[h["CC"] < 0] ax0.plot(dn.index, dn["Close"], "_", color="red", alpha=.5, markeredgewidth=2) @plot_elements("CL") @columns("Close") def plot_CL(ax, h): ax.plot(h.index, h["Close"], "-", color="black", alpha=0.5) @plot_elements("HLC") @columns("High", "Low", "Close", "CC") def plot_HLC(ax, h): up = h[h["CC"] >= 0] ax.plot(up.index, up["Close"], "_", color="black", alpha=1, markeredgewidth=1) up = h[h["Close"] >= h["Open"]] ax.vlines(up.index, up["Low"], up["High"], color="black", edgecolor="black", alpha=1, linewidth=1) dn = h[h["CC"] < 0] ax.plot(dn.index, dn["Close"], "_", color="red", alpha=1, markeredgewidth=1) dn = h[h["Close"] < h["Open"]] ax.vlines(dn.index, dn["Low"], dn["High"], color="red", edgecolor="red", alpha=1, linewidth=1) # -- ODR -- @plot_elements("ODR") @columns("ODR", "Close") def plot_ODR(ax, h): r = h[h["ODR"]] ax.plot(r.index, r["Close"], "rx", markersize=8, markeredgewidth=3, alpha=1) # -- Pivots -- @plot_elements("PV") @columns("Top", "Btm", "Close", "Low", "High") def plot_PV(ax, h): pivots = h[h["Top"] | h["Btm"]] for x, tick in pivots.iterrows(): label = "%.2f" % tick["Close"] if tick["Top"]: # crest y = tick["High"] ax.text(x, y, label, color="g", alpha=.8) else: # trough y = tick["Low"] ax.text(x, y, label, color="r", alpha=.8) @plot_elements("PVL") @columns("Top", "Btm", "Close") def plot_PVL(ax, h): pivots = h[h["Top"] | h["Btm"]] ax.plot(pivots.index, pivots["Close"], "-", color="blue", alpha=.3) r = h[h["Top"]] ax.plot(r.index, r["Close"], "g^", alpha=1.0) r = h[h["Btm"]] ax.plot(r.index, r["Close"], "rv", alpha=1.0) # -- LMK -- BAND_STYLE_MAP = { BAND_DNWARD: "rv", BAND_NAT_REACT: "m<", BAND_SEC_REACT: "m*", BAND_SEC_RALLY: "c*", BAND_NAT_RALLY: "c>", BAND_UPWARD: "g^", } @plot_elements("BAND", "LMK") @columns("Close", "WM", "Band") def plot_BAND(ax, h): for band in range(BAND_DNWARD, BAND_UPWARD + 1): #if band in (BAND_SEC_REACT, BAND_SEC_RALLY): continue r = h[(h["WM"] == h["Close"]) & (h["Band"] == band)] ax0.plot(r.index, r["Close"], BAND_STYLE_MAP[band], alpha=1.0) @plot_elements("BANDL") @columns("Band", "Buy", "Sell", "Close") def plot_BANDL(ax, h): chosen = ma.masked_where(~(h["Band"] >= BAND_NAT_RALLY), h["Close"]) if chosen.any(): ax.plot(h.index, chosen, "g-", linewidth=1, alpha=1) chosen = ma.masked_where(~(h["Band"] <= BAND_NAT_REACT), h["Close"]) if chosen.any(): ax.plot(h.index, chosen, "r-", linewidth=1, alpha=1) @plot_elements("WM") @columns("Trend", "WM", "ATR") def plot_WM(ax, h): chosen = ma.masked_where(~(h['Trend'] == TREND_UP), h["WM"]) ax.plot(h.index, chosen, drawstyle="steps-post", color="g", linewidth=1.5) chosen = ma.masked_where(~(h['Trend'] == TREND_UP), h["WM"] - h["ATR"] * 2.0) ax.plot(h.index, chosen, drawstyle="steps-post", color="r", alpha=.5) chosen = ma.masked_where(~(h['Trend'] == TREND_UP), h["WM"] - h["ATR"]) ax.plot(h.index, chosen, drawstyle="steps-post", color="b", alpha=.2) chosen = ma.masked_where(~(h['Trend'] == TREND_DN), h["WM"]) ax.plot(h.index, chosen, drawstyle="steps-post", color="r", linewidth=1.5) chosen = ma.masked_where(~(h['Trend'] == TREND_DN), h["WM"] + h["ATR"] * 2.0) ax.plot(h.index, chosen, drawstyle="steps-post", color="g", alpha=.5) chosen = ma.masked_where(~(h['Trend'] == TREND_DN), h["WM"] + h["ATR"]) ax.plot(h.index, chosen, drawstyle="steps-post", color="b", alpha=.2) @plot_elements("EE", "BS") @columns("Buy", "Sell", "Close") def plot_EE(ax, h): r = h[h["Buy"]] ax0.plot(r.index, r["Close"], "g+", markersize=8, markeredgewidth=3, alpha=1) r = h[h["Sell"]] ax0.plot(r.index, r["Close"], "r_", markersize=8, markeredgewidth=3, alpha=1) # Build the plotting function map ... plot_functions = [ f for f in locals().values() if callable(f) and hasattr(f, "elements") ] plot_dict = {} for f in plot_functions: for element in f.elements: plot_dict[element] = f # do the real plotting ... l = re.split("[-:,;.]", elements) for c in l: _plot = plot_dict[c] if c != "V": _plot(ax0, h) else: _plot(ax1, h) # -------------------------------------------------------------- # ---- Axis and Grid ---- days = WeekdayLocator(MONDAY) #days = WeekdayLocator(FRIDAY) #dayFmt = DateFormatter("%d") def _dayFmt(x, pos): dt = num2date(x) return dt.strftime("%d")[-1] if dt.day < 10 else dt.strftime("%d") dayFmt = FuncFormatter(_dayFmt) months = MonthLocator(range(1, 13), bymonthday=1, interval=1) # http://stackoverflow.com/questions/11623498/date-formatting-with-matplotlib def _monthFmt(x, pos): dt = num2date(x) return dt.strftime('\n%Y') if dt.month == 1 else dt.strftime( "\n%b") monthFmt = FuncFormatter(_monthFmt) for ax in (ax0, ax1): ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthFmt) plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, color="blue") if len(ax.get_xticks()) <= 12: ax.xaxis.set_minor_locator(days) ax.xaxis.set_minor_formatter(dayFmt) ax0.xaxis.grid(True, which='major', color="blue", linestyle="-", alpha=1) ax0.xaxis.grid(True, which='minor', color="gray", linestyle="-", alpha=.5) ax0.tick_params(labelbottom="off", which="both") ax0.yaxis.grid(True) ax1.xaxis.grid(True, which='major', color="blue", linestyle="-", alpha=1) ax1.xaxis.grid(True, which='minor', color="gray", linestyle="-", alpha=.3) # http://stackoverflow.com/questions/12750355/python-matplotlib-figure-title-overlaps-axes-label-when-using-twiny #ax0.set_title("%s%s" % (self.symbol, "" if self.symbol == self.name else ("(%s)" % self.name)), y=0.9) plt.show()
t = [] for single_date in daterange(start_date, end_date): times.append(PT.getTimes(single_date.timetuple(), cnf_city_coord, cnf_tz)) t.append(single_date.toordinal()) fajr = [time2minutes(x['fajr']) for x in times] sunrise = [time2minutes(x['sunrise']) for x in times] dhuhr = [time2minutes(x['dhuhr']) for x in times] asr = [time2minutes(x['asr']) for x in times] maghrib = [time2minutes(x['maghrib']) for x in times] isha = [time2minutes(x['isha']) for x in times] # Date Locators everyday = DayLocator(interval=1) fridays = WeekdayLocator(FRIDAY) months = MonthLocator(range(1, 13), bymonthday=1, interval=1) # every month monthsFmt = DateFormatter("%b '%y") daysFmt = DateFormatter("%d %b") fig, ax = plt.subplots() plt.plot(t,fajr, 'k',t,sunrise, 'k',t,dhuhr, 'k',t,asr, 'k',t,maghrib, 'k',t,isha, 'k') ax.xaxis.set_major_locator(fridays) ax.xaxis.set_major_formatter(daysFmt) ax.xaxis.set_minor_locator(everyday) ax.xaxis_date() ax.autoscale_view() ax.xaxis.grid(True, 'major') ax.xaxis.grid(False, 'minor') ax.set_title('Annual Prayer Times for '+cnf_city_name+', '+str(cnf_year)) #fig.autofmt_xdate() #Autorotate labels
def _xAxis(self, ax): # X-axis labels # Don't create ticks when the x-axis range is too big. Likely this is because of # a problem with the input data. Some versions of python crash when trying to # create too many ticks range = mpl.xlim() if (range[1] - range[0] < 100): if (self.shortRange): mpl.gca().xaxis.set_major_locator(DayLocator(interval=1)) mpl.gca().xaxis.set_minor_locator(HourLocator(interval=6)) mpl.gca().xaxis.set_major_formatter( DateFormatter('\n %a %d %b %Y')) mpl.gca().xaxis.set_minor_formatter(DateFormatter('%H')) else: mpl.gca().xaxis.set_major_locator( WeekdayLocator(byweekday=(MO, TU, WE, TH, FR))) mpl.gca().xaxis.set_major_formatter( DateFormatter('\n%Y-%m-%d')) mpl.gca().xaxis.set_minor_locator( WeekdayLocator(byweekday=(SA, SU))) mpl.gca().xaxis.set_minor_formatter( DateFormatter('\n%Y-%m-%d')) mpl.xticks(rotation=90) if (self.showX): mpl.xlabel('Date', fontsize=self.labelFs) majlabels = [tick.label1 for tick in mpl.gca().xaxis.get_major_ticks()] for i in majlabels: # Don't show the last label, since it will be outside the range if (i == majlabels[len(majlabels) - 1]): i.set_visible(0) if (not self.showX): i.set_visible(0) else: if (self.shortRange): i.set_horizontalalignment('left') i.set_position((0, -0.035)) else: i.set_horizontalalignment('right') i.set_rotation(30) i.set_verticalalignment('top') i.set_fontsize(self.fs) i.set_position((0, -0.035)) minlabels = [tick.label1 for tick in mpl.gca().xaxis.get_minor_ticks()] for i in minlabels: if (not self.showX): i.set_visible(0) else: if (self.shortRange): i.set_horizontalalignment('center') i.set_rotation(0) i.set_color("k") else: i.set_horizontalalignment('right') i.set_rotation(30) i.set_color((1, 0, 1)) # Weekend days are magenta i.set_verticalalignment('top') i.set_fontsize(self.fs) ylabels = [tick.label1 for tick in mpl.gca().yaxis.get_major_ticks()] for i in ylabels: i.set_fontsize(self.fs) # Gridlines mpl.gca().xaxis.grid(True, which='major', color='k', zorder=-10, linestyle='-') if (self.shortRange): mpl.gca().xaxis.grid(True, which='minor', color='k', zorder=0, linestyle=':') else: mpl.gca().xaxis.grid(True, which='minor', color=(1, 0, 1), zorder=0, linestyle='-') minOffset = min(self.file.getOffsets()) maxOffset = max(self.file.getOffsets()) if (not np.isnan(self.maxOffset)): maxOffset = minOffset + self.maxOffset / 24.0 mpl.xlim(minOffset, maxOffset)
def plot_covid( loc, cat, cty_state, wknd="skip weekends", start="2020-03-02", end=str(dt.date.today()), in_fn=f"DL-us-mobility.ndjson", out_fn=f"DL_mobility-index_{str(dt.date.today())}", ): """ Parameters ---------- loc : list a list of strings with names of counties, states, or both. default is a list containing: California, Texas, New York, Illinois, Washington, Florida. cat : list categorizes loc as states, counties, both, or rank; "rank" specifies to rank top ten counties within a state or states. default is state. cty_state : str or list a string or list of strings with the state that corresponds to counties if that is what is specified in loc wknd : bool if weekends, include weekend dates; if skip_weekends, only include weekdays. default is False. start : str starting date for plot. optional. end: str ending date for plot. optional. in_fn: str input filename for plotting. optional. out_fn: str output filename for figure. default is "DL_mobility-index_{today}.png. optional. Returns ------- plot of mobility indices for specified locations and dates """ # organize data data = {} states = [] if (cat == "county" or cat == "both") and cty_state == None: print( "Please specify states for your county or counties to ensure you're getting the expected data." ) for line in open(in_fn): d = json.loads(line) for aoi in loc: aoi = aoi.title() # state or default for county / both for if county states aren't specified if (cat == "state" or (cat == "county" and cty_state == None) or (cat == "both" and cty_state == None)): if (aoi in d["admin1"] and d["admin_level"] == 1) or ( aoi in d["admin2"] and d["admin_level"] == 2): states.append(d["admin1"]) data[aoi] = {} data[aoi]["dates"] = d["date"] data[aoi]["m50"] = d["m50_index"] data[aoi]["samples"] = d["samples"] # counties all from the same state if (cat == "county" or cat == "both") and len(cty_state) == 1: state = cty_state[0].title() if (aoi in d["admin2"] or aoi in d["admin1"]) and state in d["admin1"]: states.append(d["admin1"]) data[aoi] = {} data[aoi]["dates"] = d["date"] data[aoi]["m50"] = d["m50_index"] data[aoi]["samples"] = d["samples"] # counties from different states if (cat == "county" or cat == "both") and len(cty_state) > 1: for cty_st in cty_state: if loc.index(aoi.lower()) == cty_state.index(cty_st): state = cty_st.title() if aoi.title() in d["admin2"] and state in d["admin1"]: states.append(d["admin1"]) data[aoi] = {} data[aoi]["dates"] = d["date"] data[aoi]["m50"] = d["m50_index"] data[aoi]["samples"] = d["samples"] data[aoi]["state"] = d["admin1"] # counties ranked for a specific state if cat == "rank": if aoi in d["admin1"] and d["admin_level"] == 2: data[d["admin2"]] = {} data[d["admin2"]]["dates"] = d["date"] data[d["admin2"]]["m50"] = d["m50_index"] data[d["admin2"]]["samples"] = d["samples"] # prepare for plotting orddata = OrderedDict( sorted(data.items(), key=lambda x: getitem(x[1], "samples"))) if cat == "rank": items = list(orddata.items())[-10:] else: items = list(orddata.items()) mindex = {"x": [], "y": [], "label": []} for item in items: aoi = {"x": [], "y": []} for n in range(len(item[1]["dates"])): date = item[1]["dates"][n] m50 = item[1]["m50"][n] day = dt.date(int(date[:4]), int(date[5:7]), int(date[8:10])).weekday() if not wknd and (day == 5 or day == 6): continue if not wknd and (day != 5 or day != 6): aoi["x"].append([dt.datetime.strptime(date, "%Y-%m-%d")]) aoi["y"].append(m50) if wknd: aoi["x"].append([dt.datetime.strptime(date, "%Y-%m-%d")]) aoi["y"].append(m50) mindex["x"].append(aoi["x"]) mindex["y"].append(aoi["y"]) mindex["label"].append(item[0]) # plot data plt.rcParams["font.family"] = "sans-serif" plt.rcParams["font.sans-serif"] = ["Source Sans Pro"] fig, ax = plt.subplots(figsize=(8, 6)) filled_markers = ["v", "^", "<", ">", "8", "s", "p"] for i in range(len(mindex["label"])): if i <= 8: plt.plot(mindex["x"][i], mindex["y"][i], marker="o", label=mindex["label"][i]) if i > 8: plt.plot( mindex["x"][i], mindex["y"][i], marker=filled_markers[i % 7], label=mindex["label"][i], ) ax.set_ylabel("Mobility Index", fontsize=12) ax.set_ylim(0, 200) ax.set_xlim(dt.datetime.strptime(start, "%Y-%m-%d"), dt.datetime.strptime(end, "%Y-%m-%d")) plt.setp(ax.get_xticklabels(), rotation=50) plt.grid(axis="y") ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO)) ax.xaxis.set_major_formatter(DateFormatter("%b %d")) logo = plt.imread(dl_logo64) if len(loc) <= 5 and cat != "rank": ax.legend( loc="upper center", fontsize=11, bbox_to_anchor=(0.75, -0.16), ncol=2, frameon=False, ) ax.figure.figimage(logo, 200, 100, alpha=1.0, zorder=1) plt.figtext( 0.08, -0.15, "CC BY 4.0 descarteslabs.com/mobility", ha="left", va="bottom", alpha=0.5, fontsize=8, ) if len(loc) > 5 and len(loc) <= 12 or cat == "rank": ax.legend( loc="upper center", fontsize=11, bbox_to_anchor=(0.75, -0.16), ncol=2, frameon=False, ) ax.figure.figimage(logo, 200, 100, alpha=1.0, zorder=1) plt.figtext( 0.08, -0.05, "CC BY 4.0 descarteslabs.com/mobility", ha="left", va="bottom", alpha=0.5, fontsize=8, ) if len(loc) > 12: ax.legend( loc="upper center", fontsize=11, bbox_to_anchor=(0.75, -0.16), ncol=3, frameon=False, ) ax.figure.figimage(logo, 130, 130, alpha=1.0, zorder=1) plt.figtext( 0.08, -0.05, "CC BY 4.0 descarteslabs.com/mobility", ha="left", va="bottom", alpha=0.5, fontsize=8, ) plt.subplots_adjust(bottom=0.7) fig.tight_layout() # format titles based on user input if cat == "state": plt.title("United States") if cat == "county" or cat == "both": if len(set(states)) == 1: plt.title(states[0] + " Counties") if len(set(states)) != 1: plt.title("United States: Counties") if cat == "rank" and len(loc) == 1: plt.title(loc[0].title()) if cat == "rank" and len(loc) > 1: plt.title("United States county comparisons") if cat == "both" and len(set(states)) != 1: plt.title("United States + Counties") # plot and save figure plt.draw() fig.savefig("{}.png".format(out_fn), bbox_inches="tight", pad_inches=0.1, dpi=200)
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; # 如 果 无 参 数 splitFigures , 则 只 画 一 个 图 形 框 # 如 果 有 参 数 splitFigures , 则 画 出 两 个 图 形 框 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') 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())