75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
import pandas as pd
|
|
|
|
# 加载交易记录
|
|
df = pd.read_csv('../result/backtest_trades.csv')
|
|
|
|
# 转换日期格式
|
|
df['open_date'] = pd.to_datetime(df['open_date'])
|
|
df['close_date'] = pd.to_datetime(df['close_date'])
|
|
|
|
# 计算持仓天数
|
|
df['holding_days'] = (df['close_date'] - df['open_date']).dt.total_seconds() / (60 * 60 * 24)
|
|
|
|
# 按币种分组
|
|
grouped_by_pair = df.groupby('pair').agg(
|
|
total_trades=('profit_abs', 'size'),
|
|
avg_profit_ratio=('profit_ratio', 'mean'),
|
|
total_profit_abs=('profit_abs', 'sum'),
|
|
win_rate=('profit_ratio', lambda x: (x > 0).mean()),
|
|
avg_duration=('trade_duration', 'mean')
|
|
)
|
|
|
|
print(grouped_by_pair)
|
|
|
|
#按退出原因分组
|
|
grouped_by_exit = df.groupby('exit_reason').agg(
|
|
total_trades=('profit_abs', 'size'),
|
|
avg_profit_ratio=('profit_ratio', 'mean'),
|
|
total_profit_abs=('profit_abs', 'sum'),
|
|
win_rate=('profit_ratio', lambda x: (x > 0).mean())
|
|
)
|
|
|
|
print(grouped_by_exit)
|
|
#按月份分组统计
|
|
df['open_date_naive'] = df['open_date'].dt.tz_localize(None)
|
|
df['month'] = df['open_date_naive'].dt.to_period('M')
|
|
|
|
|
|
grouped_by_month = df.groupby('month').agg(
|
|
total_trades=('profit_abs', 'size'),
|
|
avg_profit_ratio=('profit_ratio', 'mean'),
|
|
total_profit_abs=('profit_abs', 'sum'),
|
|
win_rate=('profit_ratio', lambda x: (x > 0).mean())
|
|
)
|
|
|
|
print(grouped_by_month)
|
|
# 按盈利区间分组统计
|
|
bins = [-float('inf'), -0.05, -0.02, 0, 0.02, 0.05, float('inf')]
|
|
labels = ['<-5%', '-5%~-2%', '-2%~0%', '0%~2%', '2%~5%', '>5%']
|
|
|
|
df['profit_group'] = pd.cut(df['profit_ratio'], bins=bins, labels=labels)
|
|
|
|
grouped_by_profit = df.groupby('profit_group', observed=True).agg(
|
|
count=('profit_abs', 'size'),
|
|
avg_profit=('profit_ratio', 'mean'),
|
|
total_profit=('profit_abs', 'sum')
|
|
)
|
|
|
|
print(grouped_by_profit)
|
|
# 分组为短中长线
|
|
df['duration_group'] = pd.cut(df['trade_duration'],
|
|
bins=[0, 60, 360, 1440, 100000],
|
|
labels=['<1小时', '1~6小时', '6小时~1天', '>1天'])
|
|
|
|
grouped_by_duration = df.groupby('duration_group', observed=True).agg(
|
|
count=('profit_abs', 'size'),
|
|
avg_profit=('profit_ratio', 'mean'),
|
|
win_rate=('profit_ratio', lambda x: (x > 0).mean()),
|
|
total_profit=('profit_abs', 'sum')
|
|
)
|
|
|
|
print(grouped_by_duration)
|
|
|
|
|
|
|