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


Python finance.candlestick_ohlc函数代码示例

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


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

示例1: plotK

    def plotK(self,df,title='',fmt='%Y-%m-%d'):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False

        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

        dataArray= [[date2num(rev.date),rev['open'],rev['high'],rev['low'], rev['close']] for index, rev in df[:50].iterrows()]
        print(dataArray)
        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_ohlc(ax, dataArray, width=0.6)

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

        plt.title(title)
        plt.show()
开发者ID:AlexYang1949,项目名称:ttzStock,代码行数:27,代码来源:mplot.py

示例2: ohlc

def ohlc(g):
    date = []
    op = []
    hi = []
    lo = []
    cl = []
    for e in list(g)[1:]:
        lstmp = e.split(',')
        # DATE
        strl = lstmp[0]
        date.append(datetime.datetime.strptime(strl, '%d/%m/%y'))
        # OPEN
        strl = lstmp[2]
        op.append(float(strl))
        # HIGH
        strl = lstmp[3]
        hi.append(float(strl))
        # LOW
        strl = lstmp[4]
        lo.append(float(strl))
        # CLOSE
        strl = lstmp[5]
        cl.append(float(strl))

    ax = plt.subplot()
    quotes = []
    for e in zip(date2num(date), op, hi, lo, cl):
        quotes.append(e)
    candlestick_ohlc(ax, quotes, colorup='blue', colordown='black', width=0.9)
    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%y'))
    ax.grid(True, linewidth=0.3)
    plt.show()
开发者ID:burnayt,项目名称:CodeFragments,代码行数:35,代码来源:ohlc.py

示例3: candlestickGraph

def candlestickGraph(start, end, stock):
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %y')  # e.g., Jan 12016
    dayFormatter = DateFormatter('%d')

    quotes = quotes_historical_yahoo_ohlc(stock, start, end)

    if len(quotes) == 0:
        raise SystemExit
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.1)
    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_ohlc(ax, quotes, width=.6, colorup='#77d879', colordown='#db3f3f', alpha=0.65)

    ax.xaxis.set_major_locator(mticker.MaxNLocator(10))


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

    ax.xaxis_date()

    plt.setp(plt.gca().get_xticklabels(), rotation=45)

    plt.show()
开发者ID:weatherfordmat,项目名称:Financial-Systems,代码行数:31,代码来源:candlestickgraphs.py

示例4: show_candlestick

def show_candlestick(ticker, startD, endD):
    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_ohlc(ticker, startD, endD)
    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_ohlc(ax, quotes, width=0.6)

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

    plt.show()
开发者ID:harveywwu,项目名称:pyktrader,代码行数:25,代码来源:candle_graph_demo.py

示例5: drawCandle

 def drawCandle(self,ax,quotes, width=0.6,colorup='b', colordown='r',alpha=0.5,bDrawText = False): 
     '''
     ax.xaxis.set_major_locator(mpd.WeekdayLocator(mpd.MONDAY))  # major ticks on the mondays
     ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y%m%d'))  
     
     ax.xaxis.set_major_locator(mpd.MonthLocator())  # major ticks on the mondays
     ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y%m'))     
     
     
     ax.xaxis.set_minor_locator(mpd.DayLocator() )               # minor ticks on the days
     ax.xaxis.set_minor_formatter(mpd.DateFormatter('%d') )
     
     ax.xaxis.set_minor_locator(mpd.WeekdayLocator(mpd.MONDAY))               # minor ticks on the days
     ax.xaxis.set_minor_formatter(mpd.DateFormatter('%d') )     
     '''
     mpf.candlestick_ohlc(ax, quotes, width,colorup, colordown,alpha)
     ax.grid(True)
     ax.xaxis_date()
     ax.autoscale_view()
     if(bDrawText):
         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)    
开发者ID:UpSea,项目名称:ZipLineMid,代码行数:25,代码来源:Analyzer02.py

示例6: spyBenchPlot

