当前位置: 首页>>代码示例>>Python>>正文


Python finance.candlestick函数代码示例

本文整理汇总了Python中matplotlib.finance.candlestick函数的典型用法代码示例。如果您正苦于以下问题:Python candlestick函数的具体用法?Python candlestick怎么用?Python candlestick使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了candlestick函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, ticker):
        gtk.VBox.__init__(self)

        startdate = datetime.date(2001, 1, 1)
        today = enddate = datetime.date.today()

        date1 = datetime.date(2011, 1, 1)
        date2 = datetime.date.today()

        mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
        alldays = DayLocator()  # minor ticks on the days
        weekFormatter = DateFormatter("%b %d")  # Eg, Jan 12
        dayFormatter = DateFormatter("%d")  # Eg, 12

        quotes = quotes_historical_yahoo(ticker, date1, date2)
        if len(quotes) == 0:
            raise SystemExit

        fig = Figure(facecolor="white", figsize=(5, 4), dpi=100)
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
        ax.xaxis.set_major_formatter(weekFormatter)
        candlestick(ax, quotes, width=0.6)

        ax.xaxis_date()
        ax.autoscale_view()
        pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment="right")

        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        self.pack_start(canvas)
        toolbar = NavigationToolbar(canvas, win)
        self.pack_start(toolbar, False, False)
开发者ID:nicolasmarti,项目名称:misc-dev-2,代码行数:34,代码来源:yhstckcancas.py

示例2: candlestickExample

def candlestickExample():
    # (Year, month, day) tuples suffice as args for quotes_historical_yahoo
    date1 = ( 2004, 2, 1)
    date2 = ( 2004, 4, 12 )
    
    
    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
    
    quotes = quotes_historical_yahoo('INTC', date1, date2)
    if len(quotes) == 0:
        raise SystemExit
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)
    
    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick(ax, quotes, width=0.6)
    
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    
    print quotes
    plt.show()
开发者ID:justinoliver51,项目名称:WebExtensions,代码行数:31,代码来源:GraphExample.py

示例3: plot_data

def plot_data(data,stock):
  ticks = eg.choicebox(msg = 'choose ticks for the plot',choices = ['day','week','month'])
  if ticks == 'month':
    loc = MonthLocator()
  elif ticks == 'week':
    loc = WeekdayLocator(byweekday=MONDAY)
  elif ticks == 'day':
    loc = DayLocator()
  weekFormatter = DateFormatter('%b %d')
  dayFormatter = DateFormatter('%d')
    
#  if candle_chart == 1:
  fig = plt.figure()
  ax1 = fig.add_subplot(211)
  datelist = [matplotlib.dates.date2num(x) for x in data['Time']]
  Prices = []
  for idx in xrange(len(data)):
    Prices.append((datelist[idx],data['Open'].ix[idx],data['Close'].ix[idx],data['High'].ix[idx],data['Low'].ix[idx]))
#    candlestick(ax1,[datelist,data['Open'],data['Close'],data['High'],data['Low']])
  candlestick(ax1,Prices)
  ax1.set_xlabel('Date')
  ax1.set_ylabel('$')
  ax1.set_title('Candlestick plot for %s' %stock)
  ax2 = fig.add_subplot(212)
  ax2.plot(datelist,data['Adj Close'],'-r',label = 'Adj. Close')
  ax2.set_ylabel('$')
  ax2.legend()
  ax3 = ax2.twinx()
  ax3.bar(data['Time'],data['Volume'])
  ax3.set_ylabel('Shares')
  ax1.xaxis_date()
  ax2.xaxis_date()
  ax3.xaxis_date()
  plt.show()
  return
开发者ID:mihwano,项目名称:stock_market,代码行数:35,代码来源:read_stock.py

示例4: QueryAndShowData

