蠟燭線是股票分析中常用的一種技術指標,通過蠟燭線圖可以直觀地看出股票價格的變化情況。在Python中,我們可以使用matplotlib庫來實現畫蠟燭線。
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY from mpl_finance import candlestick_ohlc import pandas as pd # 讀入數據,這里我們使用Google的股票數據 goog = pd.read_csv('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=GOOG&apikey=demo&datatype=csv') # 處理日期數據,轉化為數字 goog['date'] = pd.to_datetime(goog['timestamp']) goog['date'] = goog['date'].apply(lambda x: DateFormatter('%Y-%m-%d')(x)) goog['date'] = pd.to_datetime(goog['date']) goog['date'] = goog['date'].apply(lambda x: x.toordinal()) # 繪制蠟燭圖 mondays = WeekdayLocator(MONDAY) alldays = DayLocator() weekFormatter = DateFormatter('%b %d') dayFormatter = DateFormatter('%d') 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, zip(goog['date'], goog['open'], goog['high'], goog['low'], goog['close']), width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, ha='right') plt.show()
代碼中使用了pandas庫來讀取和處理數據,然后使用matplotlib的candlestick_ohlc()函數繪制蠟燭圖。其中,我們將日期轉化為數字,并使用WeekdayLocator和DayLocator設置X軸的坐標。最后使用plt.show()函數顯示圖形。