蜡烛线是股票分析中常用的一种技术指标,通过蜡烛线图可以直观地看出股票价格的变化情况。在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()函数显示图形。