def QueryAndShowData(ins, beginTime, num):
	dics = GetMarketData(ins, beginTime, num)
	datas = []
	i = 1
	for item in dics:
		data = []
		data.append(i)
		i = i + 1
		data.append(item['openPrice'])
		data.append(item['closePrice'])
		data.append(item['highPrice'])
		data.append(item['lowPrice'])
		datas.append(data)

	fig = plt.figure(figsize = (18, 9))
	ax = fig.add_subplot(211)
	candlestick(ax, datas, width = 0.4, colorup = 'r', colordown = 'g')
	ax.autoscale_view()

	volumeX = fig.add_subplot(212)
	datas = []
	index = []
	i = 1
	for item in dics:
		index.append(i)
		i = i + 1
		datas.append(item['volume'])
	volumeX.set_xlim(0, num)
	plt.bar(index, datas, 0.5, color = 'r', label = '成交量')
		
	plt.show()
开发者ID:ckl1202,项目名称:Getow,代码行数:31,代码来源:showDataUI.py

示例5: plot_chart

def plot_chart(*tfs, norm=True, realtime=True, markers = None):
    import matplotlib.dates as mdt
    fig, ax = plt.subplots()
    if len(tfs) == 1 and norm is True:
        y = [(mdt.date2num(candle.DateTime), candle.Open, candle.Close, candle.High, candle.Low) for candle in tfs[0].container]
        candlestick(ax, y, width=0.4, colorup='r', colordown='b')
        ax.xaxis_date()
        plt.title(tfs[0].symbol + " chart")
        if markers is not None:
            marker_y, marker_x = [], []
            for elem in tfs[0].container:
                if elem.DateTime in markers:
                    marker_y.append(.5*(elem.Open+elem.Close))
                    marker_x.append(mdt.date2num(elem.DateTime))
            plt.plot(marker_x, marker_y, 'gD')
    else:
        for tf in tfs:
            if realtime is True:
                x = tf.get_Time_list()
            else:
                x = range(len(tf))
            y = np.array(tf.get_C_list())
            if norm is True:
                y -= y.min()
                y /= y.max()
            plt.plot(x, y, label=tf.symbol)
            plt.title("Charts graph")
    plt.legend(loc='upper center', shadow=True)
    plt.xlabel("Time")
    plt.ylabel("Price")
    plt.grid()
    plt.show()
开发者ID:866,项目名称:PyFx,代码行数:32,代码来源:plotting.py

示例6: showCandles

def showCandles(stock, days):
    quotes = []
    prices = stock.prices[len(stock.prices)-days:]
    for day in prices:
        date = map(int,tuple(day['date'].split('-')))
        date = date2num(datetime.date(*date))
        quotes.append((date, float(day['open']), float(day['close']),float(day['high']),float(day['low'])))

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays    = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12
    
    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)
    
    candlestick(ax, quotes, width=0.6)

    ax.xaxis_date()
    ax.autoscale_view()
    setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    show()
开发者ID:kirai,项目名称:algorithmic-trading,代码行数:28,代码来源:graphs.py

示例7: candlePlot

 def candlePlot(self,ax,quotes, width=0.6,colorup='r', colordown='g',alpha=0.5): 
     if sys.version > '3':
         PY3 = True
     else:
         PY3 = False   
         
     if (PY3 == True):        
         mpf.candlestick_ohlc(ax, quotes, width,colorup, colordown,alpha)
     else:        
         #opens, closes, highs, lows,
         time  = quotes[:,0]
         opens = quotes[:,1]
         closes= quotes[:,4]
         highs = quotes[:,2]
         lows  = quotes[:,3]    
         quotesNew = np.vstack((time,opens,closes,highs,lows))
         mpf.candlestick(ax, quotesNew.T, width,colorup, colordown,alpha)
     ax.xaxis_date()
     ax.autoscale_view()
     #self.addText(ax,quotes[:,0],quotes[:,4])
     for label in ax.xaxis.get_ticklabels():
         label.set_color("red")
         label.set_rotation(30)
         label.set_fontsize(12)   
     ax.grid(True)        
