Beispiel #1
0
    def bounding_box(self, data, ax, label, bBoundingBoxes, bLabels):
        """Draw bounding box around data."""

        data = np.array(data)

        width = max(data[:, 0]) - min(data[:, 0])
        height = max(data[:, 1]) - min(data[:, 1])
        r = Rectangle((min(data[:, 0]), min(data[:, 1])), width, height)

        if bBoundingBoxes:
            ax.add_artist(r)
            r.set_clip_box(ax.bbox)
            r.set_alpha(0.1)
            r.set_facecolor((0.5, 0.5, 0.5))

        if bLabels:
            ax.annotate(label,
                        xy=(min(data[:, 0]), max(data[:, 1])),
                        xytext=(0, 0),
                        textcoords='offset points',
                        ha='right',
                        va='bottom',
                        bbox=dict(boxstyle='round,pad=0.5',
                                  fc=(0.5, 0.5, 0.5),
                                  alpha=0.1))
Beispiel #2
0
Datei: stlib.py Projekt: yhyan/jq
def candlestick(ax, quotes, width=0.2, colorup="k", colordown="r", alpha=1.0):

    OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        t, open, close, high, low = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(xdata=(t, t), ydata=(low, high), color=color, linewidth=0.5, antialiased=True)

        rect = Rectangle(xy=(t - OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color)
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
Beispiel #3
0
def fooCandlestick(ax, quotes, width=0.029, colorup='#FFA500', colordown='#222', alpha=1.0):
	OFFSET = width/2.0
	lines = []
	boxes = []

	for q in quotes:

		timestamp, op, hi, lo, close = q[:5]
		box_h = max(op, close)
		box_l = min(op, close)
		height = box_h - box_l

		if close>=op:
			color = '#3fd624'
		else:
			color = '#e83e2c'

		vline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
		vline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
		rect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10)
		rect.set_alpha(alpha)
		lines.append(vline_lo)
		lines.append(vline_hi)
		boxes.append(rect)
		ax.add_line(vline_lo)
		ax.add_line(vline_hi)
		ax.add_patch(rect)

	ax.autoscale_view()

	return lines, boxes
Beispiel #4
0
    def plotKLine(self, data, timescale=1.0,
                  width=0.9, colorup='r', colorflat = 'w', colordown='g', alpha=1.0):
        u"""根据数据画一个新的K线"""
        self.priceChart.set_xlim(data[0]-50*timescale/86400,data[0]+8*timescale/86400)
        
        t, open, close, high, low = data[:5]

        if close > open:
            color = colorup
        elif close == open:
            color = colorflat
        else:
            color = colordown
            
        if close == open:
            close = open + 0.005
        
        shadowline = Line2D(xdata=(t, t), ydata=(low, high),
            color=color,linewidth=0.5,antialiased=True,)

        rect = Rectangle(xy = (t-width*timescale/172800, open),
            width = width*timescale/86400,
            height = close-open, facecolor=color, edgecolor=color,)  
            
        rect.set_alpha(alpha)
        
        self.priceChart.add_line(shadowline)
        self.priceChart.add_patch(rect)

        return shadowline, rect
Beispiel #5
0
 def candlestick(self, axis, prices, width=0.5, colorup='green', 
             colordown='red', alpha=1.0):
     """
     Plot the time, open, close, high, low as a vertical line ranging
     from low to high.  Use a rectangular bar to represent the
     open-close span.  If close >= open, use colorup to color the bar,
     otherwise use colordown
     ax          : an Axes instance to plot to
     width       : fraction of a day for the rectangle width
     colorup     : the color of the rectangle where close >= open
     colordown   : the color of the rectangle where close <  open
     alpha       : the rectangle alpha level
     """
     dates = []
     lines = []
     for date in self.dates:
         t = date2num(date)
         close = prices.close[date]
         open_ = prices.open[date]
         if close >= open_:
             color = colorup
             lower = open_
             height = close - open_
         else:
             color = colordown
             lower = close
             height = open_ - close
         lines.extend([prices.low[date], prices.high[date], None])
         dates.extend([t, t, None])
         rect = Rectangle(xy=(t - width/2, lower), width=width,
                 height=height, facecolor=color, edgecolor=color, zorder=2)
         rect.set_alpha(alpha)
         axis.add_patch(rect)
     axis.plot(dates, lines, linewidth=0.5, zorder=1, antialiased=True)
     return min(y for y in lines if y is not None), max(lines)
Beispiel #6
0
    def __plot_volume(self, ax, params=None):
        if params is None:
            width = 0.6
        else:
            width = params["width"]
        prices = self.prices.tail(self.candlestick_num)

        for i in self.indices:
            p = prices.iloc[i, :]
            open = p["Open"]
            close = p["Close"]
            volume = p["Volume"]

            if close >= open:
                color = "red"
            else:
                color = "green"

            rect = Rectangle(
                    xy = (i - width/2, 0),
                    width = width,
                    height = volume,
                    facecolor = color,
                    edgecolor = color,
            )
            rect.set_alpha(0.5)
            ax.add_patch(rect)

        ax.set_ylim([0, prices["Volume"].max() * 1.25])
        ax.grid(b=True, axis='x')
Beispiel #7
0
    def plotKLine(self, data, timescale=1.0,
                  width=0.9, colorup='r', colorflat = 'w', colordown='g', alpha=1.0):
        self.priceChart.set_xlim(data[0]-50*timescale/86400,data[0]+8*timescale/86400)
        
        t, open, close, high, low = data[:5]

        if close > open:
            color = colorup
        elif close == open:
            color = colorflat
        else:
            color = colordown
            
        if close == open:
            close = open + 0.005
        
        shadowline = Line2D(xdata=(t, t), ydata=(low, high),
            color=color,linewidth=0.5,antialiased=True,)

        rect = Rectangle(xy = (t-width*timescale/172800, open),
            width = width*timescale/86400,
            height = close-open, facecolor=color, edgecolor=color,)  
            
        rect.set_alpha(alpha)
        
        #self.priceChart.axhline(y=close,xmin=0.2,xmax=0.8)
        
        self.priceChart.add_line(shadowline)
        self.priceChart.add_patch(rect)

        #返回画的图形,方便后面adjust
        return shadowline, rect
Beispiel #8
0
    def plotVolume(self,
                   data,
                   timescale=1.0,
                   width=0.9,
                   colorup='r',
                   colorflat='w',
                   colordown='g',
                   alpha=1.0):
        u"""根据数据画一个新的成交量rect"""
        self.volumeChart.set_xlim(data[0] - 50 * timescale / 86400,
                                  data[0] + 8 * timescale / 86400)

        t, open, close = data[:3]
        volume = data[5]
        if close > open:
            color = colorup
        elif close == open:
            color = colorflat
        else:
            color = colordown

        rect = Rectangle(xy=(t - width * timescale / 172800, 0),
                         width=width * timescale / 86400,
                         height=volume,
                         facecolor=color,
                         edgecolor=color)

        rect.set_alpha(alpha)

        self.volumeChart.add_patch(rect)

        return rect
