cyberosa commited on
Commit
c2e6ec4
·
1 Parent(s): 5aa6873

new dataset for weekly traders metrics

Browse files
scripts/market_metrics.py CHANGED
@@ -1,7 +1,12 @@
1
  import numpy as np
2
  import pandas as pd
 
3
  import time
 
4
  from utils import convert_hex_to_int, ROOT_DIR, TMP_DIR
 
 
 
5
 
6
 
7
  def determine_market_status(row):
@@ -59,6 +64,84 @@ def compute_market_metrics(all_trades: pd.DataFrame):
59
  print(market_metrics.head())
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  if __name__ == "__main__":
63
  all_trades = pd.read_parquet(TMP_DIR / "fpmmTrades.parquet")
64
  compute_market_metrics(all_trades)
 
 
 
 
 
1
  import numpy as np
2
  import pandas as pd
3
+ from typing import Tuple
4
  import time
5
+ from tqdm import tqdm
6
  from utils import convert_hex_to_int, ROOT_DIR, TMP_DIR
7
+ from get_mech_info import read_all_trades_profitability
8
+ from tools_metrics import prepare_tools
9
+ from predict_kpis import compute_markets_agent_roi
10
 
11
 
12
  def determine_market_status(row):
 
64
  print(market_metrics.head())
65
 
66
 
67
+ def prepare_traders_data() -> Tuple[pd.DataFrame, pd.DataFrame]:
68
+ """Prepare traders data for weekly metrics computation."""
69
+ trades = read_all_trades_profitability()
70
+ trades["creation_timestamp"] = pd.to_datetime(trades["creation_timestamp"])
71
+ trades["creation_timestamp"] = trades["creation_timestamp"].dt.tz_convert("UTC")
72
+ trades["creation_date"] = trades["creation_timestamp"].dt.date
73
+ trades = trades.sort_values(by="creation_timestamp", ascending=True)
74
+ unique_addresses = trades.trader_address.unique()
75
+ closed_markets = trades.title.unique()
76
+ # filter the mech requests done these traders on closed markets
77
+ try:
78
+ tools_df = pd.read_parquet(TMP_DIR / "tools.parquet")
79
+ tools_df = prepare_tools(tools_df)
80
+ except Exception as e:
81
+ print(f"Error reading tools parquet file {e}")
82
+ return None
83
+ traders_activity = tools_df[
84
+ tools_df["trader_address"].isin(unique_addresses)
85
+ ].copy()
86
+ traders_activity = traders_activity[traders_activity["title"].isin(closed_markets)]
87
+ traders_activity["request_time"] = pd.to_datetime(
88
+ traders_activity["request_time"], utc=True
89
+ )
90
+ traders_activity = traders_activity.sort_values(by="request_time", ascending=True)
91
+ traders_activity["request_date"] = traders_activity["request_time"].dt.date
92
+ return trades, traders_activity
93
+
94
+
95
+ def compute_weekly_trader_metrics():
96
+ trades_data, mechs_data = prepare_traders_data()
97
+ trades_data["week_start"] = (
98
+ trades_data["creation_timestamp"].dt.to_period("W").dt.start_time
99
+ )
100
+
101
+ grouped_trades = trades_data.groupby("week_start")
102
+ contents = []
103
+ traders = trades_data.trader_address.unique()
104
+ # Iterate through the groups (each group represents a week)
105
+ for week, week_data in grouped_trades:
106
+ print(f"Week: {week}") # Print the week identifier
107
+
108
+ # for all closed markets
109
+ closed_markets = week_data.title.unique()
110
+ for trader in tqdm(
111
+ traders, total=len(traders), desc="Computing metrics for traders"
112
+ ):
113
+ # compute all trades done by the trader on those markets, no matter from which week
114
+ trader_trades = trades_data[
115
+ (trades_data["trader_address"] == trader)
116
+ & (trades_data["title"].isin(closed_markets))
117
+ ]
118
+ if len(trader_trades) == 0:
119
+ # no trading activity
120
+ continue
121
+
122
+ # filter mech requests done by the trader on those markets
123
+ trader_mech_calls = mechs_data.loc[
124
+ (mechs_data["trader_address"] == trader)
125
+ & (mechs_data["title"].isin(closed_markets))
126
+ ]
127
+ # compute the ROI for that market, that trader and that week
128
+ try:
129
+ # Convert the dictionary to DataFrame before appending
130
+ roi_dict = compute_markets_agent_roi(
131
+ trader_trades, trader_mech_calls, trader, "week", week
132
+ )
133
+ contents.append(pd.DataFrame([roi_dict]))
134
+ except ValueError as e:
135
+ print(f"Skipping ROI calculation: {e}")
136
+ continue
137
+ traders_weekly_metrics = pd.concat(contents, ignore_index=True)
138
+ return traders_weekly_metrics
139
+
140
+
141
  if __name__ == "__main__":
