-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaave.py
308 lines (286 loc) · 8.47 KB
/
aave.py
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
from utils import client,todayTimestamp
from gql import gql
import json
from utils import TIMESTAMP_PER_YEAR
import pandas as pd
import numpy as np
from config import RAY_DECIMALS
AAVE_API="https://api.thegraph.com/subgraphs/name/aave/protocol-v2"
def lookDecimals(pool,symbol):
return pool.loc[symbol]['decimals']
class Aave:
def __init__(self,url=AAVE_API):
self.client = client(url)
query='''query{
reserves(first: 1000,subgraphError: allow) {
id
underlyingAsset
symbol
decimals
}
}'''
cli = self.client
response = cli.execute(gql(query))
data=pd.json_normalize(response['reserves'])
data=data.set_index('symbol')
self.pools=data
def currentUsers(self,symbol):
cli=self.client
reserveid=self.pools.loc[symbol]['id']
decimals=self.pools.loc[symbol]['decimals']
lastid=''
query=''' query($reserve_id: String!,$lastID:ID!){
userReserves(first: 1000,
where: {reserve: $reserve_id,id_gt:$lastID},
subgraphError: allow,
orderBy: id,
orderDirection: asc)
{
id
reserve
{
id
}
user
{
id
}
currentATokenBalance
currentStableDebt
currentVariableDebt
currentTotalDebt
}
}'''
finished = 0
agg = pd.DataFrame()
while (finished == 0):
try:
params = {
"reserve_id": reserveid,
"lastID": lastid,
}
res = cli.execute(gql(query),variable_values=params)
res=pd.json_normalize(res['userReserves']).drop('reserve.id',axis=1)
# Rebase all the columns to decimals
col_to_rebase=[col for col in res.columns if col[:3]=='cur']
res[col_to_rebase]=res[col_to_rebase].astype('float')
res[col_to_rebase]=res[col_to_rebase]/10**decimals
if len(res) == 0:
return agg
else:
res.index = res.id
lastid = res.iloc[-1].id # .values
res = res.drop('id', axis=1)
res=res.set_index('user.id')
agg = agg.append(res)
except:
return agg
return agg
def userPosition(self,userids):
"""
:param self:
:param userids: list of userids we want to analyse
:return:all the user positions broken down by token
"""
lastid = ''
cli=self.client
finished=0
agg = pd.DataFrame()
query=''' query($user_list:[String!]!,$lastID:ID!){
userReserves(first: 1000, where: {user_in: $user_list,id_gt:$lastID},orderBy: id,
orderDirection: asc,subgraphError: allow)
{
id
reserve
{
id
symbol
}
user
{
id
}
currentATokenBalance
scaledATokenBalance
currentStableDebt
currentVariableDebt
currentTotalDebt
}
}'''
while (finished == 0):
try:
params = {
"user_list": list(userids),
"lastID":lastid
}
res = cli.execute(gql(query), variable_values=params)
res = pd.json_normalize(res['userReserves']).drop('reserve.id', axis=1)
res['Decimals'] = res.apply(lambda x: lookDecimals(self.pools, x['reserve.symbol']),axis=1)
# Rebase all the columns to decimals
col_to_rebase = [col for col in res.columns if col[:3] == 'cur']
for c in col_to_rebase:
res[c] = res[c].astype('float')
res[c] = res[c] / 10 ** res['Decimals']
if len(res) == 0:
return agg
else:
res.index = res.id
lastid = res.iloc[-1].id # .values
res = res.drop('id', axis=1)
res = res.set_index('user.id')
agg = agg.append(res)
except:
return agg
return agg
def getPositions(self, ids, steps=100):
"""
Need to cut the pool in small bits to retrieve all the information
Args:
ids: list of id we want to get all the positions
steps: how many accounts to retrieve data simultaneously
"""
nb_gp = int(np.ceil(len(ids) / steps))
groups = [ids[(i) * steps:(i + 1) * steps] for i in range(0, nb_gp)]
return pd.concat([self.userPosition(gp) for gp in groups])
def getTransactions(self):
cli = self.client
query = '''{
userTransactions (first: 1000,where:{timestamp_lte:1635793127,user:"0x0000006daea1723962647b7e189d311d757fb793"},orderBy:timestamp,orderDirection:asc){
id
pool {
id
}
user {
id
borrowedReservesCount
}
timestamp
__typename
...on Deposit {
pool {
id
}
reserve {
id
symbol
name
decimals
}
amount
}
...on RedeemUnderlying{
pool {
id
}
reserve {
id
symbol
name
decimals
}
amount
}
...on Borrow{
pool {
id
}
reserve {
id
symbol
name
decimals
}
amount
}
...on UsageAsCollateral{
pool {
id
}
reserve {
id
symbol
name
decimals
}
fromState
toState
}
...on Repay{
pool {
id
}
reserve {
id
symbol
name
decimals
}
amount
}
}
} '''
res = cli.execute(gql(query))
return res
def getHistBorrowRate(self,pool_id,start_ts,end_ts):
"""
:param pool_id: pool id we want
:param start_ts: starting time stamp
:param end_ts: ending timestamp
:return:
"""
cli = self.client
finished = 0
tstart=start_ts*1
agg = pd.DataFrame()
query = ''' query($tstart:Int!,$reserve_id:ID!,$tend:Int!){
reserveParamsHistoryItems(first: 1000,
where: {reserve:$reserve_id,timestamp_gte:$tstart,timestamp_lt:$tend}
orderBy: timestamp
orderDirection: asc,subgraphError: allow
) {
variableBorrowRate
variableBorrowIndex
id
timestamp
reserve {
id
decimals
}
}
}'''
while (finished == 0):
try:
params = {
"tstart": tstart,
"tend":end_ts,
"reserve_id":pool_id
}
res = cli.execute(gql(query), variable_values=params)
res = pd.json_normalize(res['reserveParamsHistoryItems']).drop(['reserve.id','id'], axis=1)
decimals=res.iloc[0]['reserve.decimals'].astype('int64')
# Rebase all the columns to decimals
col_to_rebase = ['variableBorrowRate','variableBorrowIndex']
for c in col_to_rebase:
res[c] = res[c].astype('float')
res[c] = res[c] / 10 ** RAY_DECIMALS
tstart = int(res['timestamp'].max()) + 1
res=res.set_index('timestamp')
agg=agg.append(res)
except:
return agg
pool=Aave()
token='stETH'
pool_usdc=pool.currentUsers(token)
w=pool_usdc.getHistBorrowRate()
"""
userdata=pool.currentUsers('FRAX')
print('l')
res = pd.json_normalize(tr['userTransactions'])
res.to_csv('transactions_wintermute.csv')
print('l')
"""
"""
userdata=pool.currentUsers('DAI')
pos=pool.userPosition(userdata.index[0:100])
print('finished')
"""