开发者ID:UpSea,项目名称:midProjects,代码行数:25,代码来源:mplCandleWidget.py

示例8: buildgraph

    def buildgraph(self):
        
        left, width = 0.1, 0.9
        rect1 = [left, 0.05, width, 0.99]
        size = len(self.mts.getData()) * 0.2
        if size >= 32768:
            size = 31767
        fig = figure(figsize = (size, 10))
        
        axescolor  = '#f6f6f6'
        
        ax = fig.add_axes(rect1, axisbg=axescolor)  #left, bottom, width, height

        # build the series for candles

        M = []
        ts = self.mts.getData()#[0:self.graphperiod]
        t = len(self.mts.getData())
        for i in ts:
            M.insert(0, (t, i[0], i[3], i[1], i[2], 0))
            t -= 1

        candlestick(ax, M, width=0.6)

        M1 = []
        M2 = []
        M3 = []
        t2 = 1
        for i in ts:
            if i[4] == None or i[5] == None:
                t2 += 1
            else:
                M1.insert(0, i[4] + self.K2 * i[5])
                M2.insert(0, i[4])
                M3.insert(0, i[4] - self.K * i[5])

        date=range(t2+t,t+t2+len(M1))
        ax.plot(date, M1)
        ax.plot(date, M2)
        ax.plot(date, M3)

        for i in self.open:
            if i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='cyan')

        for i in self.close:
            if i[2] == "stoploss" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='red')
            elif i[2] == "stopgain" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='green')
            elif i[2] == "timeout(open)" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='blue')
            elif i[2] == "timeout(close)" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='blue')

        now = datetime.today().strftime("-%Y-%m-%d-%H-%M-%S");

        filename = "./charts/" + sys.argv[1] + "/" + sys.argv[1] + now + ".png"
        fig.savefig(filename)
开发者ID:dm04806,项目名称:systemn,代码行数:59,代码来源:strat1.py

示例9: candlestick

 def candlestick(self, df, width=0.3):
     """
     """
     xax = np.arange(len(df.index))
     quotes = izip(xax, df.open, df.close, df.high, df.low)
     ax = self.ax
     self.df = df
     self.setup_datetime(df.index)
     candlestick(ax, quotes, width=width, colorup="g")
开发者ID:coffeecoco,项目名称:PythonSystemAdminTools,代码行数:9,代码来源:plottingCandleSticks.py

示例10: gpcs_trade

