#1. 导入所有需要的包
import pandas as pd
import pandas_datareader.data as pdr
import matplotlib.pyplot as plt
from datetime import datetime
#2. 定义股票代码字典,方便查询
gafataDict={'谷歌':'GOOG','亚马逊':'AMZN','Facebook':'FB',
'苹果':'AAPL','阿里巴巴':'BABA'}
#3. 因yahoo财经关闭API,因此从Remote Data Access选择了morningstar源获取数据
# 查询起始时间
start = datetime(2018, 1, 1)
# 查询截止时间
end = datetime(2018, 4, 28)
# 获取数据
googleDf = pdr.DataReader(gafataDict['谷歌'], 'morningstar', start, end)
amazonDf = pdr.DataReader(gafataDict['亚马逊'], 'morningstar', start, end)
fbDf = pdr.DataReader(gafataDict['Facebook'], 'morningstar', start, end)
appleDf = pdr.DataReader(gafataDict['苹果'], 'morningstar', start, end)
aliDf = pdr.DataReader(gafataDict['阿里巴巴'], 'morningstar', start, end)
#4. 查看数据
print(googleDf.head()); print()
print(amazonDf.head()); print()
print(fbDf.head()); print()
print(appleDf.head()); print()
print(aliDf.head())
#5.修改数据格式
#源数据用Symbol和Date两列作为索引,影响了后面数据合并,因此重置为默认索引。
google = googleDf.reset_index()
amazon = amazonDf.reset_index()
fb = fbDf.reset_index()
apple = appleDf.reset_index()
ali = aliDf.reset_index()
#6. 抽取各个DataFrame的Close列并合并为一个DataFrame,加上Date作为索引,方便之后制图
close_collect_df = pd.concat([google['Date'], google['Close'], amazon['Close'], fb['Close'], apple['Close'], ali['Close']], axis=1)
close_collect_df.columns = ['Date', 'GOOGLE', 'AMAZON', 'FB', 'APPLE', 'Ali']
close_collect_df.set_index('Date', inplace=True)
close_collect_df.head()
#7. 绘制收盘价折线图
#因Google和Amazon股价较接近,FB、Apple和阿里股价较接近,因此分为两个图更加清晰。
close_collect_df[['GOOGLE', 'AMAZON']].plot(figsize=(16, 5), grid=True, use_index=True)
close_collect_df[['FB', 'APPLE', 'Ali']].plot(figsize=(16, 3), grid=True, use_index=True)