-2

I am trying to create a trendline on financial stock data using the following code and getting all kinds of errors. Any suggestions are most appreciated.

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()
Mike
  • 85
  • 3
  • 7

2 Answers2

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)
Greg
  • 602
  • 2
  • 7
  • 15
0

I came up with this solution:

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)

But now the dates on the x axis don't come out right. Any suggestions on how to keep the original format of 2017-01-01 etc?

Mike
  • 85
  • 3
  • 7