def spyBenchPlot(m1, d1, y1, m2, d2, y2):
    """
    plot the s%p 500 index(ticker: spy) candlestick chart
    :param m1: staring month
    :param d1: starting day
    :param y1: starting year
    :param m2: ending month
    :param d2: ending day
    :param y2: ending year
    :return:
    """
    date1 = (y1, m1, d1)
    date2 = (y2, m2, d2)
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    alldays = DayLocator()  # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12

    quotes = quotes_historical_yahoo_ohlc('spy', 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)
    candlestick_ohlc(ax, quotes, width=0.6)
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.title('S&P 500 ETF')
    plt.show()
开发者ID:royang2012,项目名称:ML_summer_proj,代码行数:32,代码来源:stockPlot.py

示例7: plot_K

def plot_K(tuples, name):
    mondays = mdates.WeekdayLocator(mdates.MONDAY)  # 主要刻度
    alldays = mdates.DayLocator()  # 次要刻度
    # weekFormatter = DateFormatter(‘%b %d‘)     # 如:Jan 12
    mondayFormatter = mdates.DateFormatter("%m-%d-%Y")  # 如:2-29-2015
    dayFormatter = mdates.DateFormatter("%d")  # 如:12

    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_locator(mdates.DayLocator(bymonthday=range(1, 32), interval=30))
    ax.xaxis.set_minor_locator(mondays)

    ax.xaxis.set_major_formatter(mondayFormatter)
    # ax.xaxis.set_minor_formatter(dayFormatter)

    # plot_day_summary(ax, quotes, ticksize=3)
    mfinance.candlestick_ohlc(ax, tuples, width=0.6, colorup="r", colordown="g")

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

    ax.grid(True)
    plt.title(name)
    plt.show()
开发者ID:xiaofeima1990,项目名称:Project,代码行数:28,代码来源:demo_fin.py

示例8: plot_stock

