I have a data Series which looks like this:
Date Open High Low Adj Close Change
4844 26/10/2020 3441.419922 3441.419922 3233.939941 3269.959961 -5.243488
4845 02/11/2020 3296.199951 3529.050049 3279.739990 3509.439941 6.076183
4846 09/11/2020 3583.040039 3645.989990 3511.909912 3585.149902 0.058850
4847 16/11/2020 3600.159912 3628.510010 3543.840088 3557.540039 -1.198015
4848 20/11/2020 3579.310059 3581.229980 3556.850098 3557.540039 -0.611940
I'm trying to create a new list which contains a autocorrelation coefficient for various lookback periods via a for loop. I've tried this:
import pandas as pd
Df = pd.read_csv("SP500 Weekly Data.csv", delimiter=",")
Df.fillna('')
Df['Change'] = ((Df['Adj Close'] - Df['Open']) / Df['Adj Close']*100)
for t in range(1,20):
wk = []
auto = Df['Change'].autocorr(t).astype(float)
wk.append(auto)
print(wk)
but instead of getting a list of values, all I get from the print is the last value:
[0.002519726414980291]
At first I thought it was the type of value being returned [I got an ''numpy.float64' object is not iterable' error with .extend()], but .append() doesn't appear to be adding to the list with each loop.
Any help is appreciated, as well as any advice on the mistake I've made, so I can look out for it next time! Thanks
CodePudding user response:
In your code, the wk list is being initialized empty every time, Hence you need to place it outside the loop like below for it to work.
import pandas as pd
Df = pd.read_csv("SP500 Weekly Data.csv", delimiter=",")
Df.fillna('')
Df['Change'] = ((Df['Adj Close'] - Df['Open']) / Df['Adj Close']*100)
wk = []
for t in range(1,20):
auto = Df['Change'].autocorr(t).astype(float)
wk.append(auto)
print(wk)