def render_sticks(ax, quotes, width=1000, colorup='#00FF00', colordown='#FF0000', alpha=0.8):
    for q in quotes:
        t, open, high, low, close = q[:5]
        timestamp = dates.date2num(t)

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(timestamp, timestamp), ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )
        rect = Rectangle(
            xy=(timestamp, lower),
            width=0.5/len(quotes),
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)
        rect.set_linewidth((width * 0.8)/len(quotes))
        ax.add_line(vline)
        ax.add_patch(rect)
Beispiel #10
0
    def __fill_fibonacci_retracement_rectangle_dic__(self):
        index_left = self.xy[0, 0]
        index_right = self.xy[self.xy.shape[0] - 1, 0]
        value_left = self.xy[0, 1]
        value_right = self.xy[self.xy.shape[0] - 1, 1]
        value_range = value_right - value_left
        width = index_right - index_left

        for k in range(
                0,
                len(fibonacci_helper.retracement_array_for_plotting) - 1):
            ret_01 = fibonacci_helper.retracement_array_for_plotting[k]
            ret_02 = fibonacci_helper.retracement_array_for_plotting[k + 1]

            value_01 = round(value_left + ret_01 * value_range, 2)
            value_02 = round(value_left + ret_02 * value_range, 2)
            height = value_02 - value_01
            rectangle = Rectangle(np.array([index_left, value_01]),
                                  width=width,
                                  height=height)
            rectangle.set_linewidth(1)
            rectangle.set_linestyle('dashed')
            rectangle.set_color(self.color_list[k])
            rectangle.set_edgecolor('k')
            rectangle.set_alpha(0.1)
            rectangle.set_visible(False)
            self.__fib_retracement_rectangle_dic[ret_02] = rectangle
            self.__fill_retracement_text_annotations__(index_left, ret_02,
                                                       value_02)
            self.__fill_retracement_spikes_text_annotations__(ret_02, k + 1)
Beispiel #11
0
def plot_quad_system_geometry(stateSolMat, timeStep):
    '''
    stateSol is the state vector of the payload, for each time step
    X=x xDot y yDot theta thetaDot
    ax is the returned figure axis
    '''
    stateSol = stateSolMat[timeStep]
    # Figure #1
    fig = plt.figure(figsize=(13, 8))
    ax = fig.gca()
    # ax.axis todo: set limits to axes so they are bigger then expected geometry

    ax.scatter(stateSol[0], stateSol[2], s=20, c='b')  #stateSol[:,0]
    print stateSol[0], stateSol[2]

    # # LumpedMass payload
    # lumpedPayload = Circle((stateSol[0,0], stateSol[0,0]), 13)
    # Circle.set_color(lumpedPayload, '0.75')
    # Circle.set_alpha(lumpedPayload, 0.1)
    # ax.add_patch(lumpedPayload)
    # print stateSol[0,0]

    # rectangular payload
    payloadW = 1.2
    payloadH = 0.1
    rectPayload = Rectangle((stateSol[0], stateSol[2]), payloadW, payloadH)
    Rectangle.set_color(rectPayload, '0.75')
    Rectangle.set_alpha(rectPayload, 0.71)  #1-opac 0-transparent
    ax.add_patch(rectPayload)

    return fig
Beispiel #12
0
def draw_box(x1, x2, y1, y2, ax, col):
    c = array([[x1], [y1]])
    rect = Rectangle(c, width=x2 - x1, height=y2 - y1, angle=0)
    rect.set_facecolor(array([0.4, 0.3, 0.6]))
    ax.add_patch(rect)
    rect.set_clip_box(ax.bbox)
    rect.set_alpha(0.7)
    rect.set_facecolor(col)
Beispiel #13
0
 def _plot_rect(self, xy, color='b'):
     rect = Rectangle(xy=xy,
                      width=1,
                      height=1,
                      facecolor=color,
                      edgecolor=color)
     rect.set_alpha(1)
     self.ax.add_patch(rect)
def william_edu_candlestick(ax,
                            quotes,
                            width=0.2,
                            colorup='#00FF00',
                            colordown='#FF0000',
                            alpha=1.0,
                            shadowCol='k',
                            ochl=True):

    OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        if ochl:
            t, open, close, high, low = q[:5]
        else:
            t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
            vline = Line2D(
                xdata=(t, t),
                ydata=(low, high),
                color=colorup,
                linewidth=0.5,
                antialiased=True,
            )
        else:
            color = colordown
            lower = close
            height = open - close
            vline = Line2D(
                xdata=(t, t),
                ydata=(low, high),
                color=colordown,
                linewidth=0.5,
                antialiased=True,
            )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
Beispiel #15
0
def nextCandlestick(positionAfterOpen=0,
                    width=0.6,
                    colorup='g',
                    colordown='r',
                    alpha=1.0):
    global ax, ws, wb, lineMode, figureTitle, titleText, candlenumber, currentPosition, entryPrice, entryDate, PandL, datesList, opensList, closesList, highsList, lowsList
    OFFSET = width / 2.0
    lineMode = False
    close = closesList[candlenumber]
    open = opensList[candlenumber]
    if currentPosition != 0 and currentPosition != positionAfterOpen:
        profit = currentPosition * (open - entryPrice)
        PandL += profit
        ws.append((positionStrings[currentPosition], entryPrice, open,
                   (datesList[candlenumber] - entryDate).days, profit))
        wb.save('/Users/sanatana/Documents/Paper_Trades.xlsx')
    if positionAfterOpen != 0 and currentPosition != positionAfterOpen:
        entryPrice = open
        entryDate = datesList[candlenumber]
    currentPosition = positionAfterOpen
    tradeValue = currentPosition * (close - entryPrice)
    if close >= open:
        color = colorup
        lower = open
        height = close - open
    else:
        color = colordown
        lower = close
        height = open - close
    vline = lin.Line2D(xdata=(candlenumber + 1, candlenumber + 1),
                       ydata=(lowsList[candlenumber], highsList[candlenumber]),
                       color=color,
                       linewidth=1.0,
                       antialiased=True)
    rect = Rectangle(xy=(candlenumber + 1 - OFFSET, lower),
                     width=width,
                     height=height,
                     facecolor=color,
                     edgecolor=color)
    rect.set_alpha(alpha)
    ax.add_line(vline)
    ax.add_patch(rect)
    setView()
    candlenumber += 1
    if currentPosition == 0:
        entryString = "---"
        valueString = "---"
    else:
        entryString = str(round(entryPrice, 2))
        valueString = str(round(tradeValue, 2))
    titleText = "P&L: " + str(round(
        PandL, 2)) + "      Currently: " + positionStrings[currentPosition]

    titleText += "     Entry: " + entryString + "     Latest Price: " + str(
        round(close, 2)) + "    Position Value: " + valueString
    figureTitle.set_text(titleText)
