有条件的列信号

时间:2018-11-30 20:20:11

标签: python pandas quantitative-finance

从雅虎财经下载ohlcv for nvidia, 我正在创建一个用于信号购买/不买入的列,当我尝试定义通过avg> volume test的测试时,所有结果全部变为“买入”或不购买。

df=pd.read_csv('NVDA.csv',dtype={'label':str})
df['Price%delta']=((df['Close']/df['Open'])*100)                       

df['Avg_volume']=df['Volume'].rolling(7).mean()

df['Signal']=0

for index, row in df.iterrows():
    if row['Volume'] > row['Avg_volume']:
    df['Signal']='Buy'
    else:
        df['Signal']='Dont Buy'

3 个答案:

答案 0 :(得分:1)

您没有指定要分配'Buy''Don't buy'的索引。请改用loc

for index, row in df.iterrows(): 
    if row['Volume'] > row['Avg_volume']:
        df.loc[index, 'Signal']='Buy'
    else:
        df.loc[index, 'Signal']='Dont Buy'

答案 1 :(得分:1)

您根本不需要for循环:

mask = df["Volume"] > df["Avg_volume"] 

df.loc[mask, "Signal"] = "Buy"
df.loc[~mask, "Signal"] = 'Don't buy'

答案 2 :(得分:1)

使用np.where()的矢量化解决方案:

df['Signal'] = np.where(df['Volume'] > df['Avg_volume'], 'Buy', 'Dont Buy')