股票数据分析

从雅虎财经上下载6家公司股票信息,并进行分析。

1. 获取数据

pandas_datareader.data.DataReader支持包括雅虎、谷歌在内的十数种数据来源,本篇笔记只关注来源为雅虎财经的数据。

注意:直接使用pandas_datareader.data.get_data_yahoo会出现ImmediateDeprecationError,原因是Yahoo! Finance已经不存在了,2017年Yahoo!被Verizon收购了,因此,需在终端pip install fix-yahoo-finance补丁,专门解决pandas_datareader无法yahoo金融数据的方法。

import pandas as pd
# 导入互联网数据获取包pandas_datareader,使用前需先安装pip install pandas-datareader
import pandas_datareader.data as web

# 导入补丁包fix_yahoo_finance
import fix_yahoo_finance as yf
yf.pdr_override()

获取美股直接填写股票代码即可;

获取国内股票数据的方式是:“股票代码”+“对应股市”(港股为.hk,A股为.ss),例如腾讯是港股是:0700.hk

#字典:6家公司的股票
gafataDict={'谷歌':'GOOG','亚马逊':'AMZN','Facebook':'FB',
            '苹果':'AAPL','阿里巴巴':'BABA','腾讯':'0700.hk'}

# 导入日期
import datetime
# 获取哪段时间范围的股票数据
start_date=datetime.datetime(2017,1,1)
end_date=datetime.datetime(2018,1,1)

#从雅虎财经数据源(get_data_yahoo)获取阿里巴巴股票数据
babaDf=web.get_data_yahoo(gafataDict['阿里巴巴'],start_date, end_date)

2. 观察数据

'''
每日股票价位信息
Open:开盘价
High:最高加
Low:最低价
Close:收盘价
下面我们主要关注每日的收盘价
'''
# 数据集表格头
babaDf.head()

# 数据类型
babaDf.dtypes

# 统计汇总
babaDf.describe()

# 数据集信息
babaDf.info()

3. 分析数据

a. 首先查看2017年整年股价变化及趋势

'''
定义函数
函数功能:计算股票涨跌幅=(现在股价-买入股价)/买入股价
输入参数:column是指收盘价这一列的数据
返回数据:涨跌幅
'''
def change(column):
    #买入股价
    buyprice=column[0]
    #现在股价 总共251条数据,最后一条index为250
    curprice=column[250]
    #涨跌幅
    pricechange=(curprice-buyprice)/buyprice
    if (pricechange>0):
        print('股票2017年累计上涨:',pricechange)
    elif (pricechange==0):
        print('2017年累计股票没有变化')
    else:
        print('股票2017年累计跌幅:',pricechange)
    return pricechange

# 阿里巴巴股票一年涨跌幅
change(babaDf['Close'])

import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(babaDf['Close'])
plt.title('BABA')
plt.grid(True)
股票2017年累计上涨: 0.9461624931413655

图中可以看出阿里巴巴2017年整体走势是增长的,值得投资。

b. 成交量与股价

babaDf.plot(x='Volume',y='Close',kind='scatter',title='成交量与股价的关系',grid=True)
plt.xlabel('成交量')
plt.ylabel('股价(美元)')

# 皮尔逊相关系数矩阵
babaDf.corr()

说明成交量与股价相关性不强。

c. 6只股票价格趋势比较

#下载其他5只股票信息
googDf = web.get_data_yahoo(gafataDict['谷歌'],start_date,end_date)
amznDf = web.get_data_yahoo(gafataDict['亚马逊'],start_date,end_date)
fbDf = web.get_data_yahoo('FB',start_date,end_date)
aaplDf = web.get_data_yahoo(gafataDict['苹果'],start_date,end_date)
tencentDf = web.get_data_yahoo(gafataDict['腾讯'],start_date,end_date)

# 腾讯因为是港股上市,收盘价为港币,需要换算成美元
exchange = 0.1274
tencentDf['close_dollar']=tencentDf['Close']*exchange