Beispiel #16
0
def candlestick(ax, df, width=0.4, colorup='k', colordown='r', alpha=1.0):
    """ draw candle stick chart on an matplotlib axis """
    from matplotlib.lines import Line2D
    from matplotlib.patches import Rectangle
    from matplotlib.dates import date2num
    import matplotlib.dates as mdates
    import matplotlib.ticker as mticker

    OFFSET = width / 2.0

    low = df.low.values
    high = df.high.values
    op = df.open.values
    co = df.close.values
    t = df.index.to_pydatetime()
    tt = date2num(t)

    lines = []
    rects = []

    for i in range(len(tt)):

        if co[i] >= op[i]:
            color = colorup
            lower = op[i]
            height = co[i] - op[i]
        else:
            color = colordown
            lower = co[i]
            height = op[i] - co[i]

        vline = Line2D(
            xdata=(tt[i], tt[i]),
            ydata=(low[i], high[i]),
            color=color,
            linewidth=0.5,
            #antialiased=True,
        )
        vline.set_alpha(alpha)

        rect = Rectangle(
            xy=(tt[i] - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        rects.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    # end of for
    ax.autoscale_view()
    return lines, rects
 def draw_rectangle(self,xs,ys,alpha=0.2,color='g'):
     xy = (min(xs),min(ys))
     width = np.abs(np.diff(xs))
     height = np.abs(np.diff(ys))
     re = Rectangle(xy, width, height, angle=0.0)
     ax = self.axs[0]
     ax.add_artist(re)
     re.set_alpha(alpha=alpha)
     re.set_facecolor(color)
     return re
def addDynamicComponent(momdp, ax, col, row, colorComponent, totProb):
    obstPatchList = []
    for i in range(0, len(row)):
        x = col[i]
        y = momdp.gridVar.shape[0] - row[i] - 1
        patch = Rectangle((x, y), 1, 1, fc=colorComponent, ec=colorComponent)
        patch.set_alpha(1 - totProb[i])
        obstPatchList.append(patch)
        ax.add_patch(obstPatchList[-1])
    return obstPatchList
Beispiel #19
0
def candlestick(ax,
                quotes_df,
                width=0.2,
                colorup='w',
                colordown='k',
                alpha=1.0):
    lines = []
    patches = []
    offset = width / 2.0

    for i in range(len(quotes_df)):
        pr_open = quotes_df['Open'][i]
        pr_high = quotes_df['High'][i]
        pr_low = quotes_df['Low'][i]
        pr_close = quotes_df['Close'][i]

        if pr_close >= pr_open:
            color = colorup
            lower = pr_open
            upper = pr_close
            height = pr_close - pr_open
        else:
            color = colordown
            lower = pr_close
            upper = pr_open
            height = pr_open - pr_close

        vline = Line2D(xdata=(i, i),
                       ydata=(pr_low, lower),
                       color='k',
                       linewidth=0.5,
                       antialiased=True)
        vline2 = Line2D(xdata=(i, i),
                        ydata=(upper, pr_high),
                        color='k',
                        linewidth=0.5,
                        antialiased=True)
        rect = Rectangle(xy=(i - offset, lower),
                         width=width,
                         height=height,
                         facecolor=color,
                         edgecolor='k',
                         linewidth=0.5)
        rect.set_alpha(alpha)

        lines.append(vline)
        lines.append(vline2)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_line(vline2)
        ax.add_patch(rect)
    ax.set_xlim(0, len(quotes_df))
    ax.grid(axis='x', color='0.4', aa=True)
    ax.autoscale_view()
    return lines, patches
Beispiel #20
0
def draw_rectangles(img,
                    catalog,
                    colnames=['x', 'y'],
                    header=None,
                    ax=None,
                    rectangle_size=[30, 30],
                    pixel_scale=0.168,
                    color='r',
                    **kwargs):
    if ax is None:
        fig = plt.figure(figsize=(12, 12))
        fig.subplots_adjust(left=0.0,
                            right=1.0,
                            bottom=0.0,
                            top=1.0,
                            wspace=0.00,
                            hspace=0.00)
        gs = gridspec.GridSpec(2, 2)
        gs.update(wspace=0.0, hspace=0.00)
        ax1 = fig.add_subplot(gs[0])
    else:
        ax1 = ax

    #ax1.yaxis.set_major_formatter(NullFormatter())
    #ax1.xaxis.set_major_formatter(NullFormatter())
    #ax1.axis('off')

    from matplotlib.patches import Rectangle
    if np.any([item.lower() == 'ra' for item in colnames]):
        if header is None:
            raise ValueError(
                '# Header containing WCS must be provided to convert sky coordinates into image coordinates.'
            )
            return
        else:
            w = wcs.WCS(header)
            x, y = w.wcs_world2pix(
                Table(catalog)[colnames[0]].data.data,
                Table(catalog)[colnames[1]].data.data, 0)
    else:
        x, y = catalog[colnames[0]], catalog[colnames[1]]
    display_single(img, ax=ax1, pixel_scale=pixel_scale, **kwargs)
    for i in range(len(catalog)):
        e = Rectangle(xy=(x[i] - rectangle_size[0] // 2,
                          y[i] - rectangle_size[1] // 2),
                      height=rectangle_size[0],
                      width=rectangle_size[1],
                      angle=0)
        e.set_facecolor('none')
        e.set_edgecolor(color)
        e.set_alpha(0.7)
        e.set_linewidth(1.3)
        ax1.add_artist(e)
    if ax is not None:
        return ax
Beispiel #21
0
    def fooCandlestick(ax,
                       quotes,
                       width=0.5,
                       colorup='k',
                       colordown='r',
                       alpha=1.0):
        OFFSET = width / 2.0
        linewidth = width * 2
        print(width)
        lines = []
        boxes = []
        for q in quotes:
            # t, op, cl, hi, lo = q[:5]
            t, op, hi, lo, cl = q[:5]

            box_h = max(op, cl)
            box_l = min(op, cl)
            height = box_h - box_l

            if cl >= op:
                color = colorup
            else:
                color = colordown

            vline_lo = Line2D(
                xdata=(t, t),
                ydata=(lo, box_l),
                color=color,
                linewidth=linewidth,
                antialiased=True,
            )
            vline_hi = Line2D(
                xdata=(t, t),
                ydata=(box_h, hi),
                color=color,
                linewidth=linewidth,
                antialiased=True,
            )
            rect = Rectangle(
                xy=(t - OFFSET, box_l),
                width=width,
                height=height,
                facecolor=color,
                edgecolor=color,
            )
            rect.set_alpha(alpha)
            lines.append(vline_lo)
            lines.append(vline_hi)
            boxes.append(rect)
            ax.add_line(vline_lo)
            ax.add_line(vline_hi)
            ax.add_patch(rect)
        ax.autoscale_view()

        return lines, boxes
Beispiel #22
0
def addDynamicComponent(momdp, ax, col, row, colorComponent, bt):
    obstPatchList = []
    for i in range(0, len(row)):
        x = col[i]
        y = momdp.gridVar.shape[0] - row[i] - 1
        patch = Rectangle((x, y), 1, 1, fc=colorComponent, ec=colorComponent)
        totProb = 0
        for j in range(0, momdp.numO):
            totProb = totProb + (1 - momdp.comb[j][i]) * bt[0][j]
        patch.set_alpha(1 - totProb)
        obstPatchList.append(patch)
        ax.add_patch(obstPatchList[-1])
    return obstPatchList
Beispiel #23
0
    def candlestick(self,
                    ax,
                    quotes,
                    width=0.4,
                    colorup='k',
                    colordown='r',
                    alpha=1.0,
                    ochl=True):
        OFFSET = width / 2.0
        lines = []
        patches = []
        for q in quotes:
            if ochl:
                t, open, close, high, low = q[:5]
            else:
                t, open, high, low, close = q[:5]

            if close >= open:
                color = colorup
                lower = open
                height = close - open
            else:
                color = colordown
                lower = close
                height = open - close

            vline = Line2D(
                xdata=(t, t),
                ydata=(low, high),
                color=color,
                linewidth=0.7,
                antialiased=True,
            )

            rect = Rectangle(
                xy=(t - OFFSET, lower),
                width=width,
                height=height,
                facecolor=color,
                edgecolor=color,
            )
            rect.set_alpha(alpha)

            lines.append(vline)
            patches.append(rect)
            ax.add_line(vline)
            ax.add_patch(rect)
        ax.autoscale_view()
        ax.yaxis.tick_right()

        return lines, patches
Beispiel #24
0
    def __plot_candlestick(self, ax, width=0.5, colorup='red', colordown='green', alpha=0.8):
        offset = width / 2.0
        line_width = width * 2
        prices = self.prices.tail(self.candlestick_num)

        for i in self.indices:
            p = prices.iloc[i, :]
            open = p["Open"]
            close = p["Close"]
            high = p["High"]
            low = p["Low"]

            box_high = max(open, close)
            box_low = min(open, close)
            height = box_high - box_low

            if close >= open:
                color = colorup
            else:
                color = colordown

            vline_low = Line2D(
                    xdata=(i, i), ydata=(low, box_low),
                    color = 'black',
                    linewidth=line_width,
                    antialiased=True,
            )

            vline_high = Line2D(
                    xdata=(i, i), ydata=(box_high, high),
                    color = 'black',
                    linewidth=line_width,
                    antialiased=True,
            )

            rect = Rectangle(
                    xy = (i - offset, box_low),
                    width = width,
                    height = height,
                    facecolor = color,
                    edgecolor = color,
            )
            rect.set_alpha(alpha)

            ax.add_line(vline_low)
            ax.add_line(vline_high)
            ax.add_patch(rect)

        ax.autoscale_view()
    def plot_rectangle(bboxes, ax, step, c='#ff7f0e'):

        for bbox in bboxes[bboxes['ts'] % step == 0]:
            s_phi_offset, c_phi_offset = np.sin(bbox['orientation']), np.cos(bbox['orientation'])
            rot = np.array([[c_phi_offset, - s_phi_offset], [s_phi_offset, c_phi_offset]])
            offset_xy = np.dot(rot, 0.5 * bbox['dimension'])

            r = Rectangle(xy=bbox['center_xy'] - offset_xy, width=bbox['dimension'][0], height=bbox['dimension'][1],
                          angle=np.rad2deg(bbox['orientation']))

            ax.add_artist(r)
            r.set_clip_box(ax.bbox)
            r.set_alpha(0.8)
            r.set_facecolor('none')
            r.set_edgecolor(c)
Beispiel #26
0
def render_sticks(ax,
                  quotes,
                  has_date,
                  base_rect_coef=0.5,
                  width=1000,
                  colorup='#00FF00',
                  colordown='#FF0000',
                  alpha=0.8):
    index = 0
    rect_width = (base_rect_coef *
                  0.5 if len(quotes) < 100 else base_rect_coef) / len(quotes)
    for q in quotes:
        if has_date:
            open, high, low, close = q[1], q[2], q[3], q[4]
            timestamp = dates.date2num(q[0])
        else:
            open, high, low, close = q[0], q[1], q[2], q[3]
            timestamp = index

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(timestamp, timestamp),
            ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )
        rect = Rectangle(
            xy=(timestamp, lower),
            width=rect_width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)
        rect.set_linewidth((width * 0.8) / len(quotes))
        ax.add_line(vline)
        ax.add_patch(rect)
        index += 1
Beispiel #27
0
    def addTicker(self, ticker):
        
        t = date2num(ticker.getDate())
        open = ticker.getOpen()
        close = ticker.getAdjustedClose()
        high = ticker.getHigh()
        low = ticker.getLow()
        volume = ticker.getVolume()
             
        if close >= open:
            color = self.__colorup
            lower = open
            height = close - open
        else:
            color = self.__colordown
            lower = close
            height = open - close

        vline = Line2D(
                       xdata=(t, t), ydata=(low, high),
                       color='k',
                       linewidth=1,
                       antialiased=True,
                       )

        rectTicker = Rectangle(
                               xy=(t - self.__offset, lower),
                               width = self.__candleWidth,
                               height = height,
                               facecolor = color,
                               edgecolor = color,
                               )
            
        rectTicker.set_alpha(self.__alpha)

        rectVolume = Rectangle(
                               xy=(t - self.__offset, 0),
                               width = self.__candleWidth,
                               height = volume,
                               facecolor = color,
                               edgecolor = color,
                               )

        self.__axCandle.add_line(vline)
        self.__axCandle.add_patch(rectTicker)
        self.__axVolume.add_patch(rectVolume)
Beispiel #28
0
	def boundingBox(self, data, ax, label, bBoundingBoxes, bLabels):
		''' Draw bounding box around data.'''
		data = np.array(data)
	
		width = max(data[:,0]) - min(data[:,0])
		height = max(data[:,1]) - min(data[:,1])
		r = Rectangle((min(data[:,0]), min(data[:,1])), width, height)
	
		if bBoundingBoxes:
			ax.add_artist(r)
			r.set_clip_box(ax.bbox)
			r.set_alpha(0.1)
			r.set_facecolor((0.5, 0.5, 0.5))
			
		if bLabels:
			ax.annotate(label, xy = (min(data[:,0]), max(data[:,1])), xytext = (0, 0),
							textcoords = 'offset points', ha = 'right', va = 'bottom',
							bbox = dict(boxstyle = 'round,pad=0.5', fc = (0.5, 0.5, 0.5), alpha = 0.1))
Beispiel #29
0
def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0):

    OFFSET = width / 2.0

    for q in quotes:

        t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(xdata=(t, t),
                       ydata=(low, high),
                       color=color,
                       linewidth=0.5,
                       antialiased=True)

        rect = Rectangle(xy=(t - OFFSET, lower),
                         width=width,
                         height=height,
                         facecolor=color,
                         edgecolor=color)

        rect.set_alpha(alpha)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    ax.plot(quotes[:, 0],
            calc.calc_avg_exp(quotes[:, -1], 12),
            label="exponential moving average over 12 days")
    ax.plot(quotes[:, 0],
            calc.calc_avg_exp(quotes[:, -1], 26),
            label="exponential moving average over 26 days")
    ax.legend()
    return ax
Beispiel #30
0
    def __init__(self, py_time, ohlc):
        self.config()
        t = awarePyTime2Float(py_time)
        open = ohlc[0]
        high = ohlc[1]
        low = ohlc[2]
        close = ohlc[3]
        if close >= open:
            color = self.color_positive
            line_color = self.box_line_color_positive
            box_low = open
            box_high = close
            height = close - open
        else:
            color = self.color_negative
            line_color = self.box_line_color_negative
            box_low = close
            box_high = open
            height = open - close
            
        line_upper = Line2D([(t, t)],[(box_high, high)],
                            color=line_color,
                            linewidth=self.line_width,
                            antialiased=True)
        line_lower = Line2D(xdata=(t, t),
                            ydata=(box_low, low),
                            color=line_color,
                            linewidth=self.line_width,
                            antialiased=True)

        rect = Rectangle(xy=(t - self.box_width / 2, box_low),
                         width=self.box_width,
                         height=height,
                         facecolor=color,
                         edgecolor=line_color)
        rect.set_alpha(self.alpha)

        self.line_upper = line_upper
        self.line_lower = line_lower
        self.rect = rect
        return
Beispiel #31
0
def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0):
    # https://github.com/matplotlib/mpl_finance/blob/master/mpl_finance.py
    from matplotlib.lines import Line2D
    from matplotlib.patches import Rectangle

    OFFSET = width / 2.0

    for q in quotes:
        t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t),
            ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()