def gpcs_trade(series, trade):
    """Function to plot a candle graph from a given series"""
    
    """takes as input the security code, default TY"""
    from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
         DayLocator, MONDAY
    from matplotlib.finance import quotes_historical_yahoo, candlestick,\
         plot_day_summary, candlestick2
    
    
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    
    alldays    = DayLocator()              # minor ticks on the days
    monthFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12


    #quotes contains a list of tuples:
    #(date, open, close, high, low, volume)
    quotes = series
    if len(quotes) == 0:
        today = datetime.datetime.now()
        
        date2 = (today.year, today.month, today.day)
        date1 = ( today.year -1, today.month, 1)
        quotes = quotes_historical_yahoo('fut_code', date1, date2)
    if len(quotes) == 0:
        raise SystemExit

    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    #ax.xaxis.set_major_locator(mondays)
    #ax.xaxis.set_minor_locator(mondays)
    #ax.xaxis.set_major_formatter(monthFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    dt, o, c, h, l, v = zip(*quotes)
    dt2 = []
    for d in dt:
        dt2.append(datetime.datetime.fromordinal(int(d)))
    ser = DataFrame(data = {0:o, 1:c, 2:h, 3:l, 4:v}, index = dt2)
    tmdelta = len(ser[trade.trend.a:])
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg, (tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='r', linestyle='-', linewidth=2)
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg+trade.trend.stdev_p_reg, (trade.trend.stdev_p_reg +tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='g', linestyle='-', linewidth=2)
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg-trade.trend.stdev_p_reg, (-trade.trend.stdev_p_reg +tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='g', linestyle='-', linewidth=2)
    tmdelta = len(ser[trade.trend.a:trade.trend.e])
    ax.plot([trade.trend.a, trade.trend.e], [trade.trend.c_reg, (tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='b', linestyle='-', linewidth=2)
    
    candlestick(ax, quotes, width=0.6)

    #ax.xaxis_date()
    ax.autoscale_view()
    setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    show()
开发者ID:richardpeter3,项目名称:robo_pleb,代码行数:57,代码来源:gpc.py

示例11: plot

 def plot(self, mplSubplot, dateTimes, color):
     if self.__useCandleSticks:
         values = []
         for dateTime in dateTimes:
             bar = self.getValue(dateTime)
             values.append((dates.date2num(dateTime), bar.getOpen(), bar.getClose(), bar.getHigh(), bar.getLow()))
         finance.candlestick(mplSubplot, values, width=0.5, colorup="g", colordown="r")
     else:
         Series.plot(self, mplSubplot, dateTimes, color)
开发者ID:AlexColson,项目名称:pyalgotrade,代码行数:9,代码来源:plotter.py

示例12: showTrade

    def showTrade(self, position, instrumentName):
        #beforeBars = 300
        #afterBars = 100

        #barsNum = beforeBars + afterBars + (position.closeTime - position.openTime).seconds * 60
        secondsBeforeTrade = 60 * 60
        secondsAfterTrade = 60
        from datetime import timedelta
        data = self.getHistoryBarsByTime(instrumentName, position.openTime - timedelta(seconds=secondsBeforeTrade), position.closeTime + timedelta(seconds=secondsAfterTrade))

        from matplotlib.finance import candlestick


        fig = figure()
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        data = self.quotesToCandlestick(data)

        from matplotlib.lines import Line2D
        from matplotlib.dates import date2num
        color = 'red'
        if position.order.orderType is 1:
            color='green'

        candlestick(ax, data, width=0.00006, colorup='g', colordown='r')

        enter = Line2D(
        xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.openPrice, position.closePrice),
        color=color,
        linewidth=5,
        antialiased=True,
        )

        if position.order.target is not 0:
            tp = Line2D(
            xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.order.target, position.order.target),
            color='g',
            linewidth=0.5,
            antialiased=True,
            )
            ax.add_line(tp)

        if position.order.stop is not 0:
            sl = Line2D(
            xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.order.stop, position.order.stop),
            color='r',
            linewidth=0.5,
            antialiased=True,
            )
            ax.add_line(sl)


        ax.add_line(enter)
        ax.autoscale_view()

        show()
开发者ID:forregg,项目名称:cbTester,代码行数:56,代码来源:tester.py

示例13: plotStats

def plotStats():
	#columns: time, opening, close, high, low
	candlestick_data = 5 
	quotes = [(0, 103.62, 102.01, 103.62, 101.90),
          (1, 102.24, 102.90, 103.16, 102.09),
          (2, 100.89, 102.59, 102.86, 100.51)]

	fig, ax = plt.subplots()	
	candlestick(ax, quotes, width=0.5, colorup='g', colordown='r')
	plt.show()
开发者ID:agacia,项目名称:crowds,代码行数:10,代码来源:plotGraph.py

示例14: graphDataCandlestick

