如何在两个不同的窗口和一个窗口中绘制S& P500及其SMA

时间:2017-09-20 12:20:06

标签: python-3.x

我尝试使用下拉代码在两个不同的窗口中绘制S& P500及其SMA。但似乎它不能很好地运作。如果我只绘制其中一个,那就没关系。

import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as pyplot
import talib
import pandas as pd
import numpy as np

start = datetime.datetime(2002, 1, 1)

## S&P 500
sp500 = web.DataReader("SP500", "fred", start)
head = sp500[-100:].dropna()
print(len(head))
## Transform DataFrame to nparray
my_array = head.as_matrix()
## Transform column to row
x = my_array.T[0]
## Get rid off the NaN
y = x[~np.isnan(x)] 
print(len(y))
## Compute SMA
my_sma=talib.SMA(y, timeperiod=5)
print(len(my_sma))

## Plot
pyplot.figure(1)
pyplot.subplot(211) ## upper window
head.plot(use_index=False)

pyplot.subplot(212)  ## lower window
pd.Series(my_sma).plot(use_index=False)

这是密谋。

此外,我想在同一个窗口中绘制它们,即oberlay。

enter image description here

很抱歉,我必须更改我的代码,以便它更加完善,人们可以更好地理解我的意思。

start = datetime.datetime(2002, 1, 1)

def computeSMA(data):
    head = data[-100:].dropna()
    ## Transform column to row
    x = head.as_matrix().T[0]
    ## Get rid off the NaN
    y = x[~np.isnan(x)] 
    ## Compute SMA
    my_sma=talib.SMA(y, timeperiod=5)

    return my_sma

## S&P 500
sp500 = web.DataReader("SP500", "fred", start)
sp_sma = computeSMA(sp500)

## Plot
pyplot.figure(1)
sp500[-100:].dropna().plot()

pyplot.figure(2)
pd.Series(sp_sma).plot(use_index=False)

如果我运行代码,我收到如下错误:

File "C:\Users\Administrator\Anaconda3\lib\site-packages\matplotlib\dates.py", line 401, in num2date
return _from_ordinalf(x, tz)

File "C:\Users\Administrator\Anaconda3\lib\site-packages\matplotlib\dates.py", line 254, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)

ValueError: ordinal must be >= 1

如果我对图(2)的情节进行评论,我会得到的情节显示2

enter image description here

如果我对图(1)的绘图进行评论,我会得到显示的3

enter image description here

此外,我想在同一图上绘制SP500及其SMA,并在X轴上绘制日期。

1 个答案:

答案 0 :(得分:0)

在同一个图上绘制两个系列(请注意,这适用于任意数量的时间序列):

import pandas as pd
import matplotlib.pyplot as pyplot

# Generate sample series (in your case these are s1=head and s2=pd.Series(my_sma) 
s1 = pd.Series([1, 3, 8, 10])
s2 = pd.Series([2, 4, 9, 11])

# Create the plot.
pyplot.figure()
pyplot.plot(s1)
pyplot.plot(s2)
pyplot.show()

结果:

enter image description here