Beispiel #32
0
    def plot_candle(self, q):
        colorup = 'r'
        colordown = 'g'
        width = 180
        OFFSET = width / 2.0

        t, open, high, low, close = q[:5]
        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t),
            ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )

        rect.set_alpha(1)
        self.ax.add_line(vline)
        self.ax.add_patch(rect)
        self.ax.autoscale_view()

        return vline, rect
Beispiel #33
0
def plotCandleStick(ax,
                    quotes,
                    xdata=None,
                    width=0.2,
                    colorup='#B70203',
                    colordown='#3ACCCC',
                    alpha=1.0):
    if xdata is None: xdata = np.arange(quotes.shape[0])
    OFFSET = width / 2.0
    Lines, Patches = [], []
    for i in range(quotes.shape[0]):
        if pd.isnull(quotes[i]).sum() > 0: continue
        iOpen, iHigh, iLow, iClose = quotes[i]
        if iClose >= iOpen:
            iColor = colorup
            iLower = iOpen
            iHeight = iClose - iOpen
        else:
            iColor = colordown
            iLower = iClose
            iHeight = iOpen - iClose
        iVLine = Line2D(xdata=(xdata[i], xdata[i]),
                        ydata=(iLow, iHigh),
                        color=iColor,
                        linewidth=0.5,
                        antialiased=True)
        iRect = Rectangle(xy=(i - OFFSET, iLower),
                          width=width,
                          height=iHeight,
                          facecolor=iColor,
                          edgecolor=iColor)
        iRect.set_alpha(alpha)
        Lines.append(iVLine)
        Patches.append(iRect)
        ax.add_line(iVLine)
        ax.add_patch(iRect)
    ax.autoscale_view()
    return Lines, Patches
