rosacastillo commited on
Commit
e51ae04
·
1 Parent(s): d58fc7b

new non-agent graphs

Browse files
app.py CHANGED
@@ -12,6 +12,7 @@ from tabs.trades import (
12
  integrated_plot_trades_per_market_by_week,
13
  integrated_plot_trades_per_market_by_week_v2,
14
  integrated_plot_winning_trades_per_market_by_week,
 
15
  )
16
  from tabs.staking import plot_staking_trades_per_market_by_week
17
 
@@ -197,19 +198,29 @@ with demo:
197
  with gr.Row():
198
  gr.Markdown("# Trend of weekly trades")
199
  with gr.Row():
200
- trades_by_week = integrated_plot_trades_per_market_by_week(
201
  trades_df=trades_df
202
  )
203
 
204
  with gr.Row():
205
- gr.Markdown("# Percentage of winning trades per week")
206
- with gr.Row():
207
- all_wtrades_by_week = integrated_plot_winning_trades_per_market_by_week(
208
- trades_df=trades_df
209
- )
 
 
 
 
 
 
 
 
 
 
 
210
 
211
  def update_trade_details(trade_detail, trade_details_plot):
212
- print(f"user selected option= {trade_detail}")
213
  new_plot = plot_trade_metrics(
214
  metric_name=trade_detail,
215
  trades_df=trades_df,
@@ -217,7 +228,7 @@ with demo:
217
  return new_plot
218
 
219
  with gr.Row():
220
- gr.Markdown("# ⚖️ Trading metrics")
221
  with gr.Row():
222
  trade_details_selector = gr.Dropdown(
223
  label="Select a trade metric",
@@ -239,6 +250,78 @@ with demo:
239
  inputs=[trade_details_selector, trade_details_plot],
240
  outputs=[trade_details_plot],
241
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  with gr.TabItem("🔒 Staking traders"):
243
  with gr.Row():
244
  gr.Markdown("# Trades conducted at the Pearl markets")
 
12
  integrated_plot_trades_per_market_by_week,
13
  integrated_plot_trades_per_market_by_week_v2,
14
  integrated_plot_winning_trades_per_market_by_week,
15
+ integrated_plot_winning_trades_per_market_by_week_v2,
16
  )
17
  from tabs.staking import plot_staking_trades_per_market_by_week
18
 
 
198
  with gr.Row():
199
  gr.Markdown("# Trend of weekly trades")
200
  with gr.Row():
201
+ trades_by_week = integrated_plot_trades_per_market_by_week_v2(
202
  trades_df=trades_df
203
  )
204
 
205
  with gr.Row():
206
+ with gr.Column(scale=1):
207
+ gr.Markdown("# Weekly percentage of winning for Agent based trades")
208
+ agent_winning_trades = (
209
+ integrated_plot_winning_trades_per_market_by_week_v2(
210
+ trades_df=trades_df, trader_filter="agent"
211
+ )
212
+ )
213
+ with gr.Column(scale=1):
214
+ gr.Markdown(
215
+ "# Weekly percentage of winning for Non-agent based trades"
216
+ )
217
+ non_agent_winning_trades = (
218
+ integrated_plot_winning_trades_per_market_by_week_v2(
219
+ trades_df=trades_df, trader_filter="non_agent"
220
+ )
221
+ )
222
 
223
  def update_trade_details(trade_detail, trade_details_plot):
 
224
  new_plot = plot_trade_metrics(
225
  metric_name=trade_detail,
226
  trades_df=trades_df,
 
228
  return new_plot
229
 
230
  with gr.Row():
231
+ gr.Markdown("# ⚖️ Weekly trading metrics for all trades")
232
  with gr.Row():
233
  trade_details_selector = gr.Dropdown(
234
  label="Select a trade metric",
 
250
  inputs=[trade_details_selector, trade_details_plot],
251
  outputs=[trade_details_plot],
252
  )
253
+
254
+ # Agentic traders graph
255
+ with gr.Row():
256
+ gr.Markdown("# Weekly trading metrics for trades coming from Agents")
257
+ with gr.Row():
258
+ trade_a_details_selector = gr.Dropdown(
259
+ label="Select a trade metric",
260
+ choices=trade_metric_choices,
261
+ value=default_trade_metric,
262
+ )
263
+
264
+ with gr.Row():
265
+ with gr.Column(scale=3):
266
+ a_trade_details_plot = plot_trade_metrics(
267
+ metric_name=default_trade_metric,
268
+ trades_df=trades_df,
269
+ trader_filter="agent",
270
+ )
271
+ with gr.Column(scale=1):
272
+ trade_details_text = get_trade_metrics_text()
273
+
274
+ def update_a_trade_details(trade_detail, trade_details_plot):
275
+ new_a_plot = plot_trade_metrics(
276
+ metric_name=trade_detail,
277
+ trades_df=trades_df,
278
+ trader_filter="agent",
279
+ )
280
+ return new_a_plot
281
+
282
+ trade_a_details_selector.change(
283
+ update_a_trade_details,
284
+ inputs=[trade_a_details_selector, a_trade_details_plot],
285
+ outputs=[a_trade_details_plot],
286
+ )
287
+
288
+ # Non-agentic traders graph
289
+ with gr.Row():
290
+ gr.Markdown(
291
+ "# Weekly trading metrics for trades coming from Non-agents"
292
+ )
293
+ with gr.Row():
294
+ trade_na_details_selector = gr.Dropdown(
295
+ label="Select a trade metric",
296
+ choices=trade_metric_choices,
297
+ value=default_trade_metric,
298
+ )
299
+
300
+ with gr.Row():
301
+ with gr.Column(scale=3):
302
+ na_trade_details_plot = plot_trade_metrics(
303
+ metric_name=default_trade_metric,
304
+ trades_df=trades_df,
305
+ trader_filter="non_agent",
306
+ )
307
+ with gr.Column(scale=1):
308
+ trade_details_text = get_trade_metrics_text()
309
+
310
+ def update_na_trade_details(trade_detail, trade_details_plot):
311
+ print(f"user selected option= {trade_detail}")
312
+ new_a_plot = plot_trade_metrics(
313
+ metric_name=trade_detail,
314
+ trades_df=trades_df,
315
+ trader_filter="non_agent",
316
+ )
317
+ return new_a_plot
318
+
319
+ trade_na_details_selector.change(
320
+ update_na_trade_details,
321
+ inputs=[trade_na_details_selector, na_trade_details_plot],
322
+ outputs=[na_trade_details_plot],
323
+ )
324
+
325
  with gr.TabItem("🔒 Staking traders"):
326
  with gr.Row():
327
  gr.Markdown("# Trades conducted at the Pearl markets")
data/all_trades_profitability.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:804722496702da46e6034175b54c73778fd4c5b7794d29967dccb2f2f6432603
3
- size 3290989
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3068c54295d43c0d40f331cf3ad988fb8bf150bed0c948d3103161d7d7065f38
3
+ size 3292156
data/outliers.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9fa72b86e20493b5a02dff2cf9173d394546b5eaba1de21469bb66593f7939e1
3
- size 18274
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72326e188a845663048e6ebf368045dfc387eac9a54a38303e9020f5ca112ad6
3
+ size 18966
scripts/profitability.py CHANGED
@@ -444,15 +444,18 @@ def analyse_trader(
444
  winner_trade = True
445
 
446
  # Compute mech calls
447
- try:
448
- num_mech_calls = (
449
- tools_usage["prompt_request"]
450
- .apply(lambda x: trade["title"] in x)
451
- .sum()
452
- )
453
- except Exception:
454
- print(f"Error while getting the number of mech calls")
455
- num_mech_calls = 2 # Average value
 
 
 
456
 
457
  net_earnings = (
458
  earnings
 
444
  winner_trade = True
445
 
446
  # Compute mech calls
447
+ if len(tools_usage) == 0:
448
+ num_mech_calls = 0
449
+ else:
450
+ try:
451
+ num_mech_calls = (
452
+ tools_usage["prompt_request"]
453
+ .apply(lambda x: trade["title"] in x)
454
+ .sum()
455
+ )
456
+ except Exception:
457
+ print(f"Error while getting the number of mech calls")
458
+ num_mech_calls = 2 # Average value
459
 
460
  net_earnings = (
461
  earnings
scripts/pull_data.py CHANGED
@@ -156,8 +156,6 @@ def only_new_weekly_analysis():
156
  # merge new json files with old json files
157
  update_json_files()
158
 
159
- # TODO move new parquet files to a tmp folder
160
-
161
  try:
162
  updating_timestamps(rpc, TOOLS_FILENAME)
163
  except Exception as e:
 
156
  # merge new json files with old json files
157
  update_json_files()
158
 
 
 
159
  try:
160
  updating_timestamps(rpc, TOOLS_FILENAME)
161
  except Exception as e:
scripts/update_nr_mech_calls.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from profitability import DATA_DIR, DEFAULT_MECH_FEE, summary_analyse
3
+ from tqdm import tqdm
4
+
5
+
6
+ def update_roi(row: pd.DataFrame) -> float:
7
+ new_value = row.net_earnings / (
8
+ row.collateral_amount
9
+ + row.trade_fee_amount
10
+ + row.num_mech_calls * DEFAULT_MECH_FEE
11
+ )
12
+ return new_value
13
+
14
+
15
+ def update_trade_nr_mech_calls(non_agents: bool = False):
16
+ try:
17
+ all_trades_df = pd.read_parquet(DATA_DIR / "all_trades_profitability.parquet")
18
+ tools = pd.read_parquet(DATA_DIR / "tools.parquet")
19
+ except Exception as e:
20
+ print(f"Error reading the profitability and tools parquet files")
21
+
22
+ traders = list(all_trades_df.trader_address.unique())
23
+ if non_agents:
24
+ traders = list(
25
+ all_trades_df.loc[
26
+ all_trades_df["staking"] == "non_agent"
27
+ ].trader_address.unique()
28
+ )
29
+
30
+ print("before updating")
31
+ print(
32
+ all_trades_df.loc[
33
+ all_trades_df["staking"] == "non_agent"
34
+ ].num_mech_calls.describe()
35
+ )
36
+ for trader in tqdm(traders, desc=f"Updating Traders mech calls", unit="traders"):
37
+ tools_usage = tools[tools["trader_address"] == trader]
38
+ if len(tools_usage) == 0:
39
+ tqdm.write(f"trader with no tools usage found {trader}")
40
+ all_trades_df.loc[
41
+ all_trades_df["trader_address"] == trader, "nr_mech_calls"
42
+ ] = 0
43
+ # update roi
44
+ all_trades_df["roi"] = all_trades_df.apply(lambda x: update_roi(x), axis=1)
45
+ print("after updating")
46
+ print(
47
+ all_trades_df.loc[
48
+ all_trades_df["staking"] == "non_agent"
49
+ ].num_mech_calls.describe()
50
+ )
51
+
52
+ # saving
53
+ all_trades_df.to_parquet(DATA_DIR / "all_trades_profitability.parquet", index=False)
54
+ print("Summarising trades...")
55
+ summary_df = summary_analyse(all_trades_df)
56
+ summary_df.to_parquet(DATA_DIR / "summary_profitability.parquet", index=False)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ update_trade_nr_mech_calls(non_agents=True)
tabs/metrics.py CHANGED
@@ -118,7 +118,9 @@ def plot2_trade_details(
118
  )
119
 
120
 
121
- def plot_trade_metrics(metric_name: str, trades_df: pd.DataFrame) -> gr.Plot:
 
 
122
  """Plots the trade metrics."""
123
 
124
  if metric_name == "mech calls":
@@ -140,7 +142,16 @@ def plot_trade_metrics(metric_name: str, trades_df: pd.DataFrame) -> gr.Plot:
140
  column_name = metric_name
141
  yaxis_title = "Gross profit per trade (xDAI)"
142
 
143
- trades_filtered = get_boxplot_metrics(column_name, trades_df)
 
 
 
 
 
 
 
 
 
144
  fig = px.box(
145
  trades_filtered,
146
  x="month_year_week",
 
118
  )
119
 
120
 
121
+ def plot_trade_metrics(
122
+ metric_name: str, trades_df: pd.DataFrame, trader_filter: str = None
123
+ ) -> gr.Plot:
124
  """Plots the trade metrics."""
125
 
126
  if metric_name == "mech calls":
 
142
  column_name = metric_name
143
  yaxis_title = "Gross profit per trade (xDAI)"
144
 
145
+ if trader_filter == "agent":
146
+ trades_filtered = get_boxplot_metrics(
147
+ column_name, trades_df.loc[trades_df["staking"] != "non_agent"]
148
+ )
149
+ elif trader_filter == "non_agent":
150
+ trades_filtered = get_boxplot_metrics(
151
+ column_name, trades_df.loc[trades_df["staking"] == "non_agent"]
152
+ )
153
+ else:
154
+ trades_filtered = get_boxplot_metrics(column_name, trades_df)
155
  fig = px.box(
156
  trades_filtered,
157
  x="month_year_week",
tabs/staking.py CHANGED
@@ -24,9 +24,10 @@ def plot_staking_trades_per_market_by_week(
24
  trades_all["market_creator"] = "all"
25
 
26
  # choose colour
27
- market_colour = "darkgreen"
 
28
  if market_creator == "pearl":
29
- market_colour = "purple"
30
  elif market_creator == "quickstart":
31
  market_colour = "goldenrod"
32
 
@@ -40,6 +41,7 @@ def plot_staking_trades_per_market_by_week(
40
  all_filtered_trades["market_creator"] == market_creator
41
  ]
42
  print(all_filtered_trades.market_creator.value_counts())
 
43
  if market_creator != "all":
44
  all_filtered_trades["staking"] = all_filtered_trades["staking"].replace(
45
  {market_creator: "staking_traders", "non_agent": "non_agent_traders"}
@@ -56,7 +58,7 @@ def plot_staking_trades_per_market_by_week(
56
  "non_agent": "non_agent_traders",
57
  }
58
  )
59
- colour_sequence = ["gray", "purple", "goldenrod", "black"]
60
  categories_sorted = {
61
  "staking": [
62
  "non_staking_traders",
 
24
  trades_all["market_creator"] = "all"
25
 
26
  # choose colour
27
+
28
+ market_colour = "green"
29
  if market_creator == "pearl":
30
+ market_colour = "darkviolet"
31
  elif market_creator == "quickstart":
32
  market_colour = "goldenrod"
33
 
 
41
  all_filtered_trades["market_creator"] == market_creator
42
  ]
43
  print(all_filtered_trades.market_creator.value_counts())
44
+
45
  if market_creator != "all":
46
  all_filtered_trades["staking"] = all_filtered_trades["staking"].replace(
47
  {market_creator: "staking_traders", "non_agent": "non_agent_traders"}
 
58
  "non_agent": "non_agent_traders",
59
  }
60
  )
61
+ colour_sequence = ["gray", "darkviolet", "goldenrod", "black"]
62
  categories_sorted = {
63
  "staking": [
64
  "non_staking_traders",
tabs/trades.py CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
 
5
 
6
 
7
  HEIGHT = 400
@@ -70,13 +71,39 @@ def get_overall_winning_by_market_trades(trades_df: pd.DataFrame) -> pd.DataFram
70
  ].count()
71
  * 100
72
  )
73
- # winning_trades is a series, give it a dataframe
74
  winning_trades = winning_trades.reset_index()
75
  winning_trades.columns = winning_trades.columns.astype(str)
76
  winning_trades.columns = ["month_year_week", "market_creator", "winning_trade"]
77
  return winning_trades
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def plot_trades_by_week(trades_df: pd.DataFrame) -> gr.BarPlot:
81
  """Plots the trades data for the given tools and calculates the winning percentage."""
82
  return gr.BarPlot(
@@ -150,11 +177,9 @@ def integrated_plot_trades_per_market_by_week_v2(trades_df: pd.DataFrame) -> gr.
150
  .reset_index(name="trades")
151
  )
152
 
153
- # category_orders={"market_creator": ["pearl", "quickstart", "all"]},
154
-
155
  # Combine the traces
156
  final_traces = []
157
- market_colors = {"pearl": "purple", "quickstart": "goldenrod", "all": "darkgreen"}
158
  # First add 'agent' traces
159
  for market in ["pearl", "quickstart", "all"]:
160
  market_data = trades[trades["market_creator"] == market]
@@ -171,6 +196,11 @@ def integrated_plot_trades_per_market_by_week_v2(trades_df: pd.DataFrame) -> gr.
171
  final_traces.append(trace)
172
 
173
  # Then add 'non_agent' traces
 
 
 
 
 
174
  for market in ["pearl", "quickstart", "all"]:
175
  market_data = trades[trades["market_creator"] == market]
176
  non_agent_data = market_data[market_data["staking_type"] == "non_agent"]
@@ -179,7 +209,7 @@ def integrated_plot_trades_per_market_by_week_v2(trades_df: pd.DataFrame) -> gr.
179
  x=non_agent_data["month_year_week"],
180
  y=non_agent_data["trades"],
181
  name=f"{market}-non_agent",
182
- marker_color="black",
183
  offsetgroup=market,
184
  showlegend=True,
185
  )
@@ -238,6 +268,55 @@ def integrated_plot_winning_trades_per_market_by_week(
238
  )
239
 
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  def plot_winning_trades_by_week(trades_df: pd.DataFrame) -> gr.BarPlot:
242
  """Plots the winning trades data for the given tools and calculates the winning percentage."""
243
  return gr.BarPlot(
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
+ from plotly.subplots import make_subplots
6
 
7
 
8
  HEIGHT = 400
 
71
  ].count()
72
  * 100
73
  )
74
+
75
  winning_trades = winning_trades.reset_index()
76
  winning_trades.columns = winning_trades.columns.astype(str)
77
  winning_trades.columns = ["month_year_week", "market_creator", "winning_trade"]
78
  return winning_trades
79
 
80
 
81
+ def get_overall_winning_by_market_and_trader_type(
82
+ trades_df: pd.DataFrame,
83
+ ) -> pd.DataFrame:
84
+ """Gets the overall winning trades data for the given tools and calculates the winning percentage."""
85
+ # Group by week, market_creator and staking_type
86
+ winning_trades = (
87
+ trades_df.groupby(
88
+ ["month_year_week", "market_creator", "staking_type"], sort=False
89
+ )["winning_trade"].sum()
90
+ / trades_df.groupby(
91
+ ["month_year_week", "market_creator", "staking_type"], sort=False
92
+ )["winning_trade"].count()
93
+ * 100
94
+ )
95
+
96
+ winning_trades = winning_trades.reset_index()
97
+ winning_trades.columns = winning_trades.columns.astype(str)
98
+ winning_trades.columns = [
99
+ "month_year_week",
100
+ "market_creator",
101
+ "staking_type",
102
+ "winning_trade",
103
+ ]
104
+ return winning_trades
105
+
106
+
107
  def plot_trades_by_week(trades_df: pd.DataFrame) -> gr.BarPlot:
108
  """Plots the trades data for the given tools and calculates the winning percentage."""
109
  return gr.BarPlot(
 
177
  .reset_index(name="trades")
178
  )
179
 
 
 
180
  # Combine the traces
181
  final_traces = []
182
+ market_colors = {"pearl": "darkviolet", "quickstart": "goldenrod", "all": "green"}
183
  # First add 'agent' traces
184
  for market in ["pearl", "quickstart", "all"]:
185
  market_data = trades[trades["market_creator"] == market]
 
196
  final_traces.append(trace)
197
 
198
  # Then add 'non_agent' traces
199
+ market_darker_colors = {
200
+ "pearl": "purple",
201
+ "quickstart": "darkgoldenrod",
202
+ "all": "darkgreen",
203
+ }
204
  for market in ["pearl", "quickstart", "all"]:
205
  market_data = trades[trades["market_creator"] == market]
206
  non_agent_data = market_data[market_data["staking_type"] == "non_agent"]
 
209
  x=non_agent_data["month_year_week"],
210
  y=non_agent_data["trades"],
211
  name=f"{market}-non_agent",
212
+ marker_color=market_darker_colors[market],
213
  offsetgroup=market,
214
  showlegend=True,
215
  )
 
268
  )
269
 
270
 
271
+ def integrated_plot_winning_trades_per_market_by_week_v2(
272
+ trades_df: pd.DataFrame, trader_filter: str = None
273
+ ) -> gr.Plot:
274
+ # adding the total
275
+ trades_all = trades_df.copy(deep=True)
276
+ trades_all["market_creator"] = "all"
277
+
278
+ # merging both dataframes
279
+ all_filtered_trades = pd.concat([trades_df, trades_all], ignore_index=True)
280
+ all_filtered_trades = all_filtered_trades.sort_values(
281
+ by="creation_timestamp", ascending=True
282
+ )
283
+ # Create binary staking category
284
+ all_filtered_trades["staking_type"] = all_filtered_trades["staking"].apply(
285
+ lambda x: "non_agent" if x == "non_agent" else "agent"
286
+ )
287
+ if trader_filter is None:
288
+ final_df = get_overall_winning_by_market_trades(all_filtered_trades)
289
+ else:
290
+ final_df = get_overall_winning_by_market_and_trader_type(all_filtered_trades)
291
+
292
+ color_discrete_sequence = ["darkviolet", "goldenrod", "green"]
293
+ if trader_filter == "agent":
294
+ final_df = final_df[final_df["staking_type"] == "agent"]
295
+ elif trader_filter == "non_agent":
296
+ final_df = final_df[final_df["staking_type"] == "non_agent"]
297
+ color_discrete_sequence = ["purple", "darkgoldenrod", "darkgreen"]
298
+
299
+ fig = px.bar(
300
+ final_df,
301
+ x="month_year_week",
302
+ y="winning_trade",
303
+ color="market_creator",
304
+ barmode="group",
305
+ color_discrete_sequence=color_discrete_sequence,
306
+ category_orders={"market_creator": ["pearl", "quickstart", "all"]},
307
+ )
308
+ fig.update_layout(
309
+ xaxis_title="Week",
310
+ yaxis_title="Weekly % of winning trades",
311
+ legend=dict(yanchor="top", y=0.5),
312
+ )
313
+ # fig.update_layout(width=WIDTH, height=HEIGHT)
314
+ fig.update_xaxes(tickformat="%b %d\n%Y")
315
+ return gr.Plot(
316
+ value=fig,
317
+ )
318
+
319
+
320
  def plot_winning_trades_by_week(trades_df: pd.DataFrame) -> gr.BarPlot:
321
  """Plots the winning trades data for the given tools and calculates the winning percentage."""
322
  return gr.BarPlot(