股票均线和K线

本文通过使用Python的数据分析库Pandas及绘图库Matplotlib,从Yahoo Finance获取SPY股票的历史数据,并绘制了收盘价、30日及10日移动平均线图表,同时展示了OHLC蜡烛图。
# -*- coding: utf-8 -*-
"""
Created on Sun Apr  9 14:02:16 2017

@author: Administrator
"""

from __future__ import print_function, division  
import numpy as np  
import pandas as pd  
import datetime as dt  
import pandas_datareader.data as web

import matplotlib.finance as mpf  
import matplotlib.dates as mdates  
import matplotlib.mlab as mlab  
import matplotlib.pyplot as plt  
import matplotlib.font_manager as font_manager  

starttime = dt.date(2017,3,1)  
endtime = dt.date.today()  
ticker = 'SPY'  

fh = mpf.fetch_historical_yahoo(ticker, starttime, endtime)  

r = mlab.csv2rec(fh); fh.close()  
r.sort()  

df = pd.DataFrame.from_records(r)  

quotes = mpf.quotes_historical_yahoo_ohlc(ticker, starttime, endtime)  

fig, (ax1, ax2) = plt.subplots(2, sharex=True)  

tdf = df.set_index('date')  
cdf = tdf['close']  
cdf.plot(label = "close price", ax=ax1)  
pd.rolling_mean(cdf, window=30, min_periods=1).plot(label = "30-day moving averages", ax=ax1)  
pd.rolling_mean(cdf, window=10, min_periods=1).plot(label = "10-day moving averages", ax=ax1)  
ax1.set_xlabel(r'Date')  
ax1.set_ylabel(r'Price')  
ax1.grid(True)  
props = font_manager.FontProperties(size=10)  
leg = ax1.legend(loc='lower right', shadow=True, fancybox=True, prop=props)  
leg.get_frame().set_alpha(0.5)  
ax1.set_title('%s Daily' % ticker, fontsize=14)  

mpf.candlestick_ohlc(ax2, quotes, width=0.6)  
ax2.set_ylabel(r'Price')  

for ax in ax1, ax2:  
    fmt = mdates.DateFormatter('%m/%d/%Y')  
    ax.xaxis.set_major_formatter(fmt)  
    ax.grid(True)  
    ax.xaxis_date()  
    ax.autoscale()  

fig.autofmt_xdate()  
fig.tight_layout()  
plt.setp(plt.gca().get_xticklabels(), rotation=30)  
plt.show()  

fig.savefig('SPY.png')  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值