Beispiel #34
0
def candlestick(ax, quotes_df, width=0.2, colorup='w', colordown='k', alpha=1.0):
    lines = []
    patches = []
    offset = width/2.0

    for i in range(len(quotes_df)):
        pr_open = quotes_df['Open'][i]
        pr_high = quotes_df['High'][i]
        pr_low =  quotes_df['Low'][i]
        pr_close = quotes_df['Close'][i]

        if pr_close >= pr_open:
            color = colorup
            lower = pr_open
            upper = pr_close
            height = pr_close - pr_open
        else:
            color = colordown
            lower = pr_close
            upper = pr_open
            height = pr_open - pr_close

        vline  = Line2D(xdata=(i, i), ydata=(pr_low, lower), color='k', linewidth=0.5, antialiased=True)
        vline2 = Line2D(xdata=(i, i), ydata=(upper, pr_high), color='k', linewidth=0.5, antialiased=True)
        rect = Rectangle(xy=(i - offset, lower), width=width, height=height, facecolor=color, 
                         edgecolor='k', linewidth=0.5)
        rect.set_alpha(alpha)

        lines.append(vline)
        lines.append(vline2)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_line(vline2)
        ax.add_patch(rect)
    ax.set_xlim(0, len(quotes_df))
    ax.grid(axis='x', color='0.4', aa=True)
    ax.autoscale_view()
    return lines, patches
Beispiel #35
0
def addBar(xpos, quote, barWidth, colorUpper, colorLower, alpha):
    date, o, h, l, c = quote
    if o >= c:
        color = colorLower
        barHeight = o - c
        lowestBarPosition = c
    else:
        color = colorUpper
        barHeight = c - o
        lowestBarPosition = o

    line = Line2D(xdata=(xpos, xpos),
                  ydata=(l, h),
                  color=color,
                  linewidth=0.5,
                  antialiased=True)
    bar = Rectangle(xy=(xpos - barWidth / 2.0, lowestBarPosition),
                    width=barWidth,
                    height=barHeight,
                    facecolor=color,
                    edgecolor=color)
    bar.set_alpha(alpha)
    return line, bar
Beispiel #36
0
    def plotVolume(self, data, timescale=1.0,
                   width=0.9, colorup='r', colorflat='w',colordown='g', alpha=1.0):
        u"""根据数据画一个新的成交量rect"""
        self.volumeChart.set_xlim(data[0]-50*timescale/86400,data[0]+8*timescale/86400)
        
        t, open, close= data[:3]
        volume = data[5]
        if close > open:
            color = colorup
        elif close == open:
            color = colorflat
        else:
            color = colordown
            
        rect = Rectangle(xy = (t-width*timescale/172800, 0),
            width = width*timescale/86400,
            height = volume, facecolor=color, edgecolor=color)

        rect.set_alpha(alpha)
            
        self.volumeChart.add_patch(rect)

        return rect
