简体   繁体   English

熊猫如何根据条件填充单元格

[英]pandas how to fill a cell based on if condition

I am building a backtester for my algo where i want it to fill a new column with 0 or 1 if its a buy or sell signal我正在为我的算法构建一个回测器,如果它是买入或卖出信号,我希望它用 0 或 1 填充新列

the BUY signal is generated:产生买入信号:
1-if two cells in two different columns exceeded a certain threshold [ Q5> 7 & Q7>7 ] : 1-如果两个不同列中的两个单元格超过某个阈值 [ Q5> 7 & Q7>7 ] :
fill a new col ['BuySignal'] = 1填充一个新的 col ['BuySignal'] = 1
else condition not met in rule one and rule two below fill BuySignal = 0 else 条件不满足下面的规则一和规则二填充 BuySignal = 0

2-if there is two buy signals and yet there is no sell signal after the first buy signal, dont fill BuySignal with 1, keep it 0 ( as you can see in row 6 in yellow.) we can only have one buy signal until the next sell signal 2-如果有两个买入信号,但在第一个买入信号之后没有卖出信号,不要用 1 填充 BuySignal,将其保持为 0(如您在第 6 行黄色中看到的。)我们只能有一个买入信号,直到下一个卖出信号

the SELL signal is generated:产生卖出信号:

1-sell if only one cell value exceeded a certain threshold [TCN > 8] 1-卖出,如果只有一个单元格值超过某个阈值 [TCN > 8]
PS: if at the same time both buy and sell conditions are met I want to label only BuySignal as 1 and Sell = 0 PS:如果同时满足买入和卖出条件,我只想将 BuySignal 标记为 1 和 Sell = 0

在此处输入图片说明
what i am expecting is : buy at row 1, ignore buy at row 6, sell at row 10, buy again at row 13我期待的是:在第 1 行买入,在第 6 行忽略买入,在第 10 行卖出,在第 13 行再次买入
input data for your ref: https://drive.google.com/file/d/16qqrcvxJuTgd41233RNjwhaNVNREqWWe/view?usp=sharing为您的参考输入数据: https : //drive.google.com/file/d/16qqrcvxJuTgd41233RNjwhaNVNREqWWe/view? usp =sharing

在此处输入图片说明

First of all, I think there is an error in your output table - according to rule 2 for buy signal, I think the buy signal should be also 0 in rows 1 and 13, since there is no sell signal in rows 2 and 14. Here's what I got based on your description, not sure if this is exactly what you meant, but defo a good starting point.首先,我认为您的输出表中存在错误 - 根据买入信号的规则 2,我认为第 1 行和第 13 行的买入信号也应为 0,因为第 2 行和第 14 行没有卖出信号。这是我根据您的描述得到的,不确定这是否正是您的意思,但这是一个很好的起点。 To simplify the problem, I created two BuySignal columns - first shows the state after applying the first rule and second shows the state after applying the second rule to the first.为了简化问题,我创建了两个 BuySignal 列 - 第一个显示应用第一个规则后的状态,第二个显示将第二个规则应用于第一个规则后的状态。 You can just drop the first column in your final solution.您可以删除最终解决方案中的第一列。

# buy rule 1
data['BuySignal1'] = (data['Q5']>7) & (data['Q7']>7)

# sell rule 1
data['SellSignal'] = data['TCN']>8

# buy rule 2
data['BuySignal2'] = (data['BuySignal1']==1)&(data['SellSignal'].shift(-1)==1)

# PS basically - if BuySignal==1 then SellSignal==0
data.loc[data['BuySignal2']==1,'SellSignal'] = 0

# change booleans to types (just for display)
cols = ['BuySignal1','BuySignal2','SellSignal']
data[cols] = data[cols].astype(int)

And this is the output:这是输出: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM