-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataStoreInterface.py
189 lines (150 loc) · 5.3 KB
/
dataStoreInterface.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
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 22:57:25 2021
Author: Giddy Physicist
Data Store Interface Module
Part of the PETA-Bot hackathon repo. This module is used to interact with the
historical price data files. The interaction involves loading a database,
querying for a new data row, appending the row to the database structure, and
pushing the new database structure back into the file storage locaiton.
There are two main locations for the database files:
(1) local csv files
(2) decentralized file server using IPFS
"""
import os
import subprocess
import pandas as pd
import time
import queryPriceData as QPD
def getIPNSurl():
"""
return the URL to the fixed IPNS (named IPFS hash) where the directory is
stored containing the price history csv data for the analytics app.
Returns
-------
ipnsDir : str
string url to fixed IPNS location of slowly backed up price history data.
"""
ipnsDir = r'https://gateway.ipfs.io/ipns/k51qzi5uqu5djuxohf4c5kj838m14tgygn1hrey2cmda0y2efzwu03w63em3qt/'
return ipnsDir
def getStreamlitHostingUrl():
"""
returns the hosting URL to the streamlit analytics app for price edge viewing.
Returns
-------
streamlitHostingUrl : str
hosting URL for streamlit analytics app.
"""
streamlitHostingUrl = r'https://share.streamlit.io/giddyphysicist/chainlinkhackathon2021/main/analysisDashboard.py'
return streamlitHostingUrl
def queryDataPoint():
result = QPD.queryAllPricesDodoAndChainlink(chain='mainnet')
# queryTime = datetime.datetime.now().timestamp()
queryTime = time.time()
dataRowDict = {}
for pair in result:
pairData = result[pair]
dataRow = {'queryTimestamp':queryTime,
'dodoPriceEdgePercentage':(pairData['chainlinkPrice'] - pairData['dodoPrice'])/(0.5*(pairData['chainlinkPrice']+pairData['dodoPrice']))*100,
'timeLag':queryTime - pairData['chainlinkTimestamp'],
'chainlinkTimestamp':pairData['chainlinkTimestamp'],
'dodoPrice':pairData['dodoPrice'],
'chainlinkPrice':pairData['chainlinkPrice'],
'currencyPair':pair
}
dataRowDict[pair] = dataRow
return dataRowDict
def loadDatabase(currencyPair, location='file'):
"""
extract historical price data for the specified currency pair name.
Loads the data into a pandas dataframe object
Parameters
----------
currencyPair : str
currency pair name string.
location : TYPE, optional
DESCRIPTION. The default is 'file'.
Raises
------
NotImplementedError
DESCRIPTION.
Exception
DESCRIPTION.
Returns
-------
df : pandas.core.frame.DataFrame
Pandas dataframe object containing .
"""
if location.lower()=='file':
if not os.path.isdir('./data'):
os.makedirs('./data')
file = f'./data/{currencyPair}.csv'
if not os.path.isfile(file):
#pull from ipfs
ipnsDir = getIPNSurl()
ipnsFile = ipnsDir + f'{currencyPair}.csv'
df = pd.read_csv(ipnsFile)
df.to_csv(file,index=False)
else:
df = pd.read_csv(file)
elif location.lower() =='ipfs':
# raise NotImplementedError()
try:
ipnsDir = getIPNSurl()
ipnsFile = ipnsDir + f'{currencyPair}.csv'
except:
print(f'WARNING -- COULD NOT EXTRACT {currencyPair} file from IFPS. Reverting to local file.')
ipnsFile = f'./data/{currencyPair}.csv'
df = pd.read_csv(ipnsFile)
else:
raise Exception('UNRECOGNIZED INPUT. LOCATION INPUT MUST SET TO "FILE" or "IPFS"')
return df
#implement IPFS database using IPNS name service or DNS mapping
def loadAllDatabases(location='file'):
"""
Load Pandas dataframes for all currency pairs
Parameters
----------
location : TYPE, optional
DESCRIPTION. The default is 'file'.
Returns
-------
dfs : list<pandas.core.frame.DataFrame>
List of pandas dataframes containing historical price data for each
currency pair.
"""
currencyPairs = QPD.getCurrencyPairs()
dfs = []
for currencyPair in currencyPairs:
dfs.append(loadDatabase(currencyPair, location=location))
return dfs
def appendDataRowToDatabase(dataRow, database):
"""
Append a data row to the input pandas dataframe object, and return a new
dataframe object
Parameters
----------
dataRow : TYPE
DESCRIPTION.
database : TYPE
DESCRIPTION.
Returns
-------
df : TYPE
DESCRIPTION.
"""
df = database.append(dataRow,ignore_index=True)
return df
def pushDatabase(database,location='file',currencyPair=None):
if location.lower()=='file':
if currencyPair is None:
currencyPair = database.currencyPair.unique().tolist()[0]
database.to_csv(f'./data/{currencyPair}.csv',index=False)
return
elif location.lower()=='ipfs':
#PUSH UPDATED DATABASE TO IPFS
#implement IPFS
raise NotImplementedError()
pass
else:
raise Exception('UNRECOGNIZED INPUT. LOCATION INPUT MUST SET TO "FILE" or "IPFS"')