简体   繁体   English

从 pandas dataframe 生成汇总表

[英]Producing a summary table from a pandas dataframe

I have a log of events from an algorithmic trading bot loaded into a dataframe that looks like this:我有一个算法交易机器人的事件日志加载到 dataframe 中,如下所示:

          datetime_long     high     low       trade_direction  trade_entry  trade_exit
159  2021-02-05 10:15:00   88.915   88.6150              LE          1.0         0.0
160  2021-02-05 10:30:00   89.395   88.7800              LX          0.0         1.0
172  2021-02-05 13:30:00   89.090   88.9000              LE          1.0         0.0
177  2021-02-05 14:45:00   89.410   89.1900              LX          0.0         1.0
206  2021-02-08 15:30:00   88.885   88.6600              LE          1.0         0.0
207  2021-02-08 15:45:00   89.080   88.7700              LX          0.0         1.0

"LE" indicates a long entry, "LX" a long exit, "SE" short entry and "SX" short exit. “LE”表示做多,“LX”表示做多,“SE”表示做空,“SX”表示做空。 The goal would be to get each "exit" on the same row as the prior "entry" so that I could perform some simple arithmetic computations like determining profit, average hold time, etc.目标是让每个“退出”与之前的“进入”在同一行,以便我可以执行一些简单的算术计算,如确定利润、平均持有时间等。

How does one go about "shifting" only exits up one row so that my entries and corresponding exits are on the same line?一个关于“移位”的 go 如何只退出一行,以便我的条目和相应的退出在同一行?

You can use .str.contains() to check if elements in Series contains value.您可以使用.str.contains()检查 Series 中的元素是否包含值。

X_mask = df['trade_direction'].str.contains('X')
X_previous_mask = X_mask.shift(-1).fillna(False)
E_mask = df['trade_direction'].str.contains('E')

You can use您可以使用

# Entry Rows where Entry next row is Exit
X_previous_E_mask = X_previous_mask & E_mask

# Entry and Exit Rows where Entry next row is Exit
X_and_previous_E_mask = X_previous_E_mask | X_mask

At last, you can use boolean indexing to select rows.最后,您可以使用 boolean 索引到 select 行。

df[mask]

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

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