• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python finance.candlestick_ohlc函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: graph_data

def graph_data(stock):

	fig = plt.figure()
	#ax1 = plt.subplot2grid((1,1), (0,0))
	ax1 = plt.subplot2grid((6,1), (0,0),rowspan=1,colspan=1)
	plt.title(stock)
	ax2 = plt.subplot2grid((6,1), (1,0),rowspan=4,colspan=1)
	plt.xlabel('Date')
	plt.ylabel('Price')
	ax3 = plt.subplot2grid((6,1), (5,0),rowspan=1,colspan=1)

	stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
	source_code = urllib.request.urlopen(stock_price_url).read().decode()
	stock_data = []
	split_source = source_code.split('\n')
	for line in split_source:
		split_line = line.split(',')
		if len(split_line) == 6:
			if 'values' not in line and 'labels' not in line:
				stock_data.append(line)


	date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,delimiter=',',unpack=True,converters={0: bytespdate2num('%Y%m%d')})

	x = 0
	y = len(date)
	ohlc = []

	while x < y:
		append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
		ohlc.append(append_me)
		x+=1
	
	ma1 = moving_average(closep,MA1)
	ma2 = moving_average(closep,MA2)
	start = len(date[MA2-1:])
		
	h_l = list(map(high_minus_low,highp,lowp))
	ax1.plot_date(date,h_l,'-')

	candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
	
	for label in ax2.xaxis.get_ticklabels():
		label.set_rotation(45)
	
	ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
	ax2.grid(True)
	
	bbox_props = dict(boxstyle='round',fc='w',ec='k',lw=1)

	ax2.annotate(str(closep[-1]),(date[-1],closep[-1]),xytext=(date[-1]+4, closep[-1]),bbox=bbox_props)
	print(len(date), len(ma1)) 
	ax3.plot(date[-start:],ma1[-start:])
	ax3.plot(date[-start:],ma2[-start:])
	
	plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
	plt.show()
开发者ID:byronkilbourne,项目名称:Test_MkI,代码行数:58,代码来源:matplotlib_tutorial_subplot_III.py


示例17: _candlestick_ax

def _candlestick_ax(df, ax):
    """
    # Alternatively: (but hard to get dates set up properly)
    plt.xticks(range(len(df.index)), df.index, rotation=45)
    fplt.candlestick2_ohlc(ax, df.loc[:, 'Open'].values, df.loc[:, 'High'].values, 
            df.loc[:, 'Low'].values, df.loc[:, 'Close'].values, width=0.2)
    """
    quotes = df.reset_index()
    quotes.loc[:, 'Date'] = mdates.date2num(quotes.loc[:, 'Date'].astype(dt.date))
    fplt.candlestick_ohlc(ax, quotes.values)
开发者ID:herberthudson,项目名称:pynance,代码行数:10,代码来源:chart.py