def plot_stock(data):
    symbol = data["Symbol"][0]
    data['Date'] = data.index
    data['Date2'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
    tuples = [tuple(x) for x in data[['Date2', 'Open', 'High', 'Low', 'Adj_Close']].values]
    fig, ax = plt.subplots()
    ax.grid(True)
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
    plt.xticks(rotation=45)
    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.title("data for stock: " + symbol)
    candlestick_ohlc(ax, tuples, width=.6, colorup='g', alpha=.4)
    ax.plot(data["Date2"], data["ema_17"])
    ax.plot(data["Date2"], data["ema_43"])
    ax2 = ax.twinx()
    ax2.set_ylabel('Volume', color='r')
    ax2.set_ylim(ymax=data["Volume"].max()*5)
    ax2.bar(data["Date2"], data["Volume"])
    xmax = data.Date2.max() + 21
    xmin = data.Date2.min() - 21
    ax2.set_xlim([xmin, xmax])
    plt.close()
    return fig
开发者ID:ralphxu28,项目名称:stocks_pred,代码行数:25,代码来源:make_plot.py

示例9: plot

    def plot(self, file_name):
        figure, axes = mplot.subplots(nrows=2, ncols=1)
        figure.subplots_adjust(bottom=0.2)

        #candle stick
        k_ax = axes[0]
        k_ax.set_xticks(range(0, len(self.__datas), self.__xstep))
        k_ax.set_xticklabels([self.__datas[index]['date'] for index in k_ax.get_xticks()])
        mfinance.candlestick_ohlc(k_ax, self.__convert_k_datas(), width=0.6, colorup='r', colordown='g') 
        k_ax.xaxis_date()
        k_ax.autoscale_view()
        mplot.setp(mplot.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

        k_ax.grid(True)
        #mplot.title(self.__stock_code)

        #asset curve
        asset_ax = axes[1]
        asset_ax.set_xticks(range(0, len(self.__datas), self.__xstep))
        asset_ax.set_xticklabels([self.__datas[index]['date'] for index in asset_ax.get_xticks()])

        ind = np.arange(len(self.__datas))
        share_ax = asset_ax.twinx()
        asset_ax.plot(ind, self.__get_asset_datas(), '-', color='blue', label='asset')
        asset_ax.set_ylabel('total asset')

        share_ax.plot(ind, self.__get_shares_datas(), '-', color='magenta', label='shares')
        share_ax.set_ylabel('total share')
        asset_ax.xaxis_date()
        asset_ax.autoscale_view()
        mplot.setp(mplot.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
        asset_ax.grid(True)

        mplot.savefig(file_name)
开发者ID:sandtower,项目名称:crystalball,代码行数:34,代码来源:plot.py

示例10: plot_finance

 def plot_finance(self):
 # (Year, month, day) tuples suffice as args for quotes_historical_yahoo
     date1 = (2014, 1, 1)
     date2 = (2014, 1, 2) 
 
 
     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_ohlc('INTC', date1, date2)
     quotes = self.get_stock('3057', 12)
     if len(quotes) == 0:
         raise SystemExit
     print quotes
 
     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_ohlc(ax, quotes, width=0.6)
 
     ax.xaxis_date()
     ax.autoscale_view()
     plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
     plt.show()
开发者ID:kevin89126,项目名称:stock_trade_simulation,代码行数:32,代码来源:plot.py

示例11: plotKBarsFromPrices

def plotKBarsFromPrices(prices, pvList):
    dataList = []
    i = 1
    for price in prices:
        bar = (i, price[3], price[0], price[1], price[2])
        dataList.append(bar)
        i += 1

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)    
    #ax.xaxis_date()
    ax.autoscale_view()    
    plt.xticks(rotation=45)
    plt.yticks()
    plt.title("K bars")
    plt.xlabel("seq")
    plt.ylabel("price point")
    mpf.candlestick_ohlc(ax,dataList,width=0.5,colorup='r',colordown='green')

    if pvList is not None:
        x = range(1, len(pvList) + 1)        
        plt.plot(x, pvList)

    plt.grid()
    plt.show()
开发者ID:yiweiming-github,项目名称:playground,代码行数:25,代码来源:KbarUtils.py

示例12: 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

示例13: draw2

def draw2(data):    
    chart_width = 0.5
    fig = plt.figure()
    
    gs1 = GridSpec(4, 1)
    ax1 = plt.subplot(gs1[:-1, :])
    ax2 = plt.subplot(gs1[-1, :])
    
    locator = MonthLocator(bymonth=range(1, 13, 3))
    formatter = DateFormatter('%Y-%m')
    ax1.xaxis.set_major_locator(locator)
    #ax1.xaxis.set_major_formatter(NullFormatter())
    
    ax1.set_yscale('log')
    ax1.yaxis.set_major_locator(SymmetricalLogLocator(base=1.2, linthresh=1))
    ax1.yaxis.set_minor_locator(NullLocator())
    ax1.yaxis.set_major_formatter(ScalarFormatter())
    ax1.set_ylabel('Price')
    ax1.grid(True)
    
    quote = dataframe2quote(data)
    candlestick_ohlc(ax1, quote, width=chart_width, colorup='#ff1717', colordown='#53c156')

    
    plt.bar(data.index, data['turnoverValue'], width = 20)
    ax2.set_ylabel('Volume')
    ax2.xaxis.set_major_locator(locator)
    ax2.xaxis.set_major_formatter(formatter)
    ax2.yaxis.set_major_formatter(ScalarFormatter())
    ax2.grid(True)
    
    plt.setp(plt.gca().get_xticklabels(), rotation=90, horizontalalignment='right')
    fig.suptitle(data.iloc[0]['id'], fontsize=12)
开发者ID:zifengyu,项目名称:stock,代码行数:33,代码来源:figure.py

示例14: plot_stock_date

def plot_stock_date(symbol, start_date, end_date, tweet_volume):
	# Get the quote data from the symbol and unpack it
	quotes = pltf.quotes_historical_yahoo_ohlc(symbol, start_date, end_date)
	ds, open, highs, lows,close,  volumes = zip(*quotes)
	# Scale the labels with the amount of quotes
	if len(quotes) < 31:
		locator = DayLocator()
		weekFormatter = DateFormatter('%b %d')
	elif len(quotes) >=31 and len(quotes) < 500:
		locator = MonthLocator()
		weekFormatter = DateFormatter('%y %b')
	elif len(quotes) >= 500 and len(quotes) < 600:
		locator = MonthLocator()
		weekFormatter = DateFormatter('%b')
	else:
		locator = YearLocator()
		weekFormatter = DateFormatter('%y')
	alldays = WeekdayLocator()
	# Create the figure, axis, and locators
	fig = plt.figure(1)
	ax = plt.subplot(311)
	ax2 = plt.subplot(312)
	ax3 = plt.subplot(313)
	fig.subplots_adjust(bottom=0.2)
	ax.xaxis.set_major_locator(locator)
	ax.xaxis.set_minor_locator(alldays)
	ax.xaxis.set_major_formatter(weekFormatter)
	# Plot candlestick
	pltf.candlestick_ohlc(ax, quotes, width=0.6, colorup='g')
	# Set date and autoscale
	ax.xaxis_date()
	ax.autoscale_view()
	plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
	ax2.xaxis_date()
	ax2.autoscale_view()
	ax3.xaxis_date()
	ax3.autoscale_view()
	# Extract the volume and calculate the color for each bar
	vol = [v for v in volumes]
	vol = np.asarray(vol)
	dates = [d for d in ds]
	op = [o for o in open]
	cl = [c for c in close]
	cols = []
	for x in range(0, len(op)):
		if op[x] - cl[x] < 0:
			cols.append('g')
		else:
			cols.append('r')
	# Plot volume as red and green bars
	ax2.bar(dates, vol, width=1.0,align='center', color=cols)
	# Plot tweet volume
	tweet_volume = np.asarray(tweet_volume)
	dates = []
	for x in range(0, len(tweet_volume)):
		dates.append(ds[0] + x)
	ax3.bar(dates, tweet_volume, width=1.0, align='center')
	# Show figure
	plt.show()
开发者ID:benzemann,项目名称:TwitterStockAnalyzer,代码行数:59,代码来源:stock_data_downloader.py

示例15: drawCandleStick

def drawCandleStick(curStock,dateStrInput,interval=10):
    mpl.rcParams['font.sans-serif'] = ['SimHei'] 

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays    = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%Y-%m-%d')  # e.g., Jan 12
    dayFormatter = DateFormatter('%d')      # e.g., 12

    #starting from dates expressed as strings...
    #...you convert them in float numbers....
    indexDate=Ccomfunc.getIndexByStrDate(curStock,dateStrInput)
    Prices=[]
    for i in range(indexDate-interval,indexDate+interval):
        mplDate = date2num(datetime.strptime(curStock.dayStrList[i], "%Y/%m/%d"))
    #so redefining the Prices list of tuples... date open high lowest close
        openPrice=curStock.dayPriceOpenFList[i]
        highestPrice=curStock.dayPriceHighestFList[i]
        lowestPrice=curStock.dayPriceLowestFList[i]
        closePrice=curStock.dayPriceClosedFList[i]
        tradeVolume=curStock.dayTradeVolumeFList[i]
        Prices.append([mplDate,openPrice,highestPrice, lowestPrice, closePrice,tradeVolume])
    
    PricesArray=np.array(Prices)
    #and then following the official example. 
    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)
    candlestick_ohlc(ax, PricesArray, width=0.5,colorup='r', colordown='g')

    ax.yaxis.grid(True)
    ## add notation
    Xmark=matplotlib.dates.date2num(datetime.strptime(curStock.dayStrList[indexDate], "%Y/%m/%d"))
    Ymark=curStock.dayPriceClosedFList[indexDate]*0.5+curStock.dayPriceOpenFList[indexDate]*0.5
    ax.annotate("$", (Xmark,Ymark), xytext=(-2, 0), textcoords='offset points' )

    ax.xaxis_date()
    ax.autoscale_view()

    axVol = ax.twinx()
##
    dates = PricesArray[:,0]
    dates = np.asarray(dates)
    volume = PricesArray[:,5]
    volume = np.asarray(volume)

    # make bar plots and color differently depending on up/down for the day
    pos = PricesArray[:,1]-PricesArray[:,4]<0
    neg = PricesArray[:,1]-PricesArray[:,4]>0
    axVol.bar(dates[pos],volume[pos],color='red',width=0.5,align='center')
    axVol.bar(dates[neg],volume[neg],color='green',width=0.5,align='center')
    axVol.set_position(matplotlib.transforms.Bbox([[0.125,0.05],[0.9,0.2]]))

    plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.title(u"{} {} 20日K".format(curStock.stockID,dateStrInput),color='r')


    plt.show()
开发者ID:xuleoBJ,项目名称:stock2015,代码行数:59,代码来源:candleStickPlot.py


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