我已经编写了一个代码,通过在数据帧上使用标准for循环来工作。我想检查是否可以通过使用groupby、apply、lamda等使代码更加pythonic来提高性能
该代码旨在检查股票价格数据上的特定数据模式。股票收盘价与其20EMA一起使用。 panda数据帧是从mysql数据库加载的。它有下面的结构。你知道吗
df[['eod_dt','bull_bear','open','high','low','close','ema20']]
对于看涨的情况
条件1:必须至少有一次“low”高于“ema20”。你知道吗
条件2:如果此情况为真,则事件后至少需要2个“bull”蜡烛。第一支“公牛”蜡烛后面应该有一支“高”高于第一支“公牛”蜡烛“高”的蜡烛。第二支公牛蜡烛将是我买入的信号。你知道吗
目前我已经这样做了。你知道吗
df_bull=df[(df['bull_bear']=='bull') & (df['high']<df['EMA20']) & (df['eod_dt']>start_dt)] #start_dt is start of analysis period
for index,row in df_bull.iterrows():
df_temp1=df[(df['index']>(row['index']-10)) & (df['index']<row['index'])] #10 day look back, the index field actually exists and acts as a proxy to actual trading days
df_temp2=df_temp1[df_temp1['low']>df_temp1['EMA20']]
if not df_temp2.empty: #condition1 satisfied
df_temp1['high_1']=df_temp1['high'].shift(-1)
df_temp2=df_temp1[(df_temp1['bull_bear']=='bull') & (df_temp1['high']<df_temp1['EMA20']) & (df_temp1['high_1']>df_temp1['high'])]
if not df_temp2.empty and len(df_temp2)<4:
#entry above signal bar high
“更好”代码的结果应与上述相同。但我想把运行时间降到最低限度。代码越短越好。你知道吗
要摆脱for循环,可以使用应用.DataFrame.apply你知道吗
应用允许您对数据集的所有行执行操作。你知道吗
其工作原理如下(简单示例):
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
就你而言:
我在手机上写这篇文章对我来说很难。温柔一点
相关问题 更多 >
编程相关推荐