-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
171 lines (129 loc) · 4.75 KB
/
server.py
File metadata and controls
171 lines (129 loc) · 4.75 KB
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
###########
# IMPORTS #
###########
import os
import json
import redis
import pandas as pd
from flask import Flask
from flask import request
from flask import Response
from flask import jsonify
from flask import abort
from flask.ext.cache import Cache
from flask_sslify import SSLify
from lib.efficient_frontier import efficient_frontier
###############
# ENVIRONMENT #
###############
app = Flask(__name__)
app.config['DEBUG'] = os.environ.get('DEBUG', False)
if not app.config['DEBUG']:
sslify = SSLify(app)
if app.config['DEBUG']:
cache = Cache(app,config={'CACHE_TYPE': 'null'})
else:
cache = Cache(app, config={
'CACHE_TYPE': 'memcached',
'CACHE_MEMCACHED_SERVERS': [ os.environ['MEMCACHEDCLOUD_SERVERS'] ],
'CACHE_MEMCACHED_USERNAME': os.environ['MEMCACHEDCLOUD_USERNAME'],
'CACHE_MEMCACHED_PASSWORD': os.environ['MEMCACHEDCLOUD_PASSWORD']
})
redis_conn = redis.StrictRedis.from_url(os.environ['REDIS_URL'])
###################
# UTILITY METHODS #
###################
def check_for_authorization():
auth_token = os.environ['AUTH_TOKEN']
provided_token = request.headers.get('Authorization') or request.args.get('auth_token')
if (provided_token and provided_token == auth_token):
return True
else:
return abort(403)
def get_key_in_json(key, json):
if json is None:
return abort(400)
if key not in json:
return abort(422)
return json[key]
######################
# APP HELPER METHODS #
######################
def covariance_matrix(asset_ids):
# No need to memoize this unless jsonify is taking lots of time - data from redis
# Covariance matrix is a *DataFrame*
json = redis_conn.get('covariance_matrix')
df = pd.io.json.read_json(json)
asset_ids_set = set(asset_ids)
available_asset_ids_set = set(df.index.values)
asset_ids_to_eliminate = list(available_asset_ids_set - asset_ids_set)
return df.drop(asset_ids_to_eliminate, axis=0).drop(asset_ids_to_eliminate, axis=1)
def cholesky_decomposition(asset_ids):
# No need to memoize this unless jsonify is taking lots of time - data from redis
# Cholesky decomp matrix is a *DataFrame*
json = redis_conn.get('cholesky_decomposition')
df = pd.io.json.read_json(json)
asset_ids_set = set(asset_ids)
available_asset_ids_set = set(df.index.values)
asset_ids_to_eliminate = list(available_asset_ids_set - asset_ids_set)
return df.drop(asset_ids_to_eliminate, axis=0).drop(asset_ids_to_eliminate, axis=1)
def mean_returns(asset_ids):
# No need to memoize this unless jsonify is taking lots of time - data from redis
# Mean returns is a *Series*
json = redis_conn.get('mean_returns')
df = pd.io.json.read_json(json, typ='series')
asset_ids_set = set(asset_ids)
available_asset_ids_set = set(df.index.values)
asset_ids_to_eliminate = list(available_asset_ids_set - asset_ids_set)
return df.drop(asset_ids_to_eliminate)
@cache.memoize()
def build_efficient_frontier_for(asset_ids):
app.logger.warning("[Cache Miss] Building efficient frontier for: %s" % asset_ids)
means = mean_returns(asset_ids)
covars = covariance_matrix(asset_ids)
return efficient_frontier(asset_ids, means, covars)
##########
# ROUTES #
##########
# Utility routes
@app.route('/')
def root():
return 'Hello World!'
@app.route('/health')
def health():
return "OK", 200
@app.route('/clear_cache', methods=["GET"])
def clear_cache():
check_for_authorization()
cache.clear()
return jsonify({"success": True, "message": "Cache cleared."})
# App routes
@app.route('/assets', methods=['GET'])
def assets_route():
check_for_authorization()
return jsonify( json.loads(redis_conn.get('asset_list')) )
@app.route('/etfs', methods=['GET'])
def etfs_route():
check_for_authorization()
return jsonify( json.loads(redis_conn.get('etf_list')) )
@app.route('/cholesky', methods=['GET'])
def cholesky_route():
check_for_authorization()
asset_ids = get_key_in_json('asset_ids', request.json)
asset_ids.sort()
app.logger.info("Received cholesky request for: %s" % asset_ids)
cholesky_dataframe_as_array = cholesky_decomposition(asset_ids).values
as_flat_array = cholesky_dataframe_as_array.flatten().tolist() # Just do .tolist() if you want it as an array of arrays
return jsonify( { "cholesky_decomposition": as_flat_array } )
@app.route('/calc', methods=["POST"])
def cla_calc_route():
check_for_authorization()
asset_ids = get_key_in_json('asset_ids', request.json)
asset_ids.sort()
app.logger.info("Received CLA calc request for: %s" % asset_ids)
return jsonify(build_efficient_frontier_for(asset_ids))
##########
# LOADER #
##########
if __name__ == '__main__':
app.run()