M-Rique commited on
Commit
9568e9c
Β·
0 Parent(s):

First commit

Browse files
Files changed (3) hide show
  1. README.md +34 -0
  2. app.py +290 -0
  3. requirements.txt +5 -0
README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PrediBench Frontend
3
+ emoji: πŸ†
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 5.42.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # PrediBench Frontend
14
+
15
+ Interactive leaderboard and performance dashboard for AI agent predictions on Polymarket.
16
+
17
+ ## Features
18
+
19
+ - πŸ† **Leaderboard Tab**: Rankings by PnL, Sharpe ratio, win rate
20
+ - πŸ“ˆ **Performance Tab**: Interactive charts with agent selection
21
+ - πŸ”„ **Daily Refresh**: Loads latest data from HuggingFace datasets
22
+ - πŸ“± **Responsive UI**: Clean Gradio interface
23
+
24
+ ## Data Source
25
+
26
+ Loads from:
27
+ - `m-ric/predibench-agent-choices`
28
+
29
+ ## Usage
30
+
31
+ 1. View overall leaderboard in the first tab
32
+ 2. Select specific agents in the performance tab
33
+ 3. Explore interactive Plotly visualizations
34
+ 4. Refresh data anytime with the button
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import plotly.graph_objects as go
4
+ import plotly.express as px
5
+ from plotly.subplots import make_subplots
6
+ import gradio as gr
7
+ from datetime import datetime, date
8
+ from datasets import Dataset
9
+ from huggingface_hub import HfApi
10
+
11
+ # Configuration
12
+ AGENT_CHOICES_REPO = "m-ric/predibench-agent-choices"
13
+
14
+ def load_agent_choices():
15
+ """Load agent choices from HuggingFace dataset"""
16
+ try:
17
+ dataset = Dataset.from_parquet(f"hf://datasets/{AGENT_CHOICES_REPO}")
18
+ return dataset.to_pandas()
19
+ except Exception as e:
20
+ print(f"Error loading dataset: {e}")
21
+ # Return dummy data for testing
22
+ return pd.DataFrame({
23
+ 'agent_name': ['gpt-4o', 'claude-sonnet', 'test_random'],
24
+ 'date': [date.today()] * 3,
25
+ 'question': ['Sample question'] * 3,
26
+ 'choice': [1, -1, 0],
27
+ 'question_id': ['123'] * 3
28
+ })
29
+
30
+ def calculate_pnl_and_performance(df: pd.DataFrame):
31
+ """Calculate PnL and performance metrics for each agent"""
32
+ # This is a simplified version - in production you'd need actual market returns
33
+ # For now, simulate returns based on random walk
34
+ np.random.seed(42) # For reproducible results
35
+
36
+ agents_performance = {}
37
+
38
+ for agent in df['agent_name'].unique():
39
+ agent_data = df[df['agent_name'] == agent].copy()
40
+
41
+ # Simulate daily PnL based on positions
42
+ # In real implementation, this would use actual market returns
43
+ daily_pnl = []
44
+ cumulative_pnl = 0
45
+
46
+ for _, row in agent_data.iterrows():
47
+ # Simulate daily return based on position
48
+ if row['choice'] == 1: # Long position
49
+ daily_return = np.random.normal(0.01, 0.1) # Slightly positive expected return
50
+ elif row['choice'] == -1: # Short position
51
+ daily_return = -np.random.normal(0.01, 0.1) # Inverse return
52
+ else: # No position
53
+ daily_return = 0
54
+
55
+ daily_pnl.append(daily_return)
56
+ cumulative_pnl += daily_return
57
+
58
+ agents_performance[agent] = {
59
+ 'total_decisions': len(agent_data),
60
+ 'long_positions': len(agent_data[agent_data['choice'] == 1]),
61
+ 'short_positions': len(agent_data[agent_data['choice'] == -1]),
62
+ 'no_positions': len(agent_data[agent_data['choice'] == 0]),
63
+ 'cumulative_pnl': cumulative_pnl,
64
+ 'sharpe_ratio': np.mean(daily_pnl) / (np.std(daily_pnl) + 1e-8) * np.sqrt(252),
65
+ 'win_rate': len([x for x in daily_pnl if x > 0]) / len(daily_pnl) if daily_pnl else 0,
66
+ 'daily_pnl': daily_pnl,
67
+ 'dates': agent_data['date'].tolist()
68
+ }
69
+
70
+ return agents_performance
71
+
72
+ def create_leaderboard(performance_data):
73
+ """Create leaderboard table"""
74
+ leaderboard_data = []
75
+
76
+ for agent, metrics in performance_data.items():
77
+ leaderboard_data.append({
78
+ 'Agent': agent.replace('smolagent_', '').replace('--', '/'),
79
+ 'Total Decisions': metrics['total_decisions'],
80
+ 'Long Positions': metrics['long_positions'],
81
+ 'Short Positions': metrics['short_positions'],
82
+ 'No Position': metrics['no_positions'],
83
+ 'Cumulative PnL': f"{metrics['cumulative_pnl']:.3f}",
84
+ 'Sharpe Ratio': f"{metrics['sharpe_ratio']:.3f}",
85
+ 'Win Rate': f"{metrics['win_rate']:.1%}",
86
+ })
87
+
88
+ # Sort by cumulative PnL
89
+ leaderboard_df = pd.DataFrame(leaderboard_data)
90
+ leaderboard_df['PnL_numeric'] = leaderboard_df['Cumulative PnL'].astype(float)
91
+ leaderboard_df = leaderboard_df.sort_values('PnL_numeric', ascending=False)
92
+ leaderboard_df = leaderboard_df.drop('PnL_numeric', axis=1)
93
+
94
+ return leaderboard_df
95
+
96
+ def create_pnl_plot(performance_data, selected_agent=None):
97
+ """Create interactive PnL plot"""
98
+ fig = go.Figure()
99
+
100
+ agents_to_plot = [selected_agent] if selected_agent and selected_agent in performance_data else performance_data.keys()
101
+
102
+ colors = px.colors.qualitative.Set1
103
+
104
+ for i, agent in enumerate(agents_to_plot):
105
+ if agent not in performance_data:
106
+ continue
107
+
108
+ metrics = performance_data[agent]
109
+ daily_pnl = metrics['daily_pnl']
110
+ dates = metrics['dates']
111
+
112
+ # Calculate cumulative PnL over time
113
+ cumulative_pnl = np.cumsum([0] + daily_pnl)
114
+ plot_dates = [dates[0]] + dates if dates else [datetime.now()]
115
+
116
+ fig.add_trace(go.Scatter(
117
+ x=plot_dates,
118
+ y=cumulative_pnl,
119
+ name=agent.replace('smolagent_', '').replace('--', '/'),
120
+ line=dict(color=colors[i % len(colors)], width=2),
121
+ mode='lines+markers',
122
+ hovertemplate='<b>%{fullData.name}</b><br>' +
123
+ 'Date: %{x}<br>' +
124
+ 'Cumulative PnL: %{y:.3f}<br>' +
125
+ '<extra></extra>'
126
+ ))
127
+
128
+ fig.update_layout(
129
+ title="Agent Performance - Cumulative PnL Over Time",
130
+ xaxis_title="Date",
131
+ yaxis_title="Cumulative PnL",
132
+ hovermode='x unified',
133
+ template="plotly_white",
134
+ height=500,
135
+ showlegend=True
136
+ )
137
+
138
+ # Add horizontal line at 0
139
+ fig.add_hline(y=0, line_dash="dash", line_color="gray", opacity=0.5)
140
+
141
+ return fig
142
+
143
+ def create_position_breakdown_plot(performance_data):
144
+ """Create position breakdown plot"""
145
+ agents = list(performance_data.keys())
146
+ long_positions = [performance_data[agent]['long_positions'] for agent in agents]
147
+ short_positions = [performance_data[agent]['short_positions'] for agent in agents]
148
+ no_positions = [performance_data[agent]['no_positions'] for agent in agents]
149
+
150
+ # Clean agent names for display
151
+ clean_agents = [agent.replace('smolagent_', '').replace('--', '/') for agent in agents]
152
+
153
+ fig = go.Figure()
154
+
155
+ fig.add_trace(go.Bar(
156
+ name='Long Positions',
157
+ x=clean_agents,
158
+ y=long_positions,
159
+ marker_color='green',
160
+ opacity=0.7
161
+ ))
162
+
163
+ fig.add_trace(go.Bar(
164
+ name='Short Positions',
165
+ x=clean_agents,
166
+ y=short_positions,
167
+ marker_color='red',
168
+ opacity=0.7
169
+ ))
170
+
171
+ fig.add_trace(go.Bar(
172
+ name='No Position',
173
+ x=clean_agents,
174
+ y=no_positions,
175
+ marker_color='gray',
176
+ opacity=0.7
177
+ ))
178
+
179
+ fig.update_layout(
180
+ title="Position Breakdown by Agent",
181
+ xaxis_title="Agent",
182
+ yaxis_title="Number of Decisions",
183
+ barmode='stack',
184
+ template="plotly_white",
185
+ height=400
186
+ )
187
+
188
+ return fig
189
+
190
+ def get_agent_list(df):
191
+ """Get list of agents for dropdown"""
192
+ if df.empty:
193
+ return ["No agents available"]
194
+ agents = df['agent_name'].unique()
195
+ clean_agents = [agent.replace('smolagent_', '').replace('--', '/') for agent in agents]
196
+ return ["All Agents"] + clean_agents
197
+
198
+ def update_plot(selected_agent):
199
+ """Update plot based on selected agent"""
200
+ df = load_agent_choices()
201
+ performance_data = calculate_pnl_and_performance(df)
202
+
203
+ # Map clean name back to original name
204
+ if selected_agent != "All Agents" and selected_agent != "No agents available":
205
+ original_name = None
206
+ for agent in performance_data.keys():
207
+ clean_name = agent.replace('smolagent_', '').replace('--', '/')
208
+ if clean_name == selected_agent:
209
+ original_name = agent
210
+ break
211
+ selected_agent = original_name
212
+ else:
213
+ selected_agent = None
214
+
215
+ return create_pnl_plot(performance_data, selected_agent)
216
+
217
+ def refresh_data():
218
+ """Refresh all data and return updated components"""
219
+ df = load_agent_choices()
220
+ performance_data = calculate_pnl_and_performance(df)
221
+
222
+ leaderboard = create_leaderboard(performance_data)
223
+ pnl_plot = create_pnl_plot(performance_data)
224
+ position_plot = create_position_breakdown_plot(performance_data)
225
+ agent_list = get_agent_list(df)
226
+
227
+ return leaderboard, pnl_plot, position_plot, gr.update(choices=agent_list), f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
228
+
229
+ # Initialize data
230
+ df = load_agent_choices()
231
+ performance_data = calculate_pnl_and_performance(df)
232
+
233
+ # Create Gradio interface
234
+ with gr.Blocks(title="PrediBench Leaderboard", theme=gr.themes.Soft()) as demo:
235
+ gr.Markdown("# πŸ† PrediBench Agent Leaderboard")
236
+ gr.Markdown("Track the performance of AI agents making predictions on Polymarket questions")
237
+
238
+ with gr.Row():
239
+ refresh_btn = gr.Button("πŸ”„ Refresh Data", variant="primary")
240
+ last_updated = gr.Textbox(
241
+ value=f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
242
+ label="Status",
243
+ interactive=False,
244
+ scale=3
245
+ )
246
+
247
+ with gr.Tabs():
248
+ with gr.TabItem("πŸ“Š Leaderboard"):
249
+ gr.Markdown("### Agent Performance Ranking")
250
+ leaderboard_table = gr.Dataframe(
251
+ value=create_leaderboard(performance_data),
252
+ interactive=False,
253
+ wrap=True
254
+ )
255
+
256
+ gr.Markdown("### Position Breakdown")
257
+ position_breakdown = gr.Plot(
258
+ value=create_position_breakdown_plot(performance_data)
259
+ )
260
+
261
+ with gr.TabItem("πŸ“ˆ Individual Performance"):
262
+ gr.Markdown("### Select Agent to View Detailed Performance")
263
+
264
+ with gr.Row():
265
+ agent_dropdown = gr.Dropdown(
266
+ choices=get_agent_list(df),
267
+ value="All Agents",
268
+ label="Select Agent",
269
+ scale=3
270
+ )
271
+
272
+ pnl_plot = gr.Plot(
273
+ value=create_pnl_plot(performance_data)
274
+ )
275
+
276
+ # Update plot when agent selection changes
277
+ agent_dropdown.change(
278
+ fn=update_plot,
279
+ inputs=agent_dropdown,
280
+ outputs=pnl_plot
281
+ )
282
+
283
+ # Refresh functionality
284
+ refresh_btn.click(
285
+ fn=refresh_data,
286
+ outputs=[leaderboard_table, pnl_plot, position_breakdown, agent_dropdown, last_updated]
287
+ )
288
+
289
+ if __name__ == "__main__":
290
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ datasets
3
+ huggingface_hub
4
+ plotly
5
+ git+https://github.com/m-ric/predibench-core