[置顶] Python显示股票直线图和K线图

1. 获取数据

参见Python获取Yahoo股票数据

    fh = finance.fetch_historical_yahoo(code, start_date, end_date)
    data = mlab.csv2rec(fh)
    fh.close()
    data.sort()

2. 显示数据

2.1 显示基本数据

应用matplotlib.plyplot绘制收市数据
(1)获取收市数据

    close_data = data['close']

(2)日期数据

    date_data = data['date']

(3)绘制曲线

plt.plot(date_data, close_data)

(4)显示曲线

plt.show()

完整代码如下:

def show_data(data):
    close_data = data['close']
    plt.autoscale(True, 'both', None)
    #绘制方格
    plt.rc('axes', grid=True)
    plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)
    plt.plot(data['date'], close_data)
    #设置坐标标签
    plt.xlabel('Date')
    plt.ylabel('Close')
    #将x坐标日期进行倾斜
    plt.setp(plt.gca().get_xticklabels(), rotation=20, horizontalalignment='right')
    plt.show()

[置顶] Python显示股票直线图和K线图_第1张图片

2.2 绘制K线图
利用matplotlib.finance.candlestick函数绘制K线图
完整代码如下:

#!/usr/bin/env python
# coding=utf-8

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY,YEARLY
from matplotlib.finance import quotes_historical_yahoo, candlestick

import numpy as np

def main():
    # plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    ticker = '600028' # 600028 是"中国石化"的股票代码
    ticker += '.ss'   # .ss 表示上证 .sz表示深证

    date1 = (2015, 8, 1) # 起始日期,格式:(年,月,日)元组
    date2 = (2016, 1, 1)  # 结束日期,格式:(年,月,日)元组


    mondays = WeekdayLocator(MONDAY)            # 主要刻度
    alldays = DayLocator()                      # 次要刻度
    #weekFormatter = DateFormatter('%b %d') # 如:Jan 12
    mondayFormatter = DateFormatter('%Y-%m-%d') # 如:2-29-2015
    dayFormatter = DateFormatter('%d')          # 如:12

    quotes = quotes_historical_yahoo(ticker, 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(mondayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick(ax, quotes, 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('600028')
    plt.show()
    return

if __name__ == '__main__':
    main()

[置顶] Python显示股票直线图和K线图_第2张图片

你可能感兴趣的:(python,股票,K线图,量化投资)