0

I have the below code:

import pandas as pd 
import yfinance as yf
import matplotlib.pyplot as plt
import datetime as dt

start=dt.datetime.today()-dt.timedelta(160)
end=dt.datetime.today()
clprice=pd.DataFrame(yf.download("FB MSFT AMZN GOOG GM", start=start, end=end))
clprice=clprice.dropna()
def macd(DF,a,b,c):
  df=DF.copy()
  df['MA Fast']=df['Adj Close'].ewm(span=a, min_periods=a).mean()
  df['MA Slow']=df['Adj Close'].ewm(span=b, min_periods=b).mean()
  df["MACD"]=df['MA Fast']-df['MA Slow']
  df['Signal']=df.MACD.ewm(span=c, min_periods=c).mean()
  df["Histrogram"]=df.MACD-df.Signal
  df=df.dropna()
  df.iloc[:,[4,8,9,10]].plot()
  plt.savefig("msftmacdsignal.png")
  return df


d=macd(clprice, 12,26,9)

I am trying to create a function that takes a dataframe and returns MACD and signal. when I am using a single ticker I have no problem it is giving me the appropriate results. When I am using more than one stock like in this case "FB MSFT AMZn GOOG GM" i am getting this error:

raise ValueError(
ValueError: Wrong number of items passed 5, placement implies 1
4

1 回答 1

0

我的回答是指有问题提供的代码:

import pandas as pd 
import yfinance as yf
import matplotlib.pyplot as plt
import datetime as dt

start=dt.datetime.today()-dt.timedelta(160)
end=dt.datetime.today()
clprice=pd.DataFrame(yf.download("FB MSFT AMZN GOOG GM", start=start, end=end))
clprice=clprice.dropna()
def macd(DF,a,b,c):
  df=DF.copy()
  df['MA Fast']=df['Adj Close'].ewm(span=a, min_periods=a).mean()
  df['MA Slow']=df['Adj Close'].ewm(span=b, min_periods=b).mean()
  df["MACD"]=df['MA Fast']-df['MA Slow']
  df['Signal']=df.MACD.ewm(span=c, min_periods=c).mean()
  df["Histrogram"]=df.MACD-df.Signal
  df=df.dropna()
  df.iloc[:,[4,8,9,10]].plot()
  plt.savefig("msftmacdsignal.png")
  return df

要调用单个代码,例如“FB”,我使用:

macd(clprice.xs('FB', level=1, axis=1), 12,26,9)

因此,对于多个代码,您的macd功能没有变化:

for ticker in clprice.columns.get_level_values(1).unique():
    macd(clprice.xs(ticker, level=1, axis=1), 12,26,9)

请注意列是多级的,因此get_levelvalues使用。运行上述代码后,将生成每个代码的图表。

于 2020-07-18T15:21:30.670 回答