我有一个包含股票价格的Dataframe。下面的示例,但这持续4500行股票价格
>>
DATE MMM US Equity AIR US Equity
1/3/2000 47.19 17.56
1/4/2000 45.31 17.63
1/5/2000 46.63 17.81
1/6/2000 50.38 17.94
我使用iteritems创建了移动平均线,其中包含以下
>>>for stockname, stock in df.iteritems():
# Create 10,30,50,100 and 200D MAvgs
MA10D = stock.rolling(10).mean()
MA30D = stock.rolling(30).mean()
MA50D = stock.rolling(50).mean()
MA100D = stock.rolling(100).mean()
MA200D = stock.rolling(200).mean()
df_stockname = pd.concat([df[[1]],MA10D,MA30D,MA50D,MA100D,MA200D],axis=1)
问题是这只显示循环中的最后一项(AIR US Equity股票)。如何获取循环中第一个股票的MA10D,MA30D等(即MMM美国股票,这是df中的第一只股票)。我怎么能这样做
我最终希望能够创建两个数据框,每个股票对应一个股票价格,MA10D,MA30D,MA50D,MA100D和MA200D。所以我最终需要一种方法来命名每个数据帧并更改concat中的df [[#]]。
答案 0 :(得分:0)
这是你想要做的吗?
results = {}
# Create 10,30,50,100 and 200D MAvgs
for stockname, stock in df.iteritems():
df_copy = pd.DataFrame(stock)
df_copy[stockname + '_MA10D'] = stock.rolling(10).mean()
df_copy[stockname + '_MA30D'] = stock.rolling(30).mean()
df_copy[stockname + '_MA50D'] = stock.rolling(50).mean()
df_copy[stockname + '_MA100D'] = stock.rolling(100).mean()
df_copy[stockname + '_MA200D'] = stock.rolling(200).mean()
results[stockname] = df_copy
这是一个应该执行的完整版本和结果:
data = {
'MMM': (47.19, 45.31, 46.63, 50.38),
'AIR': (17.56, 17.63, 17.81, 17.94)
}
index = pd.Index(pd.date_range("01/03/2000", "01/06/2000"), name='DATE')
df = pd.DataFrame(data=data, index=index)
results = {}
# Create 10,30,50,100 and 200D MAvgs
for stockname, stock in df.iteritems():
df_copy = pd.DataFrame(stock)
df_copy[stockname + '_MA10D'] = stock.rolling(10).mean()
df_copy[stockname + '_MA30D'] = stock.rolling(30).mean()
df_copy[stockname + '_MA50D'] = stock.rolling(50).mean()
df_copy[stockname + '_MA100D'] = stock.rolling(100).mean()
df_copy[stockname + '_MA200D'] = stock.rolling(200).mean()
results[stockname] = df_copy
print(results['MMM'])
print(results['AIR'])
输出:
MMM MMM_MA10D MMM_MA30D MMM_MA50D MMM_MA100D MMM_MA200D
DATE
2000-01-03 47.19 NaN NaN NaN NaN NaN
2000-01-04 45.31 NaN NaN NaN NaN NaN
2000-01-05 46.63 NaN NaN NaN NaN NaN
2000-01-06 50.38 NaN NaN NaN NaN NaN
AIR AIR_MA10D AIR_MA30D AIR_MA50D AIR_MA100D AIR_MA200D
DATE
2000-01-03 17.56 NaN NaN NaN NaN NaN
2000-01-04 17.63 NaN NaN NaN NaN NaN
2000-01-05 17.81 NaN NaN NaN NaN NaN
2000-01-06 17.94 NaN NaN NaN NaN NaN