Python 画K 线

import pyqtgraph as pg
import matplotlib.dates as datesx
import tushare as ts
import datetime as dt
import numpy as np
from pyqtgraph import QtCore, QtGui


## Create a subclass of GraphicsObject.
## The only required methods are paint() and boundingRect() 
## (see QGraphicsItem documentation)
class CandlestickItem(pg.GraphicsObject):
    def __init__(self, data):
        pg.GraphicsObject.__init__(self)
        self.data = data  ## data must have fields: time, open, close, min, max
        self.generatePicture()
    
    def generatePicture(self):
        ## pre-computing a QPicture object allows paint() to run much more quickly, 
        ## rather than re-drawing the shapes every time.
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
       
        #w = (datesx.date2num(self.data[1][0]) - datesx.date2num(self.data[0][0])) / 3.
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            #t_int= datesx.date2num(t_date)
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('r'))
            else:
                p.setBrush(pg.mkBrush('g'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()
    
    def paint(self, p, *args):
        p.drawPicture(0, 0, self.picture)
    
    def boundingRect(self):
        ## boundingRect _must_ indicate the entire area that will be drawn on
        ## or else we will get artifacts and possibly crashing.
        ## (in this case, QPicture does all the work of computing the bouning rect for us)
        return QtCore.QRectF(self.picture.boundingRect())






hist_data = ts.get_hist_data('600519',start='2017-05-01',end='2018-03-06').sort_index()
xdict = dict(enumerate(hist_data.index))
axis_1 = [(i,list(hist_data.index)[i]) for i in range(0,len(hist_data.index),10)]


app = pg.QtGui.QApplication([])
win = pg.GraphicsWindow(title='无下坐标K线')
#win = pg.plot()


stringaxis = pg.AxisItem(orientation='bottom')
stringaxis.setTicks([axis_1,xdict.items()])


data_list = []
int_xi=0
for dates,row in hist_data.iterrows():
# 将时间转换为数字
    date_time = dt.datetime.strptime(dates,'%Y-%m-%d')
    t = datesx.date2num(date_time)
    open,high,close,low = row[:4]
    datasitem = (int_xi,open,close,low,high)
    data_list.append(datasitem)
    int_xi=int_xi+1
item = CandlestickItem(data_list)




plt =  win.addPlot(axisItems={'bottom': stringaxis},title='600519')
#plt .setLabel(axis='bottom',text='日期')
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')
plt.showGrid(x=True,y=True)


plt.plot(x=list(xdict.keys()), y=hist_data['ma5'].values, pen='r', name='5日线')
plt.plot(x=list(xdict.keys()), y=hist_data['ma10'].values, pen='g', name='10日线')
plt.plot(x=list(xdict.keys()), y=hist_data['ma20'].values, pen='b', name='20日线')


#plt.plot(x=list(xdict.keys()), y=hist_data['v_ma5'].values, pen='r', name='5日线')
#plt.plot(x=list(xdict.keys()), y=hist_data['v_ma10'].values, pen='g', name='10日线')
#plt.plot(x=list(xdict.keys()), y=hist_data['v_ma20'].values, pen='b', name='20日线')




#xax = plt.getAxis('bottom')
#xax.setTicks(axis_1)


win.nextRow()
p2 =  win.addPlot(title="Multiple curves")
p2.plot(np.random.normal(size=100), pen=(255,0,0), name="Red curve")
#p2.plot(np.random.normal(size=110)+5, pen=(0,255,0), name="Green curve")
#p2.plot(np.random.normal(size=120)+10, pen=(0,0,255), name="Blue curve")


print(list(xdict.keys()))
print(hist_data['volume'].values)
#bg1=pg.BarGraphItem(x=list(xdict.keys()), height=hist_data['volume'].values, width=0.3, brush='r')
#win.addItem(p2)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
### 如何使用 Python 绘制 K 线图 #### 方法一:基于 Matplotlib 和 Pandas 的简单实现 为了绘制简单的 K 线图,可以采用 `matplotlib.finance` 模块中的函数来完成这一操作。不过需要注意的是,在较新的版本中该模块已经被移至 `mpl_finance` 中。 ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates # 创建示例数据框 df data = {'Date': ['2023-01-%02d' % i for i in range(1, 6)], 'Open': [7.45, 7.48, 7.5, 7.52, 7.5], 'High': [7.49, 7.5, 7.55, 7.55, 7.52], 'Low': [7.43, 7.45, 7.48, 7.5, 7.48], 'Close': [7.46, 7.48, 7.52, 7.54, 7.5]} df = pd.DataFrame(data) # 将日期字符串转换成数值型时间戳 df['Date'] = pd.to_datetime(df['Date']) df['Date'] = df['Date'].apply(mdates.date2num) fig, ax = plt.subplots() candlestick_ohlc(ax, df.values, width=0.6, colorup='g', colordown='r') ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.xticks(rotation=45) plt.grid(True) plt.show() ``` 这段代码展示了如何创建一个包含 OHLC 数据的数据帧,并将其传递给 `candlestick_ohlc()` 函数以生成图表[^1]。 #### 方法二:结合 Pandas DataReader 获取真实市场行情并绘图 如果希望获取真实的股市交易日志,则可以通过第三方 API 或者本地文件加载实际的历史价格记录。这里展示了一个例子,它通过 Yahoo Finance 下载 AAPL 股票过去一年的日度收盘价: ```python import yfinance as yf import datetime import matplotlib.pyplot as plt from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates end_date = datetime.datetime.now().date() start_date = end_date - datetime.timedelta(days=365*2) ticker_symbol = "AAPL" stock_data = yf.download(ticker_symbol, start=start_date, end=end_date) stock_data.reset_index(inplace=True) stock_data["Date"] = stock_data["Date"].map(mdates.date2num) fig, ax = plt.subplots(figsize=(10, 6)) formatter = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(formatter) locator = mdates.DayLocator(interval=10) ax.xaxis.set_major_locator(locator) candlestick_ohlc(ax=ax, quotes=stock_data[['Date', 'Open', 'High', 'Low', 'Close']].values, width=.6, colorup='green', colordown='red') plt.title(f"{ticker_symbol} Candlestick Chart Over Last Two Years", fontsize=16) plt.xlabel('Date', fontsize=14) plt.ylabel('Price (USD)', fontsize=14) plt.tight_layout() for label in ax.get_xticklabels(): label.set_rotation(45) plt.grid(True) plt.show() ``` 此脚本不仅能够下载指定时间段内的历史股价信息,还能自动调整 X 轴标签以便更好地显示大量数据点[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值