【问题标题】:12 month moving average from python来自 python 的 12 个月移动平均线
【发布时间】:2020-12-02 03:09:17
【问题描述】:
df_close['MA'] = df_close.rolling(window=12).mean()

我一直收到这个错误,谁能帮忙

ValueError: Wrong number of items passed 20, placement implies 1

我的任务:

  1. 从雅虎财经中提取任意 20 只股票的 20 年月度股价和交易量数据。
  2. 计算每只股票的月收益和 12 个月移动平均线。

其他部分代码:

start = dt.datetime(2000,1,1)
end = dt.datetime(2020,2,1)

df = web.DataReader(['AAPL', 'MSFT', 'ROKU', 'GS', 'GOOG', 'KO', 'ULTA', 'JNJ', 'ZM', 'AMZN', 'NFLX', 'TSLA', 'CMG', 'ATVI', 'LOW', 'BA', 'SYY', 'SNAP', 'BYND', 'OSTK'], 'yahoo',start,end)

df['Adj Close']
df['Volume']

data1 = df[['Adj Close', 'Volume']].copy()
data1['date1'] = data1.index
print(data1)

data2 = data1.merge(data1, left_on='date1', right_on='date1')
data2

df.sort_index()
df

df_monthly_returns = df['Adj Close'].ffill().pct_change()
df_monthly_returns.sort_index()
print(df_monthly_returns.tail())

df_close['MA'] = df_close.rolling(window=12).mean()
df_close ```

【问题讨论】:

  • 你能提供更多细节吗?喜欢您的数据框样本和您想要的输出?
  • 开始 = dt.datetime(2000,1,1) 结束 = dt.datetime(2020,2,1)
  • df = web.DataReader(['AAPL', 'MSFT', 'ROKU', 'GS', 'GOOG', 'KO', 'ULTA', 'JNJ', 'ZM' , 'AMZN', 'NFLX', 'TSLA', 'CMG', 'ATVI', 'LOW', 'BA', 'SYY', 'SNAP', 'BYND', 'OSTK'], '雅虎',开始,结束)df.tail(100)
  • @ibrahimjaafil 将有关 cmets 的详细信息添加到问题本身,编辑您的问题
  • 我拉了20年的月股价和交易量。我计算了每月回报,但我无法计算它一直给我这个错误的移动平均线

标签: python pandas


【解决方案1】:

ValueError:错误的项目数通过了 20,位置意味着 1 意味着您试图在更小的空间中放置太多元素。

df_close['MA'] = df_close.rolling(window=12).mean()

您将 20 个“事物”推入一个只允许一个容器的容器中。

因此,如果您想将具有 20 个“列”的元素放入单个数据框列中,请尝试遍历 df_close.rolling(window=12).mean() 并存储在 df_close['MA'] 中。

请用更多代码更新您的问题,以便我可以为您提供准确的解决方案。

【讨论】:

  • 如何构建 20 只股票的等权组合?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2016-07-07
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
相关资源
最近更新 更多