142
  all_trades = pd.read_parquet(TMP_DIR / "fpmmTrades.parquet")
143
  compute_market_metrics(all_trades)
144
+ weekly_metrics_df = compute_weekly_trader_metrics()
145
+ weekly_metrics_df.to_parquet(
146
+ ROOT_DIR / "traders_weekly_metrics.parquet", index=False
147
+ )
scripts/predict_kpis.py CHANGED
@@ -310,12 +310,12 @@ def compute_markets_agent_roi(
310
  period_value: datetime,
311
  ) -> dict:
312
  # ROI formula net_earnings/total_costs
313
- earnings = agent_trades.earnings.sum()
314
  total_market_fees = agent_trades.trade_fee_amount.sum()
315
  total_mech_fees = len(mech_calls) * DEFAULT_MECH_FEE
316
  total_bet_amount = agent_trades.collateral_amount.sum()
317
  total_costs = total_bet_amount + total_market_fees + total_mech_fees
318
- net_earnings = earnings - total_costs
319
  if total_costs == 0:
320
  raise ValueError(f"Total costs for agent {agent} are zero")
321
  roi = net_earnings / total_costs
@@ -325,8 +325,10 @@ def compute_markets_agent_roi(
325
  "week_start": period_value,
326
  "roi": roi,
327
  "net_earnings": net_earnings,
 
328
  "total_bet_amount": total_bet_amount,
329
  "total_mech_calls": len(mech_calls),
 
330
  }
331
  if period == "day":
332
  return {
@@ -334,8 +336,10 @@ def compute_markets_agent_roi(
334
  "creation_date": period_value,
335
  "roi": roi,
336
  "net_earnings": net_earnings,
 
337
  "total_bet_amount": total_bet_amount,
338
  "total_mech_calls": len(mech_calls),
 
339
  }
340
  raise ValueError(
341
  f"Invalid period {period} for agent {agent}. Expected 'week' or 'day'."
 
310
  period_value: datetime,
311
  ) -> dict:
312
  # ROI formula net_earnings/total_costs
313
+ total_earnings = agent_trades.earnings.sum()
314
  total_market_fees = agent_trades.trade_fee_amount.sum()
315
  total_mech_fees = len(mech_calls) * DEFAULT_MECH_FEE
316
  total_bet_amount = agent_trades.collateral_amount.sum()
317
  total_costs = total_bet_amount + total_market_fees + total_mech_fees
318
+ net_earnings = total_earnings - total_costs
319
  if total_costs == 0:
320
  raise ValueError(f"Total costs for agent {agent} are zero")
321
  roi = net_earnings / total_costs
 
325
  "week_start": period_value,
326
  "roi": roi,
327
  "net_earnings": net_earnings,
328
+ "earnings": total_earnings,
329
  "total_bet_amount": total_bet_amount,
330
  "total_mech_calls": len(mech_calls),
331
+ "nr_trades": len(agent_trades),
332
  }
333
  if period == "day":
334
  return {
 
336
  "creation_date": period_value,
337
  "roi": roi,
338
  "net_earnings": net_earnings,
339
+ "earnings": total_earnings,
340
  "total_bet_amount": total_bet_amount,
341
  "total_mech_calls": len(mech_calls),
342
+ "nr_trades": len(agent_trades),
343
  }
344
  raise ValueError(
345
  f"Invalid period {period} for agent {agent}. Expected 'week' or 'day'."
traders_weekly_metrics.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5af7a128ae02f8213fd6054b18919517539748c5e0d113ae651e48a6b1d4b8fc
3
+ size 214869