File size: 7,555 Bytes
18ab870
 
 
 
 
 
 
 
 
7f9e80f
0e538d2
577dd09
 
 
 
 
 
 
 
0e538d2
18ab870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60949bd
 
0e538d2
 
 
 
18ab870
 
0e538d2
18ab870
 
 
0e538d2
18ab870
 
 
0e538d2
18ab870
 
0e538d2
18ab870
7f9e80f
18ab870
7f9e80f
18ab870
 
 
 
 
 
 
 
 
 
 
 
 
6298cbe
 
18ab870
 
 
 
7f9e80f
 
18ab870
 
 
 
 
 
 
 
 
 
 
7f9e80f
18ab870
 
 
 
 
 
 
7f9e80f
 
 
18ab870
6298cbe
 
18ab870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import pandas as pd
import gradio as gr
import gc
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from datetime import datetime, timedelta
from tqdm import tqdm

trader_daily_metric_choices = ["mech calls", "collateral amount", "nr_trades"]
default_daily_metric = "collateral amount"
color_mapping = [
    "darkviolet",
    "purple",
    "goldenrod",
    "darkgoldenrod",
    "green",
    "darkgreen",
]


def plot_daily_trades(trades_df: pd.DataFrame) -> gr.Plot:
    # get daily trades
    daily_trades_count = (
        trades_df.groupby("month_year_week").size().reset_index(name="trades")
    )
    daily_trades_count.columns = daily_trades_count.columns.astype(str)
    print("WIP")


def get_current_week_data(trades_df: pd.DataFrame) -> pd.DataFrame:
    # Get current date
    now = datetime.now()

    # Get start of the current week (Monday)
    start_of_week = now - timedelta(days=now.weekday())
    start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
    print(f"start of the week = {start_of_week}")

    # Get end of the current week (Sunday)
    end_of_week = start_of_week + timedelta(days=6)
    end_of_week = end_of_week.replace(hour=23, minute=59, second=59, microsecond=999999)
    print(f"end of the week = {end_of_week}")
    trades_df["creation_date"] = pd.to_datetime(trades_df["creation_date"])
    # Filter the dataframe
    return trades_df[
        (trades_df["creation_date"] >= start_of_week)
        & (trades_df["creation_date"] <= end_of_week)
    ]


def get_boxplot_daily_metrics(
    column_name: str, trades_df: pd.DataFrame
) -> pd.DataFrame:
    trades_filtered = trades_df[
        [
            "creation_timestamp",
            "creation_date",
            "market_creator",
            "trader_address",
            "staking",
            column_name,
        ]
    ]

    # adding the total
    trades_filtered_all = trades_filtered.copy(deep=True)
    trades_filtered_all["market_creator"] = "all"

    # merging both dataframes
    all_filtered_trades = pd.concat(
        [trades_filtered, trades_filtered_all], ignore_index=True
    )
    all_filtered_trades = all_filtered_trades.sort_values(
        by="creation_timestamp", ascending=True
    )
    gc.collect()
    return all_filtered_trades