示例18: candlePlot

 def candlePlot(self,ax,quotes, width=0.6,colorup='r', colordown='g',alpha=0.5): 
     mpf.candlestick_ohlc(ax, quotes, 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,项目名称:ZipLineMid,代码行数:10,代码来源:PyQtGraphCandles02.py


示例19: Acct_mkt_candle

def Acct_mkt_candle(dealArr = [],AcctAmtArr=[],BuildPriceArr=[]):
    from matplotlib.finance import candlestick_ohlc
    datenumArr = []
    openp = []
    highp = []
    lowp=[]
    closep=[]
    volume=[]
    font = FontProperties(fname=r"c:\windows\fonts\mingliu.ttc", size=12)
    
    for a in dealArr:
        datenumArr.append(mdates.date2num(a.TradeDate))
        openp.append(a.OpenPrice)
        highp.append(a.HighPrice)
        lowp.append(a.LowPrice)
        closep.append(a.ClosePrice)
        volume.append(a.DealAmt)
        x = 0
        y = len(datenumArr)
        
    newAr = []
    while x < y:
        appendLine = datenumArr[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
        newAr.append(appendLine)
        x+=1
        
        
    fig = plt.figure(facecolor='#07000d')
    ax1 = plt.subplot2grid((3,2), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
    fig.set_size_inches(18.5, 10.5)
    candlestick_ohlc(ax1,newAr[:],width=.6,colorup='#ff1717',colordown='#53c156')
    plt.scatter(datenumArr,BuildPriceArr,s=50,marker='^',color = 'white')
    plt.xticks()
    par1 = ax1.twinx()    
    par1.plot(datenumArr[:],AcctAmtArr[:],color = "red",linewidth=1)    
    ax1.grid(True, color='w')
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.yaxis.label.set_color("w")
    par1.yaxis.label.set_color("w")
    par1.spines['right'].set_color("#5998ff")
    par1.spines['bottom'].set_color("#5998ff")
    par1.spines['top'].set_color("#5998ff")
    par1.spines['left'].set_color("#5998ff")
    ax1.tick_params(axis='y', colors='w')
    par1.tick_params(axis='y', colors='w')
    plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
    ax1.tick_params(axis='x', colors='w')
    plt.ylabel('Stock price and Volume')
    extent = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    plt.title(u"Test", fontproperties=font)
    plt.xlabel("Time")
    plt.ylabel("Hits/hour")
    plt.sca(par1)
    plt.savefig(u"test.png", format="png",bbox_inches=extent.expanded(1.1, 1.2))
开发者ID:tiomor4n,项目名称:quant_trade_python,代码行数:55,代码来源:figure_plot_output.py


示例20: draw

    def draw(self, number, length = CANDLE_FIG_LENGTH):

        reader = Reader(number)
        series = [[] for x in xrange(7)]

        # Candle Stick
        candle_sticks = []

        idx = -1
        while True:
            idx +=1 
            row = reader.getInput()
            if row == None: break
            for i in [1, 3, 4, 5, 6]:
                series[i].append(float(row[i]))
                # matplotlib 的 candlestick_ohlc 依序放入 [編號, 收盤, 最高, 最低, 開盤] 會畫出 K 線圖
            candle_sticks.append((
                idx,
                float(row[6]),
                float(row[4]),
                float(row[5]),
                float(row[3])
            ))            
            
        bool_up_series, ma_series, bool_down_series = self._getBooleanBand(series[6])
        
        # Draw Figure
        line_width = CANDLE_FIG_LINE_WIDTH
        
        fig, axarr = plt.subplots(2, sharex=True)

        candlestick_ohlc(axarr[0], candle_sticks[-length:], width=CANDLE_STICK_WIDTH)
        
        x_axis = range(len(series[6]))
        # set zorder 讓 candlestick 可以在上面
        axarr[0].plot(x_axis[-length:], ma_series[-length:], c='#00ff00', ls='-', lw=line_width, zorder=-5)
        axarr[0].plot(x_axis[-length:], bool_up_series[-length:], c='#ff0000', ls='-', lw=line_width, zorder=-4)
        axarr[0].plot(x_axis[-length:], bool_down_series[-length:], c='#0000ff', ls='-', lw=line_width, zorder=-3)
        axarr[0].plot(x_axis[-length:], series[4][-length:], c='#ff3399', ls='-', lw=line_width, zorder=-2)
        axarr[0].plot(x_axis[-length:], series[5][-length:], c='#0099ff', ls='-', lw=line_width, zorder=-1)
        
        axarr[0].set_title(self._getFigTitle(number))
        
        axarr[1].plot(x_axis[-length:], series[1][-length:], c='#000000', ls='-', lw=line_width)
        
        # set figure arguments
        fig.set_size_inches(FIGURE_WIDTH, FIGURE_HEIGHT)

        # output figure
        
        fig.savefig(CANDLE_FIG_PATH+'/'+number+'.png', dpi=FIGURE_DPI)

        plt.clf()
        plt.close('all')
        
开发者ID:copyfun,项目名称:stockflow,代码行数:54,代码来源:CandleDrawer.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python finance.fetch_historical_yahoo函数代码示例发布时间:2022-05-27
下一篇:
Python finance.candlestick函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap