Python 用Matplotlib绘制日内OHLC图时应注意的问题

Python 用Matplotlib绘制日内OHLC图时应注意的问题,python,pandas,numpy,matplotlib,plot,Python,Pandas,Numpy,Matplotlib,Plot,我正试图绘制OHLC烛台图(1分钟)完成一天,并希望显示“小时”作为主要定位和分钟作为次要定位。 小时定位器应显示为直到数据结束 主定位器 09:00 10:00 11点等等 我无法理解我犯了什么错误,为什么时间从22:00开始,OHLC蜡烛不可见 如果你也能帮助ohlc图表上的音量叠加,那将是一个很大的帮助 在绘制图形时,我在定义极限和宽度时犯了错误。我在阅读了文档和一些测试后进行了修复,并获得了所需的输出 你介意重新上传你的文件还是类似的文件?这个链接不起作用了。我在这里也面临着类似的问题

我正试图绘制OHLC烛台图(1分钟)完成一天,并希望显示“小时”作为主要定位和分钟作为次要定位。 小时定位器应显示为直到数据结束 主定位器 09:00 10:00 11点等等

我无法理解我犯了什么错误,为什么时间从22:00开始,OHLC蜡烛不可见

如果你也能帮助ohlc图表上的音量叠加,那将是一个很大的帮助


在绘制图形时,我在定义极限和宽度时犯了错误。我在阅读了文档和一些测试后进行了修复,并获得了所需的输出


你介意重新上传你的文件还是类似的文件?这个链接不起作用了。我在这里也面临着类似的问题。谢谢
from datetime import datetime, date, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.gridspec as grd
from matplotlib.transforms import Bbox
from matplotlib.finance import candlestick_ohlc, volume_overlay3, volume_overlay
#from matplotlib.finance import candlestick
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY, HourLocator, MinuteLocator


import numpy as np
import pandas as pd


def plot_underlying_hft_data(filename):


    #Read the data and filtered out the required rows and columns
    print("Reading File.. ", filename)
    tempdata = pd.read_csv(filename, index_col = ['Date'])
    tempdata = tempdata.loc[(tempdata.index == '2016-09-16')]

    tempdata['Datetime'] =  pd.to_datetime(tempdata['Datetime'], format='%Y-%m-%d %H:%M:%S')
    print(tempdata)

    HourLocator

    hour = HourLocator()    
    minute = MinuteLocator()
    hourformatter = DateFormatter('%H:%M') 

    #tempdata['Datetime'] = tempdata['Datetime'].apply(lambda datetimevar : datetime)

    tempdata['DatetimeNum'] = mdates.date2num(tempdata['Datetime'].dt.to_pydatetime())

    quotes = [tuple(x) for x in tempdata[['DatetimeNum', 'Open', 'High', 'Low', 'Close', 'Volume']].to_records(index=False)]

    #print(quotes)    
    title_name_ohlc = 'OHLC Intraday Chart'
    #print(title_name_ohlc)
    plt.figure(figsize = (12,6))
    #plt.title(title_name_ohlc)
    ax1 = plt.subplot2grid((1,1), (0,0), axisbg='w')

    ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
    ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
    ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
    ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
    print(tempdata['DatetimeNum'].min(), tempdata['DatetimeNum'].max())
    ax1.set_ylim(bottom = tempdata['DatetimeNum'].min(), top = tempdata['DatetimeNum'].max())

    ax1.xaxis.set_major_locator(hour)
    ax1.xaxis.set_minor_locator(minute)
    ax1.xaxis.set_major_formatter(hourformatter)
    #ax1.grid(True)
    candlestick_ohlc(ax1, quotes, width=1, colorup='g', colordown='r', alpha = 1.0)
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.show()

plot_underlying_hft_data("data.csv")

        #print(tempdata.head(5))
def plot_underlying_hft_data(filename):


