批量计算移动平均值并打印条件lis

2024-04-27 23:17:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份针对整个sp500的调整收盘价列表,我想计算50天sma和200天sma,并打印一份满足指定时间间隔条件的股票列表(我是一个编码新手,并且意识到这是一个巨大的混乱的工作,以消除不需要的列)

我在np.where sma>;lma,它创建了一个只有1,0的数组,没有日期和标记

df = pd.read_csv('sp500_joined_closes.csv')
df = df.copy()
df['Date'] = pd.to_datetime(df["Date"])
df.set_index('Date', inplace=True)

df = pd.concat([df, df.rolling(window = 50, min_periods=0).mean().add_prefix('50ma_')], axis=1)
df = pd.concat([df, df.rolling(window = 200, 
min_periods=0).mean().add_prefix('200ma_')], axis=1)

df = df[df.columns.drop(list(df.filter(regex='200ma_50ma_')))]

tickers = df.loc[:,df.columns]
sma = df.filter(regex='50ma_', axis = 1)
lma = df.filter(regex='200ma_', axis = 1)

sma.columns = [col.replace('50ma_','') for col in sma.columns]
lma.columns = [col.replace('200ma_','') for col in lma.columns]

signal = np.where(sma>lma, 1.0, 0.0)`

我可以得到所有移动平均值的输出。我想创建一个在指定时间间隔内满足条件的ticker列表

 print(signal)

 output:[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 1. 0. ... 1. 0. 1.]
 [0. 1. 0. ... 1. 0. 1.]
 [0. 1. 0. ... 1. 0. 1.]]`

Tags: columnsdf列表date间隔np时间col