如何使用pandas和matplotlib在金融股票数据上创建趋势线

时间:2017-11-21 14:26:25

标签: python pandas matplotlib trendline

我正在尝试使用以下代码创建金融股票数据的趋势线并获取各种错误。任何建议都非常感谢。

import pandas as pd
from pandas_datareader import data
import numpy as np
import matplotlib.pyplot as plt

df = data.DataReader(name = "GHC", data_source = "google", start = "2010-01-01", end = "2017-11-01")

#reset the index
df['ID'] = " "
df.reset_index(inplace = True)
df.set_index("ID", inplace = True)
#print(df.head(10))

#create new df for plotting
data = df[['Date', 'Close']]
#print(data.head(10))

#plot stock data
x = data['Date']
y = data['Close']
plt.scatter(x, y)

#create and plot a trendline
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r--")
plt.show()

2 个答案:

答案 0 :(得分:0)

mylist = [1, 2, 3, 4, 5, 6, 7]
N = 3
cumsum, moving_aves = [0], []

for i, x in enumerate(mylist, 1):
    cumsum.append(cumsum[i-1] + x)
    if i>=N:
        moving_ave = (cumsum[i] - cumsum[i-N])/N
        #can do stuff with moving_ave here
        moving_aves.append(moving_ave)

答案 1 :(得分:0)

我提出了这个解决方案:

import pandas as pd
from pandas_datareader import data
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 25,16
from datetime import datetime
%matplotlib inline

df = data.DataReader(name = "GHC", data_source = "google", start = "2017-01-01", end = "2017-11-01")

x = list(range(0, len(df.index.tolist()), 1))
y = df['Close']

date_x = df.index

fit = np.polyfit(x,y, 1)
fit_fn = np.poly1d(fit)

plt.plot(date_x, fit_fn(x), 'k-')
plt.plot(date_x, y, 'go', ms=2)

但是现在x轴上的日期并不正确。关于如何保持2017-01-01等原始格式的任何建议?