需要帮助创建新列 pandas。形状记忆合金
Need help creating a new column with pandas. SMA
我对 python 金融编程很感兴趣。我一直在学习本教程 https://youtu.be/myFD0np9eys,但在视频的第 17 分钟尝试添加移动平均线列时卡住了。我按照确切的代码但是得到了错误:
用户警告:Pandas 不允许通过新属性名称创建列 - 请参阅 https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access
df.smaString=df.iloc[:,4].rolling(window=ma).mean()
这是我的代码:
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)
错误的原因是新列名的做法不对。我认为 [] 是使用字符串变量作为新列名称所必需的。
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
我对 python 金融编程很感兴趣。我一直在学习本教程 https://youtu.be/myFD0np9eys,但在视频的第 17 分钟尝试添加移动平均线列时卡住了。我按照确切的代码但是得到了错误: 用户警告:Pandas 不允许通过新属性名称创建列 - 请参阅 https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access df.smaString=df.iloc[:,4].rolling(window=ma).mean()
这是我的代码:
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)
错误的原因是新列名的做法不对。我认为 [] 是使用字符串变量作为新列名称所必需的。
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