用Matplotlib绘制股票每月最高收盘价曲线

这是《用Python玩转数据》第4周的编程小练习。目的是绘制Microsoft和INTEL公司,2014年,每个月的最高收盘价的曲线。不计分,而且老师也给出了答案,所以我在这里贴出自己的作业应该不会侵权吧。

from matplotlib.finance import quotes_historical_yahoo_ohlc
from datetime import date
import pandas as pd
import matplotlib.pyplot as plt

start_date = (2014, 1, 1)
end_date = (2015, 1, 1)
MS_date = []
INTEL_date = []
MS_month = []
INTEL_month = []

quotes_MS = quotes_historical_yahoo_ohlc('MSFT', start_date, end_date)
quotes_INTEL = quotes_historical_yahoo_ohlc('INTC', start_date, end_date)
fields = ['date', 'open', 'close', 'high', 'low', 'volume']

#把日期原始格式转换成标准格式输出. 分别转换2支股票以避免停牌的影响
for i in xrange(len(quotes_MS)):
    x = date.fromordinal(int(quotes_MS[i][0]))
    y = date.strftime(x, '%Y-%m-%d')
    MS_date.append(y)
    MS_month.append(x.month)

for i in xrange(len(quotes_INTEL)):
    x = date.fromordinal(int(quotes_INTEL[i][0]))
    y = date.strftime(x, '%Y-%m-%d')
    INTEL_date.append(y)
    INTEL_month.append(x.month)

quotesdf_MS = pd.DataFrame(quotes_MS, index = MS_date, columns = fields)
quotesdf_INTEL = pd.DataFrame(quotes_INTEL, index = INTEL_date, 
                              columns = fields)
quotesdf_MS = quotesdf_MS.drop('date', axis = 1)                              
quotesdf_INTEL = quotesdf_INTEL.drop('date', axis = 1)   
quotesdf_MS['month'] = pd.Series(MS_month, index = quotesdf_MS.index)
quotesdf_INTEL['month'] = pd.Series(INTEL_month, index = quotesdf_INTEL.index)

mclose_MS = quotesdf_MS.groupby('month').max().close
mclose_INTEL = quotesdf_INTEL.groupby('month').max().close

#使用更漂亮的模板
with plt.style.context('fivethirtyeight'):
    plt.plot(mclose_MS.index, mclose_MS.values, color = 'blue', marker = 'o',
             label = 'Microsoft')
    plt.plot(mclose_INTEL.index, mclose_INTEL.values, color = 'green', 
             marker = '*', label = 'Intel')
    #生成图例并指定图例位置。本例中loc='best'和loc='upper left'效果相同
    plt.legend(loc = 'best')
    plt.title('Max Close of MS and INTEL')

plt.show()
#plt.savefig('MS_INTEL_quotes.png')    

输出的图片如下:
用Matplotlib绘制股票每月最高收盘价曲线_第1张图片

你可能感兴趣的:(python,python,matplotlib,编程,股票,yahoo)