def buildExcVol(cutX,cutY,cutZ,ax):
    """
    Builds rectangular prism (excluded volume).
    """
    r1 = Rectangle((-cutX,-cutZ),2.0*cutX,2.0*cutZ)
    r4 = Rectangle((-cutX,-cutZ),2.0*cutX,2.0*cutZ)
    r2 = Rectangle((-cutY,-cutZ),2.0*cutY,2.0*cutZ)
    r5 = Rectangle((-cutY,-cutZ),2.0*cutY,2.0*cutZ)
    r3 = Rectangle((-cutX,-cutY),2.0*cutX,2.0*cutY)
    r6 = Rectangle((-cutX,-cutY),2.0*cutX,2.0*cutY)
    r1.set_alpha(0.1)
    r2.set_alpha(0.1)
    r3.set_alpha(0.1)
    r4.set_alpha(0.1)
    r5.set_alpha(0.1)
    r6.set_alpha(0.1)
    ax.add_patch(r1), ax.add_patch(r2)
    ax.add_patch(r3), ax.add_patch(r4)
    ax.add_patch(r5), ax.add_patch(r6)

    art3d.pathpatch_2d_to_3d(r1, z=-cutY, zdir="y")
    art3d.pathpatch_2d_to_3d(r4, z=cutY, zdir="y")
    art3d.pathpatch_2d_to_3d(r2, z=cutX, zdir="x")
    art3d.pathpatch_2d_to_3d(r5, z=-cutX, zdir="x")
    art3d.pathpatch_2d_to_3d(r3, z=cutZ, zdir="z")
    art3d.pathpatch_2d_to_3d(r6, z=-cutZ, zdir="z")
Beispiel #38
0
def _candlestick(ax,
                 quotes,
                 width=0.2,
                 colorup='k',
                 colordown='r',
                 alpha=1.0,
                 ochl=True):
    """
    Plot the time, open, high, low, close as a vertical line ranging
    from low to high.  Use a rectangular bar to represent the
    open-close span.  If close >= open, use colorup to color the bar,
    otherwise use colordown

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    quotes : sequence of quote sequences
        data to plot.  time must be in float date format - see date2num
        (time, open, high, low, close, ...) vs
        (time, open, close, high, low, ...)
        set by `ochl`
    width : float
        fraction of a day for the rectangle width
    colorup : color
        the color of the rectangle where close >= open
    colordown : color
         the color of the rectangle where close <  open
    alpha : float
        the rectangle alpha level
    ochl: bool
        argument to select between ochl and ohlc ordering of quotes

    Returns
    -------
    ret : tuple
        returns (lines, patches) where lines is a list of lines
        added and patches is a list of the rectangle patches added

    """

    OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        if ochl:
            t, open, close, high, low = q[:5]
        else:
            t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t),
            ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
def buildOuter(Lx,Ly,Lz,ax,col='Purple'):
    """
    Builds rectangular prism (outer cell walls).
    """
    r7 = Rectangle((-Lx/2,-Lz/2),Lx,Lz, color=col)
    r8 = Rectangle((-Lx/2,-Lz/2),Lx,Lz, color=col)
    r9 = Rectangle((-Ly/2,-Lz/2),Ly,Lz, color=col)
    r10 = Rectangle((-Ly/2,-Lz/2),Ly,Lz, color=col)
    r11 = Rectangle((-Lx/2,-Ly/2),Lx,Ly, color=col)
    r12 = Rectangle((-Lx/2,-Ly/2),Lx,Ly, color=col)
    r7.set_alpha(0.1)
    r8.set_alpha(0.1)
    r9.set_alpha(0.1)
    r10.set_alpha(0.1)
    r11.set_alpha(0.1)
    r12.set_alpha(0.1)
    ax.add_patch(r7), ax.add_patch(r8)
    ax.add_patch(r9), ax.add_patch(r10)
    ax.add_patch(r11), ax.add_patch(r12)

    art3d.pathpatch_2d_to_3d(r7, z=-Ly/2, zdir="y")
    art3d.pathpatch_2d_to_3d(r8, z=Ly/2, zdir="y")
    art3d.pathpatch_2d_to_3d(r9, z=Lx/2, zdir="x")
    art3d.pathpatch_2d_to_3d(r10, z=-Lx/2, zdir="x")
    art3d.pathpatch_2d_to_3d(r11, z=Lz/2, zdir="z")
    art3d.pathpatch_2d_to_3d(r12, z=-Lz/2, zdir="z")
Beispiel #40
0
def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
                alpha=1.0):

    """

    quotes is a sequence of (time, open, close, high, low, ...) sequences.
    As long as the first 5 elements are these values,
    the record can be as long as you want (eg it may store volume).

    time must be in float days format - see date2num

    Plot the time, open, close, high, low as a vertical line ranging
    from low to high.  Use a rectangular bar to represent the
    open-close span.  If close >= open, use colorup to color the bar,
    otherwise use colordown

    ax          : an Axes instance to plot to
    width       : fraction of a day for the rectangle width
    colorup     : the color of the rectangle where close >= open
    colordown   : the color of the rectangle where close <  open
    alpha       : the rectangle alpha level

    return value is lines, patches where lines is a list of lines
    added and patches is a list of the rectangle patches added

    """

    OFFSET = width/2.0

    lines = []
    patches = []
    for q in quotes:
        t, open, close, high, low = q[:5]

        if close>=open :
            color = colorup
            lower = open
            height = close-open
        else           :
            color = colordown
            lower = close
            height = open-close

        vline = Line2D(
            xdata=(t, t), ydata=(low, high),
            color='k',
            linewidth=0.5,
            antialiased=True,
            )

        rect = Rectangle(
            xy    = (t-OFFSET, lower),
            width = width,
            height = height,
            facecolor = color,
            edgecolor = color,
            )
        rect.set_alpha(alpha)


        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
Beispiel #41
0
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as npr
import utilities_nopd as utils
from matplotlib.font_manager import FontProperties
from matplotlib.patches import Rectangle
import colorbrewer as cb
from mpltools import color

legend_font = FontProperties()
legend_font.set_size('small')
ticks_font = FontProperties(family='Helvetica', style='normal', \
                            size=8, weight='normal', stretch='normal')
empty_rect = Rectangle((0,0),1,1)
empty_rect.set_alpha(0)
empty_rect.set_edgecolor('white')
color_scheme_names = ['BrBG', 'PiYG', 'PRGn', 'RdBu', 'RdGy', 'PuOr', \
    'RdYlBu', 'RdYlGn', 'Spectral']
color_schemes = {}
for name in color_scheme_names:
    color_schemes[name] = eval('cb.{0}'.format(name))

def to_rgb(t):
    """
    Args:
        t: 3-tuple of int's in range [0,255]
    
    Returns:
        out: 3-tuple of float's in range [0,1]
    """
    r,g,b = np.array(t)/255.
Beispiel #42
0
def _candlestick(ax, df, width=0.2, colorup='k', colordown='r',
                 alpha=1.0):

    """
    Plot the time, open, high, low, close as a vertical line ranging
    from low to high.  Use a rectangular bar to represent the
    open-close span.  If close >= open, use colorup to color the bar,
    otherwise use colordown

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    df : pandas data from tushare
    width : float
        fraction of a day for the rectangle width
    colorup : color
        the color of the rectangle where close >= open
    colordown : color
         the color of the rectangle where close <  open
    alpha : float
        the rectangle alpha level
    ochl: bool
        argument to select between ochl and ohlc ordering of quotes

    Returns
    -------
    ret : tuple
        returns (lines, patches) where lines is a list of lines
        added and patches is a list of the rectangle patches added

    """

    OFFSET = width / 2.0

    lines = []
    patches = []
    for date_string,row in df.iterrows():
        date_time = datetime.datetime.strptime(date_string,'%Y-%m-%d')
        t = date2num(date_time)
        open, high, close, low = row[:4]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t), ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
