Search code examples
pythonpandasyfinance

Need help creating a new column with pandas. SMA


I'm interested in programming python with finance. I've been following this tutorial https://youtu.be/myFD0np9eys, and have got stuck at minute 17 of the video when he tries adding a moving average column. I follow the exact code but get the error: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access df.smaString=df.iloc[:,4].rolling(window=ma).mean()

Here is my code:

import yfinance as yf

import datetime as dt
from pandas_datareader import data as pdr

yf.pdr_override()

stock=input("Enter a stock ticker symbol: ")
print(stock)

startyear=2022
startmonth=1
startday=1

start=dt.datetime(startyear,startmonth,startday)

now=dt.datetime.now()

df=pdr.get_data_yahoo(stock,start,now)

print(df)

ma=50

smaString="Sma_"+str(ma)

df.smaString=df.iloc[:,4].rolling(window=ma).mean()

df=df.iloc[ma:]

print(df)

Solution

  • The reason for the error is that the way the new column name was done was wrong. I think [] is necessary to use a string variable as the new column name.

    smaString="Sma_"+str(ma)
    df[smaString] = df.iloc[:,4].rolling(window=ma).mean()
    
             Open   High    Low     Close   Adj Close   Volume  Sma_50
    
    Date                            
    2021-03-16  125.699997  127.220001  124.720001  125.570000  124.987122  115227900   129.172046
    2021-03-17  124.050003  125.860001  122.339996  124.760002  124.180885  111932600   129.083321
    2021-03-18  122.879997  123.180000  120.320000  120.529999  119.970512  121229700   128.878586
    2021-03-19  119.900002  121.430000  119.680000  119.989998  119.433022  185549500   128.750759
    2021-03-22  120.330002  123.870003  120.260002  123.389999  122.817245  111912300   128.604747