f,ax1 = plt.subplots()
#ax.plot(x=googDf.index,y='Close',data=googDf,label='谷歌')
babaDf.plot(x=babaDf.index,y='Close',ax=ax1,label='阿里巴巴',title='2017年GAFATA股价走势比较')
googDf.plot(x=googDf.index,y='Close',ax=ax1,label='谷歌')
amznDf.plot(x=amznDf.index,y='Close',ax=ax1,label='亚马逊')
fbDf.plot(x=fbDf.index,y='Close',ax=ax1,label='Facebook')
aaplDf.plot(x=aaplDf.index,y='Close',ax=ax1,label='苹果')
tencentDf.plot(x=tencentDf.index,y='close_dollar',ax=ax1,label='腾讯')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
ax1.legend(loc='best')
ax1.grid(True)
plt.savefig('股价趋势.png')

由于谷歌和亚马逊股价比其他四家公司股价高,放在同一坐标下其他四家公司股票走势不明显,因此,可以分成两组来比较:

ax2 = googDf.plot(x=googDf.index,y='Close',label='谷歌')
amznDf.plot(x=amznDf.index,y='Close',ax=ax2,label='亚马逊')
#x坐标轴文本
plt.xlabel('时间')
#y坐标轴文本
plt.ylabel('股价(美元)')
#图片标题
plt.title('2017年谷歌和亚马逊股价走势比较')
#显示网格
plt.grid(True)

ax3 = babaDf.plot(x=babaDf.index,y='Close',label='阿里巴巴',title='2017年4家公司股价走势比较')
fbDf.plot(x=fbDf.index,y='Close',ax=ax3,label='Facebook')
aaplDf.plot(x=aaplDf.index,y='Close',ax=ax3,label='苹果')
tencentDf.plot(x=tencentDf.index,y='close_dollar',ax=ax3,label='腾讯')
#x坐标轴文本
plt.xlabel('时间')
#y坐标轴文本
plt.ylabel('股价(美元)')
#显示网格
plt.grid(True)

d. 6只股票收盘价比较

gafata_mean = [googDf['Close'].mean(),
            amznDf['Close'].mean(),
            fbDf['Close'].mean(),
            aaplDf['Close'].mean(),
            tencentDf['close_dollar'].mean(),
            babaDf['Close'].mean()]
gafata_mean1 = pd.Series(gafata_mean,index=['谷歌','亚马逊','FB','苹果','腾讯','阿里巴巴'])
gafata_mean1.plot(kind='bar',title='收盘价平均值柱状图',grid=True)

#添加文字注释
W = range(6)
for a, b in zip(W,gafata_mean1):
    plt.text(a,b,'%.0f'%b,ha='center',va='bottom')

plt.xlabel('公司')
plt.ylabel('股价(美元)')

从股价均值来看,亚马逊和谷歌的股价均值远超过其他4个公司股价,其中亚马逊最高,其次是谷歌,最低是腾讯。

但是均值容易受极端值影响,箱线图可反映股价的分布情况:

closeDf = pd.DataFrame()
closeDf = pd.concat([closeDf,googDf['Close'],
            amznDf['Close'],
            fbDf['Close'],
            aaplDf['Close'],
            tencentDf['close_dollar'],
            babaDf['Close']],axis=1)
closeDf.columns=['谷歌','亚马逊','FB','苹果','腾讯','阿里巴巴']
closeDf.boxplot()

由上图可以看出:

1. 在亚马逊的统计值中,有部分点是outlier。结合价格走势,在10月底11月初亚马逊的股票价格增幅非常大,与箱线图吻合;

2. 谷歌和亚马逊在一年中价格波动较大,而腾讯,苹果和FB在一年中股价较集中;

3. 中位数价格比较与均值价格比较基本相同,仍然是亚马逊最高,谷歌其次,最低为腾讯。

猜你喜欢

转载自blog.csdn.net/huangxiaoyun1900/article/details/82317116