def graphDataCandlestick(ticker, date, openp, highp, lowp, closep, volume, intradata):
    fig = plt.figure() # facecolor='#07000d'
    
    ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4) #, axisbg='#07000d'
    candlestick(ax1, intradata[-len(intradata):], width=.0005, colorup='#53c156', colordown='#ff1717')
    #plot_day_summary2_ochl(ax1, openp, closep, closep, lowp, ticksize=4, colorup='k', colordown='r')
    
    # CUSTOMIZE AXES 1
    ax1.grid(True)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.set_ylim(0.75 * lowp.min(), 1.25 * highp.max())
    plt.ylabel('Stock price and Volume')
    
    # Colors
    ax1.yaxis.label.set_color('w')
    ax1.spines['bottom'].set_color('#5998ff')
    ax1.spines['left'].set_color('#5998ff')
    ax1.spines['right'].set_color('#5998ff')
    ax1.spines['top'].set_color('#5998ff')
    ax1.tick_params(axis='y', colors='w')
    ax1.tick_params(axis='x', colors='w')
    
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    
    volumeMin = 0
    
    ax1v = ax1.twinx()
    ax1v.axes.yaxis.set_ticklabels([])
    ax1v.grid(False)
    ax1v.set_ylim(0, 3*volume.max())
    ax1v.axes.yaxis.set_ticklabels([])
    
    # Colors
    ax1v.spines['bottom'].set_color('#5998ff')
    ax1v.spines['left'].set_color('#5998ff')
    ax1v.spines['right'].set_color('#5998ff')
    ax1v.spines['top'].set_color('#5998ff')
    ax1v.tick_params(axis='y', colors='w')
    ax1v.tick_params(axis='x', colors='w')
    ax1v.bar(date, volume, color='w', width=.0005)
    
    #ax2 = plt.subplot2grid((4,4), (5,0), rowspan=2, colspan=4) # 3 rows down
    
    #ax2.grid(True)
    #plt.ylabel('Volume')
    
    # Formats the plot
    plt.subplots_adjust(left=.09, bottom=.18, right=.94, top=.95, wspace=.20, hspace=0)
    plt.setp(ax1.get_xticklabels(), visible=True)
    plt.xlabel('Date')
    
    plt.show()
开发者ID:justinoliver51,项目名称:WebExtensions,代码行数:54,代码来源:GraphHistoricalData.py

示例15: graphData

def graphData(datafile, MA1, MA2):

    def bytedate2num(fmt):
        def converter(b):
            return mdates.strpdate2num(fmt)(b.decode('utf8'))
        return converter

    datep, openp, highp, lowp, closep, volume = \
        np.loadtxt(datafile, unpack=True , usecols=(0,2,3,4,5,6), \
                converters={ 0: bytedate2num("%Y-%m-%d")})

    candleAr = []
    #while x < y:
    for x in range(len(datep)):
        appendLine = datep[x],openp[x],closep[x],highp[x],lowp[x],volume[x] #highp[x],lowp[x],closep[x],volume[x]
        candleAr.append(appendLine)
    #print (candleAr)

    AV1 = movingaverage(closep, MA1)
    AV2 = movingaverage(closep, MA2)
    SP = len(datep[MA2-1:])

    fig = plt.figure()
    ax1 = plt.subplot2grid((5,4),(0,0),rowspan=4, colspan=4)
    candlestick(ax1, candleAr, width=0.5, colorup='g', colordown='r')

    ax1.plot(datep[-SP:],AV1[-SP:])
    ax1.plot(datep[-SP:],AV2[-SP:])

    #ax1.plot(datep, openp)
    #ax1.plot(datep, highp)
    #ax1.plot(datep, lowp)
    #ax1.plot(x=datep, y=closep)
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.ylabel('Stock price')
    ax1.grid(True)

    ax2 = plt.subplot2grid((5,4),(4,0), sharex=ax1, rowspan=1, colspan=4)
    ax2.bar(datep, volume)
    ax2.axes.yaxis.set_ticklabels([])
    plt.ylabel('Volume')
    ax2.grid(True)

    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(45)

    plt.subplots_adjust(left=.10,bottom=.19,right=.93,top=.95, wspace=.20, hspace=.07)
    plt.xlabel('Date')
    plt.suptitle('GAZP')
    plt.setp(ax1.get_xticklabels(), visible=False)
    #fig.savefig('example.png')
    plt.show()
开发者ID:axce1,项目名称:anypython,代码行数:53,代码来源:alor.py


注:本文中的matplotlib.finance.candlestick函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。