#Read the data and filtered out the required rows and columns
print("Reading File.. ", filename)
tempdata = pd.read_csv(filename, index_col = ['Date'])
tempdata = tempdata.loc[(tempdata.index == '2016-09-16')].tail(751)
print(tempdata.head(5))
tempdata.set_index(['Datetime'], inplace = True)
print(tempdata.head(5))

#tempdata['Datetime'] =  pd.to_datetime(tempdata['Datetime'], format='%Y-%m-%d %H:%M:%S')
#print(tempdata)

#hour = HourLocator(interval = 1)    
minute = MinuteLocator(interval = 30)
hourformatter = DateFormatter('%H:%M') 

#tempdata['Datetime'] = tempdata['Datetime'].apply(lambda datetimevar : datetime)
tempdata["Datetime"] = pd.to_datetime(tempdata.index)
tempdata.Datetime = mdates.date2num(tempdata.Datetime.dt.to_pydatetime())
#print(tempdata.head(5))

quotes = [tuple(x) for x in tempdata[['Datetime', 'Open', 'High', 'Low', 'Close', 'Volume']].to_records(index=False)]

#print(quotes)    
title_name_ohlc = 'OHLC Intraday Chart'
#print(title_name_ohlc)
plt.figure(figsize = (18,10))
#plt.title(title_name_ohlc)
ax1 = plt.subplot2grid((1,1), (0,0), axisbg='w')

ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
ax1.set_xlabel('Time', fontsize=12, fontweight = 'bold')
ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
#print(tempdata['DatetimeNum'].min(), tempdata['DatetimeNum'].max())
ax1.set_xlim(tempdata['Datetime'].min(), tempdata['Datetime'].max())

ax1.xaxis.set_major_locator(minute)
#ax1.xaxis.set_minor_locator(minute)
ax1.xaxis.set_major_formatter(hourformatter)
ax1.axhline(y=262.32, linewidth=1.5, color='g', alpha = 0.7, linestyle = "dashed")
ax1.axhline(y=260.33, linewidth=2, color='g', alpha = 0.7, linestyle = "dashed")
ax1.axhline(y=258.17, linewidth=2.5, color='g', alpha = 0.7, linestyle = "dashed")
ax1.axhline(y=256.18, linewidth=3, color='b', alpha = 1, linestyle = "dashed")
ax1.axhline(y=254.02, linewidth=2.5, color='r', alpha = 0.7, linestyle = "dashed")
ax1.axhline(y=252.03, linewidth=2, color='r', alpha = 0.7, linestyle = "dashed")
ax1.axhline(y=249.87, linewidth=1.5, color='r', alpha = 0.7, linestyle = "dashed")

#['256.18', '254.02', '252.03', '249.87', '258.17', '260.33', '262.32']
ax1.grid(True)

#ax1.grid(True)
candlestick_ohlc(ax1, quotes, width = 1/(24*60*2.5), alpha = 1.0, colorup = 'g', colordown ='r')
plt.setp(plt.gca().get_xticklabels(), horizontalalignment='center')

pad = 0.25
yl = ax1.get_ylim()
print(yl)
ax1.set_ylim(yl[0]-(yl[1]-yl[0])*pad,yl[1]*1.005)

Datetime = [x[0] for x in quotes]
Datetime = np.asarray(Datetime)
Volume = [x[5] for x in quotes]
Volume = np.asarray(Volume)

ax2 = ax1.twinx()
ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.125],[0.9,0.27]]))
width = 1/(24*60*4)
ax2.bar(Datetime, Volume, color='blue', width = width, alpha = 0.75)
ax2.set_ylim([0, ax2.get_ylim()[1] * 1])
ax2.set_ylabel('Volume', fontsize=12, fontweight = 'bold')
yticks = ax2.get_yticks()
ax2.set_yticks(yticks[::1])
#ax2.grid(True)
#report_pdf.savefig(pad_inches=0.5, bbox_inches= 'tight')
#plt.close()
plt.show()