def create_board_figure(pcb, bom_row, layer=pcbnew.F_Cu, invert_axis=False):
    qty, value, footpr, highlight_refs = bom_row

    plt.figure(figsize=(5.8, 8.2))
    ax = plt.subplot("111", aspect="equal")

    color_pad1 = "lightgray"
    color_pad2 = "#AA0000"
    color_pad3 = "#CC4444"
    color_bbox1 = "None"
    color_bbox2 = "#E9AFAF"

    # get board edges (assuming rectangular, axis aligned pcb)
    edge_coords = []
    for d in pcb.GetDrawings():
        if (d.GetLayer() == pcbnew.Edge_Cuts):
            edge_coords.append(d.GetStart())
            edge_coords.append(d.GetEnd())
    edge_coords = np.asarray(edge_coords) * 1e-6
    board_xmin, board_ymin = edge_coords.min(axis=0)
    board_xmax, board_ymax = edge_coords.max(axis=0)

    # draw board edges
    rct = Rectangle((board_xmin, board_ymin),
                    board_xmax - board_xmin,
                    board_ymax - board_ymin,
                    angle=0)
    rct.set_color("None")
    rct.set_edgecolor("black")
    rct.set_linewidth(3)
    ax.add_patch(rct)

    # add title
    ax.text(board_xmin + .5 * (board_xmax - board_xmin), board_ymin - 0.5,
            "%dx %s, %s" % (qty, value, footpr), wrap=True,
            horizontalalignment='center', verticalalignment='bottom')\

    # add ref list
    textsize = 12
    refdes_text = ", ".join(highlight_refs)
    if len(refdes_text) > 200:  # limit the size to prevent truncation
        textsize = 10
    if len(refdes_text) > 500:  # limit the size to prevent truncation
        textsize = 8
    if len(refdes_text) > 1100:
        textsize = 6
    ax.text(board_xmin + .5 * (board_xmax - board_xmin),
            board_ymax + 0.5,
            ", ".join(highlight_refs),
            wrap=True,
            horizontalalignment='center',
            verticalalignment='top',
            fontsize=textsize)

    # draw parts
    for m in pcb.GetModules():
        if m.GetLayer() != layer:
            continue
        ref, center = m.GetReference(), np.asarray(m.GetCenter()) * 1e-6
        highlight = ref in highlight_refs

        # bounding box
        mrect = m.GetFootprintRect()
        mrect_pos = np.asarray(mrect.GetPosition()) * 1e-6
        mrect_size = np.asarray(mrect.GetSize()) * 1e-6
        rct = Rectangle(mrect_pos, mrect_size[0], mrect_size[1])
        rct.set_color(color_bbox2 if highlight else color_bbox1)
        rct.set_alpha(0.7)
        rct.set_zorder(-1)
        if highlight:
            rct.set_linewidth(.1)
            rct.set_edgecolor(color_pad2)
        ax.add_patch(rct)

        # center marker
        if highlight:
            plt.plot(center[0],
                     center[1],
                     ".",
                     markersize=mrect_size.min() / 4,
                     color=color_pad2)

        # plot pads
        for p in m.Pads():
            pos = np.asarray(p.GetPosition()) * 1e-6
            #additional scaling pads result in strange effects on pads made
            #from multiple pads - so I removed the * 0.9
            size = np.asarray(p.GetSize()) * 1e-6

            is_pin1 = p.GetPadName() == "1" or p.GetPadName() == "A1"
            shape = p.GetShape()
            offset = p.GetOffset()  # TODO: check offset

            # pad rect
            angle = p.GetOrientation() * 0.1
            cos, sin = np.cos(np.pi / 180. * angle), np.sin(np.pi / 180. *
                                                            angle)
            dpos = np.dot([[cos, -sin], [sin, cos]], -.5 * size)

            if shape == pcbnew.PAD_SHAPE_RECT:
                rct = Rectangle(pos + dpos, size[0], size[1], angle=angle)
            elif shape == pcbnew.PAD_SHAPE_ROUNDRECT:
                # subtract 2x corner radius from pad size, as FancyBboxPatch draws a rounded rectangle around the specified rectangle
                pad = p.GetRoundRectCornerRadius() * 1e-6
                # the bottom-left corner of the FancyBboxPatch is the inside rectangle so need to compensate with the corner radius
                corneroffset = np.asarray([pad, pad])
                #draw rounded patch
                rct = FancyBboxPatch(pos + dpos + corneroffset,
                                     size[0] - 2 * pad,
                                     size[1] - 2 * pad,
                                     boxstyle=matplotlib.patches.BoxStyle(
                                         "Round", pad=pad))
                #and rotate it
                xy = pos + dpos
                tfm = matplotlib.transforms.Affine2D().rotate_deg_around(
                    xy[0], xy[1], angle) + ax.transData
                rct.set_transform(tfm)
            elif shape == pcbnew.PAD_SHAPE_OVAL:
                rct = Ellipse(pos, size[0], size[1], angle=angle)
            elif shape == pcbnew.PAD_SHAPE_CIRCLE:
                rct = Ellipse(pos, size[0], size[0], angle=angle)
            elif shape == pcbnew.PAD_SHAPE_TRAPEZOID:
                #draw trapezoid from scratch
                sx = size[0]
                sy = size[1]
                delta = p.GetDelta()[1] * 1e-6
                xy = np.array([[(sx + delta) / 2, sy / 2],
                               [(sx - delta) / 2, -sy / 2],
                               [(-sx + delta) / 2, -sy / 2],
                               [(-sx - delta) / 2, sy / 2]])
                xy = xy + pos
                rct = Polygon(xy)
                #and rotate it
                xy = pos
                # TODO DEBUG: based on corrections made in ROUNDRECT code above, the angle should NOT be negative(might be bug). No use case so ignored for now
                tfm = matplotlib.transforms.Affine2D().rotate_deg_around(
                    xy[0], xy[1], -angle) + ax.transData
                rct.set_transform(tfm)
            else:
                print("Unsupported pad shape: {0} ".format(shape))
                continue
            rct.set_linewidth(0)
            rct.set_color(color_pad2 if highlight else color_pad1)
            rct.set_zorder(1)
            # highlight pin1
            if highlight and is_pin1:
                rct.set_color(color_pad3)
                rct.set_linewidth(.1)
                rct.set_edgecolor(color_pad2)
            ax.add_patch(rct)

    plt.xlim(board_xmin, board_xmax)
    plt.ylim(board_ymax, board_ymin)

    if (invert_axis):
        plt.gca().invert_xaxis()

    plt.axis('off')