def plot_daily_metrics(
    metric_name: str, trades_df: pd.DataFrame, trader_filter: str = None
) -> gr.Plot:
    """Plots the trade metrics."""

    if metric_name == "mech calls":
        metric_name = "nr_mech_calls"
        column_name = "nr_mech_calls"
        yaxis_title = "Total nr of mech calls per trader"
    elif metric_name == "nr_trades":
        column_name = metric_name
        yaxis_title = "Total nr of trades per trader"
    elif metric_name == "ROI":
        column_name = "roi"
        yaxis_title = "Total ROI (net profit/cost)"
    elif metric_name == "collateral amount":
        metric_name = "bet_amount"
        column_name = metric_name
        yaxis_title = "Total bet amount per trader (xDAI)"
    elif metric_name == "net earnings":
        metric_name = "net_earnings"
        column_name = metric_name
        yaxis_title = "Total net profit per trader (xDAI)"
    else:  # earnings
        column_name = metric_name
        yaxis_title = "Total gross profit per trader (xDAI)"

    color_discrete_sequence = ["purple", "goldenrod", "darkgreen"]
    if trader_filter == "agent":
        color_discrete_sequence = ["darkviolet", "goldenrod", "green"]
        trades_filtered = trades_df.loc[trades_df["staking"] != "non_agent"]
    elif trader_filter == "non_agent":
        trades_filtered = trades_df.loc[trades_df["staking"] == "non_agent"]
    else:
        trades_filtered = trades_df

    # Create binary staking category
    trades_filtered["trader_type"] = trades_filtered["staking"].apply(
        lambda x: "non_agent" if x == "non_agent" else "agent"
    )
    trades_filtered["trader_market"] = trades_filtered.apply(
        lambda x: (x["trader_type"], x["market_creator"]), axis=1
    )

    all_dates = sorted(trades_filtered["creation_date"].unique())
    fig = px.box(
        trades_filtered,
        x="creation_date",
        y=column_name,
        color="market_creator",
        color_discrete_sequence=color_discrete_sequence,
        category_orders={
            "market_creator": ["pearl", "quickstart", "all"],
            "trader_market": [
                ("agent", "pearl"),
                ("non_agent", "pearl"),
                ("agent", "quickstart"),
                ("non_agent", "quickstart"),
                ("agent", "all"),
                ("non_agent", "all"),
            ],
        },
        # facet_col="market_creator",
    )
    fig.update_traces(boxmean=True)
    fig.update_layout(
        xaxis_title="Day",
        yaxis_title=yaxis_title,
        legend=dict(yanchor="top", y=0.5),
    )
    # for axis in fig.layout:
    #     if axis.startswith("xaxis"):
    #         fig.layout[axis].update(title="Day")
    fig.update_xaxes(tickformat="%b %d")
    # Update layout to force x-axis category order (hotfix for a sorting issue)
    fig.update_layout(xaxis={"categoryorder": "array", "categoryarray": all_dates})
    return gr.Plot(
        value=fig,
    )


def plot_daily_metrics_v2(
    metric_name: str, trades_df: pd.DataFrame, trader_filter: str = None
) -> gr.Plot:
    """Plots the trade metrics."""

    if metric_name == "mech calls":
        metric_name = "mech_calls"
        column_name = "num_mech_calls"
        yaxis_title = "Nr of mech calls per trade"
    elif metric_name == "ROI":
        column_name = "roi"
        yaxis_title = "ROI (net profit/cost)"
    elif metric_name == "collateral amount":
        metric_name = "collateral_amount"
        column_name = metric_name
        yaxis_title = "Collateral amount per trade (xDAI)"
    elif metric_name == "net earnings":
        metric_name = "net_earnings"
        column_name = metric_name
        yaxis_title = "Net profit per trade (xDAI)"
    else:  # earnings
        column_name = metric_name
        yaxis_title = "Gross profit per trade (xDAI)"

    color_discrete = ["purple", "darkgoldenrod", "darkgreen"]
    trades_filtered = get_boxplot_daily_metrics(column_name, trades_df)
    fig = make_subplots(rows=1, cols=2, subplot_titles=("Agent", "Non-Agents"))

    # Create first boxplot for staking=True
    fig.add_trace(
        go.Box(
            x=trades_filtered[trades_filtered["staking"] != "non_agent"][
                "creation_date"
            ],
            y=trades_filtered[trades_filtered["staking"] != "non_agent"][column_name],
            name="Trades from agents",
            marker_color=color_discrete[0],
            legendgroup="staking_true",
            showlegend=True,
        ),
        row=1,
        col=1,
    )

    # Create second boxplot for staking=False
    fig.add_trace(
        go.Box(
            x=trades_filtered[trades_filtered["staking"] == False]["creation_date"],
            y=trades_filtered[trades_filtered["staking"] == False][column_name],
            name="Staking False",
            marker_color=color_discrete[1],
            legendgroup="staking_false",
            showlegend=True,
        ),
        row=1,
        col=2,
    )

    # Update layout
    fig.update_layout(
        height=600,
        width=1200,
        title_text=f"Box Plot of {column_name} by Staking Status",
        showlegend=True,
    )

    # Update y-axes to have the same range
    fig.update_yaxes(matches="y")