Beispiel #44
0
def candlestick(ax, data, width=0.6, colorup='r', colordown='g', time_format="%Y-%m-%d", alpha=0.7):
    """ Optimized candle stick graph interface.

        :type ax matplotlib.axes.Axes
    """
    offset = width / 2.0
    timeseries = data.index
    t = [tt.strftime(time_format) for tt in timeseries]
    oo = data['open']
    cc = data['close']
    hh = data['high']
    ll = data['low']

    ax.set_xlim(0.0, len(t)*width)

    major_locator = MultipleLocator(20*width)
    minor_locator = MultipleLocator(5*width)

    ax.set_xticks([x*width for x in range(len(t))], minor=True)

    ticklabels = [t[d] for d in range(len(timeseries)) if d % 20 == 0]
    ticklabels.insert(0, 'dummy')  # fix matplotlib tick bug
    ax.tick_params(axis='both', direction='out', width=2, length=8,
                   labelsize=10, pad=8)
    ax.xaxis.set_ticklabels(ticklabels, horizontalalignment='center')
    ax.xaxis.set_major_locator(major_locator)
    ax.xaxis.set_minor_locator(minor_locator)

    lines = []
    patches = []
    for q in range(len(t)):
        c = float(cc[q])
        o = float(oo[q])
        h = float(hh[q])
        l = float(ll[q])
        if c >= o:
            color = colorup
            lower = o
            height = c - o
        else:
            color = colordown
            lower = c
            height = o - c

        vline = Line2D(
            xdata=(q*width, q*width), ydata=(l, h),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(q*width-offset, lower),
            width = width,
            height = height,
            facecolor = color,
            edgecolor = color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)

    ax.autoscale_view()
    return lines, patches
Beispiel #45
0
def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
                 alpha=1.0, ochl=True):

    """
    Plot the time, open, high, low, close as a vertical line ranging
    from low to high.  Use a rectangular bar to represent the
    open-close span.  If close >= open, use colorup to color the bar,
    otherwise use colordown

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    quotes : sequence of quote sequences
        data to plot.  time must be in float date format - see date2num
        (time, open, high, low, close, ...) vs
        (time, open, close, high, low, ...)
        set by `ochl`
    width : float
        fraction of a day for the rectangle width
    colorup : color
        the color of the rectangle where close >= open
    colordown : color
         the color of the rectangle where close <  open
    alpha : float
        the rectangle alpha level
    ochl: bool
        argument to select between ochl and ohlc ordering of quotes

    Returns
    -------
    ret : tuple
        returns (lines, patches) where lines is a list of lines
        added and patches is a list of the rectangle patches added

    """

    OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        if ochl:
            t, open, close, high, low = q[:5]
        else:
            t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t), ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            xy=(t - OFFSET, lower),
            width=width,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect.set_alpha(alpha)

        lines.append(vline)
        patches.append(rect)
        ax.add_line(vline)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches
Beispiel #46
0
def candlestick(self, X = [],Y = [],  # X-Y points in the graph.
        labels = [], legend = [],       # Basic Labelling
        color = None,  lw = 2, alpha = 1.0,  # Basic line properties
        nf = 0, na = 0,          # New axis. To plot in a new axis         # TODO: shareX option
        ax = None, position = [], projection = "2d", # Type of plot
        sharex = None, sharey = None,
        fontsize = 20,fontsizeL = 10, fontsizeA = 15,  # The font for the labels in the axis
        xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision
        ws = None, Ninit = 0,     
        loc = "best",    
        dataTransform = None,
        xaxis_mode = None,yaxis_mode = None,AxesStyle = None,   # Automatically do some formatting :)
        barwidth = None, colorup = "g", colordown = "r"
       ):
       
    # Management of the figure and properties
    ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey,
                      projection = projection, position = position)
    ## Preprocess the data given so that it meets the right format
    X, Y = self.preprocess_data(X,Y,dataTransform)
    NpY, NcY = Y.shape
    plots,plots_typ =  self.init_WidgetData(ws)
    
    ##################### PREPROCESSING AND PLOTTING #######################
    
    # Prepare the data
    openp = Y[self.start_indx:self.end_indx,0]
    closep = Y[self.start_indx:self.end_indx,1]
    highp = Y[self.start_indx:self.end_indx,2]
    lowp = Y[self.start_indx:self.end_indx,3]

    dates = X[self.start_indx:self.end_indx]
    dates = ul.preprocess_dates(dates)
    if (type(barwidth) == type(None)):
        barwidth = self.get_barwidth(dates, barwidth) * 0.8
        
    # PLOTTING !!
    Npoints = dates.size
    
    OFFSET = barwidth / 2.0
    
    line_factor = 0.15
    barwidth_HL = barwidth * line_factor 
    OFFSET_HL = barwidth_HL / 2.0
    
    lines = []
    patches = []
    for i in range(Npoints):
        if closep[i] >= openp[i] :
            color = colorup
            baseRectable = openp[i]
        else:
            color = colordown
            baseRectable = closep[i]
            
        height = np.abs(openp[i]  - closep[i])
        
        ## High-low line

#        line_HL = Line2D(
#            xdata=(dates[i],dates[i]), ydata=(lowp[i], highp[i]),
#            color=color,
#            linewidth=lw,
#            antialiased=True,
#        )

        rect_HL = Rectangle(
            xy=(dates[i] - OFFSET_HL, lowp[i]),
            width=barwidth_HL,
            height=highp[i] - lowp[i],
            facecolor=color,
            edgecolor=color,
        )
        
#        print type(dates[i]), type(OFFSET)
        ## Open Close rectangle
        rect_OP = Rectangle(
            xy=(dates[i] - OFFSET, baseRectable),
            width=barwidth,
            height=height,
            facecolor=color,
            edgecolor=color,
        )
        rect_OP.set_alpha(alpha)
#
#        lines.append(line_HL)
#        patches.append(rect_OP)
        
#        ax.add_line(line_HL)
        ax.add_patch(rect_OP)
        ax.add_patch(rect_HL)
        
#    lines = mc.LineCollection(lines)
#    ax.add_collection(lines)
#    ax.add_collection(patches)
    
    ax.autoscale()  # TODO: The zoom is not changed if we do not say it !
    ############### Last setting functions ###########################
    self.store_WidgetData(plots_typ, plots)     # Store pointers to variables for interaction
    
    self.update_legend(legend,NcY,ax = ax, loc = loc)    # Update the legend 
    self.set_labels(labels)
    self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad)
    self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode)
    self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode)
    self.apply_style(nf,na,AxesStyle)
    
    self.plots_type.append(["candlestick"])
#    self.plots_list.append([plotting]) # We store the pointers to the plots
    
    data_i = [Y, ax]
    self.Data_list.append(data_i)
    
    return ax
Beispiel #47
0
def getRectangle(x, y, width, height, color, alpha=1):
    rect = Rectangle((x, y), width, height)
    rect.set_color(color)
    rect.set_alpha(alpha)
    return rect