-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
1693 lines (1428 loc) · 53.7 KB
/
application.py
File metadata and controls
1693 lines (1428 loc) · 53.7 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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
application.py
"""
import collections
import datetime
import importlib
import json
import logging
import os
import secrets
import shutil
import time
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
import flask
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import requests
from PIL import Image
from dash import Dash
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
from flask import Flask, flash, redirect, url_for
from flask import render_template
from flask import request
from flask import send_from_directory
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, UserMixin, current_user, login_required, \
login_user, logout_user
from flask_mail import Message, Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from oauthlib.oauth2 import WebApplicationClient
from pylint import epylint as lint
from pylint.lint import Run
from tqdm import trange
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
from wtforms import BooleanField, PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, Length, \
ValidationError
from flask_moment import Moment
from errors.handlers import errors
from user import OAuthUser
from utils import s3_util, rds
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
application = Flask(__name__)
moment = Moment(application)
application.config.from_object("config")
db = SQLAlchemy(application)
bcrypt = Bcrypt(application)
login_manager = LoginManager(application)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
# create an s3 client
s3_client = s3_util.init_s3_client()
# email for send reset password token
mail = Mail(application)
# error handler
application.register_blueprint(errors)
# Google OAuth login client
client = WebApplicationClient(application.config["GOOGLE_CLIENT_ID"])
migrate = Migrate(application, db)
# dash object
dash_app = Dash(__name__, server=application, external_stylesheets=[dbc.themes.BOOTSTRAP],
url_base_pathname='/dash_plots/')
dash_app.validation_layout = True
dash_app._layout = html.Div()
# global variables for update dash dynamically depending on different user
OptionList = []
pnl_paths = []
TOTAL_CAPITAL = 10 ** 6
# endpoint routes
@application.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(application.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@application.route("/OAuth_login")
def oauth_login():
"""
OAuth login route
:return:
"""
google_provider_cfg = requests.get(application.config["GOOGLE_DISCOVERY_URL"]).json()
authorization_endpoint = google_provider_cfg["authorization_endpoint"]
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "/callback",
scope=["openid", "email", "profile"]
)
logger.info(request_uri)
return redirect(request_uri)
@application.route("/OAuth_login/callback")
def callback():
"""
OAuth login callback function from google auth page
:return:
"""
code = request.args.get("code")
google_provider_cfg = requests.get(application.config["GOOGLE_DISCOVERY_URL"]).json()
token_endpoint = google_provider_cfg["token_endpoint"]
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(application.config["GOOGLE_CLIENT_ID"], application.config["GOOGLE_CLIENT_SECRET"])
)
client.parse_request_body_response(json.dumps(token_response.json()))
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
url, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(url, headers=headers, data=body)
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
user_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
user_name = userinfo_response.json()["given_name"]
current_user.id = int(unique_id)
else:
return "User email not available or not verified by Google", 400
user = OAuthUser(
id_=unique_id, username=user_name, email=user_email, image_file=picture
)
if not OAuthUser.get(unique_id):
OAuthUser.create(unique_id, user_name, user_email, picture)
login_user(user)
return redirect(url_for("home"))
@login_manager.user_loader
def load_user(user_id):
"""
load user from OAuth user table if id is found otherwise load user from user table
:param user_id:
:return:
"""
if not OAuthUser.get(user_id):
return User.query.get(int(user_id))
return OAuthUser.get(user_id)
@application.route("/home")
@login_required
def home():
"""
home page after user login
:return: redirect user to upload page
"""
if current_user.is_authenticated:
conn = rds.get_connection()
if isinstance(current_user.email, str):
userid = pd.read_sql(
f"select id from backtest.user where email = '{current_user.email}';",
conn
)
current_user.id = int(userid['id'].iloc[0])
else:
current_user.email = str(current_user.email['email'].iloc[0])
userid = pd.read_sql(
f"select id from backtest.OAuth_user where email = '{current_user.email}';",
conn
)
current_user.id = int(userid['id'].iloc[0])
return redirect('upload')
return render_template('welcome.html', title='About')
@application.route("/")
@application.route("/welcome")
def about():
"""Welcome page of Backtesting platform, introduce features and functionalities of the platform
Returns:
function: render welcome.html page with title About
"""
return render_template('welcome.html', title='About')
@application.route("/login", methods=['GET', 'POST'])
def login():
"""authenticate current user to access the platform with valid email and
password registered in user table
Returns:
function: render login.html page with title Login, redirect user to home page
when successfully authenticate
"""
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password,
form.password.data) and user.is_approved == "Yes":
login_user(user, remember=form.remember.data)
current_user.email = form.email.data
current_user.user_type = user.user_type
current_user.id = user.id
next_page = request.args.get('next')
if next_page:
return redirect(next_page)
else:
if user.user_type == "user":
return redirect(url_for('home'))
elif user.user_type == "admin":
return redirect(url_for('admin'))
else:
flash('Login Unsuccessful. Please check email and password. Waiting for admin approval',
'danger')
return render_template('login.html', title='Login', form=form)
@application.route("/logout")
def logout():
"""
logout current user
:return:
"""
logout_user()
return redirect(url_for('about'))
@application.route("/upload")
@login_required
def upload():
"""home page of the backtesting platform, login is required to access this page
Returns:
function: render home.html page with context of login user's username
"""
current_user_init()
context = {"username": current_user.username,
"report": "",
"message": "Your upload check detail will be shown here"}
return render_template('upload.html', **context)
@application.route("/upload", methods=["POST"])
@login_required
def upload_strategy():
"""upload user strategy to alchemist database
Returns:
string: return message of upload status with corresponding pylint score
test_id = num -> it is for testing
need to avoid local and cloud storage difference
cloud path: e.g. s3://com34156-strategies/{user_id}/strategy_num/{strategy_name}.py
local has its own count
and cloud has its own count
"""
current_user_init()
if "user_file" not in request.files:
return "No user_file is specified"
if "strategy_name" not in request.form:
return "No strategy name specified"
file = request.files["user_file"]
name = request.form["strategy_name"]
if name == "":
return "Strategy name may not be empty"
if len(name) >= 50:
return "Strategy name should not be greater than 50 characters"
message = check_upload_file(file)
if message != "OK":
return message
# get the number of folders
bucket_name = application.config["S3_BUCKET"]
userid = str(current_user.id)
response = check_py_validity(file, userid)
if '/' not in response:
# move coverage to same page
# this will be checked by frontend
return response
local_path = response.split(':')[1]
status = response.split(':')[0]
# Run pylint again to get the message
# to pylint_stdout, which is an IO.byte
(pylint_stdout, _) = lint.py_run(local_path, return_std=True)
pylint_message = pylint_stdout.read()
pylint_message = clean_pylint_output(pylint_message)
# if the file is invalid, need to stop here
local_prefix = '/'.join(local_path.split('/')[:-1])
if "error" in status:
shutil.rmtree(local_prefix)
logger.info("pytest does not pass for a valid .py file")
report = (
"Your strategy has error or is not able to run! "
"Correct your file and upload again\n\n"
"*************Backend Check Information**************\n\n"
)
# append information
report = report + pylint_message
context = {
"username": current_user.username,
"report": report,
"message": "Your upload check detail will be shown here"
}
return render_template('upload.html', **context)
test_id = request.args.get('test_id')
conn = rds.get_connection()
cursor = conn.cursor()
if test_id is not None:
test_id = int(test_id)
logger.info("uploading testing file...")
cnt_loc = test_id
else:
logger.info("uploading user file...")
cursor.execute(
"SELECT MAX(strategy_id) as max_strategy FROM backtest.strategies"
)
first = cursor.fetchone()
cnt_loc = first['max_strategy']
cnt_loc += 1
logger.info("max + 1 is - %s", cnt_loc)
cloud_new_folder = "strategy" + str(cnt_loc)
strategy_folder = os.path.join(userid, cloud_new_folder)
# upload to s3 bucket
filepath = upload_strategy_to_s3(
local_path, bucket_name, strategy_folder
)
logger.info(f"file uploads to path {filepath}")
# store in database
cursor = conn.cursor()
timestamp = str(datetime.datetime.utcnow())
query = "INSERT INTO backtest.strategies (user_id, strategy_location, \
last_modified_date, last_modified_user, strategy_name) \
VALUES (%s,%s,%s,%s,%s)"
username = current_user.username
cursor.execute(
query, (current_user.id, filepath, timestamp, username, name)
)
conn.commit()
# remove the local file
shutil.rmtree(local_prefix)
logger.info(f"affected rows = {cursor.rowcount}")
message = "Your strategy " + name + \
" is uploaded successfully!"
context = {"username": current_user.username,
"report": pylint_message,
"message": message}
return render_template('upload.html', **context)
@application.route("/register", methods=['GET', 'POST'])
def register():
"""register a new user to the platform database
Returns:
function: render register.html page with title Register
"""
form = RegistrationForm()
if form.validate_on_submit():
if len(set(form.password.data)) < 5:
raise ValidationError('password should contain 5 or more unique characters')
hashed_password = bcrypt.generate_password_hash(
form.password.data).decode('utf-8')
if len(form.username.data) < 2 or len(form.username.data) > 20:
raise ValidationError
user = User(username=form.username.data,
email=form.email.data, password=hashed_password)
db.session.add(user)
db.session.commit()
flash(
f'Your account has been created! An admin is reviewing your registration request, please check-in again '
f'in 24 hours',
'success')
return redirect(url_for('login'))
return render_template(
'register.html', title='Register', form=form)
@application.route("/admin", methods=['GET', 'POST'])
@login_required
def admin():
"""render admin user page
Returns:
function: render falsk admin page
"""
return redirect('/admin/')
@application.route("/account", methods=['GET', 'POST'])
@login_required
def account():
"""display current user's account information and allows the current user to
update their username, email and upload profile image
Returns:
function : render account.html page with title account
"""
current_user_init()
form = UpdateAccountForm()
if hasattr(current_user, "password") and form.validate_on_submit():
if form.picture.data:
picture_file = save_picture(form.picture.data)
current_user.image_file = picture_file
current_user.username = form.username.data
current_user.email = form.email.data
db.session.commit()
flash('Your account has been updated!', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
else:
flash('Google account info cannot be updated', 'warning')
if hasattr(current_user, "password"):
image_file = url_for('static',
filename='profile_pics/' + current_user.image_file)
else:
image_file = current_user.image_file
return render_template('account.html', title='Account',
image_file=image_file, form=form)
@application.route('/strategies/<int:page_num>')
@login_required
def all_strategy(page_num):
"""display all user strategy as a table on the U.I.
Returns:
function: render strategies.html page
"""
if not isinstance(current_user.id, int):
conn = rds.get_connection()
current_user.email = str(current_user.email['email'].iloc[0])
userid = pd.read_sql(
f"select id from backtest.OAuth_user where email = '{current_user.email}';",
conn
)
current_user.id = int(userid['id'].iloc[0])
user_name = pd.read_sql(
f"select username from backtest.OAuth_user where email = '{current_user.email}';",
conn
)
current_user.username = str(user_name['username'].iloc[0])
current_user_id = current_user.id
username = current_user.username
strategies = Strategies.query.filter_by(
user_id=current_user_id).order_by(
Strategies.last_modified_date.desc()
).paginate(per_page=5, page=page_num, error_out=True)
return render_template(
'strategies.html',
df=strategies,
username=username
)
def get_strategy_to_local(strategy_location):
"""
get strategy from s3_resource to local
:param strategy_location: s3_resource loction
:return: local strategy file path
"""
current_user_init()
s3_resource = s3_util.init_s3()
if "/" not in strategy_location:
raise ValueError("Invalid Strategy Location.")
s3_url_obj = s3_util.S3Url(strategy_location)
user_folder = f"strategies/user_id_{current_user.id}"
if not os.path.exists(user_folder):
os.makedirs(user_folder)
open(f"{user_folder}/__init__.py", 'a').close()
local_strategy_path = f"{user_folder}/current_strategy.py"
logger.info(
f"-- s3_resource bucket: {s3_url_obj.bucket} -- s3_resource key: {s3_url_obj.key}")
s3_resource.Bucket(s3_url_obj.bucket).download_file(
s3_url_obj.key,
local_strategy_path
)
return local_strategy_path
@application.route('/strategy')
def display_strategy():
"""display select strategy with id
Returns:
function: strategy.html
"""
strategy_id = request.args.get('id')
strategy_location = get_strategy_location(strategy_id)
# step 1: aws cp file to local
local_strategy_path = get_strategy_to_local(strategy_location)
# step 2: display content
with open(local_strategy_path) as file:
code_snippet = file.read()
return render_template(
'strategy.html', strategy_id=strategy_id, code=code_snippet, num_bars=1)
@application.route('/strategy', methods=["POST"])
@login_required
def delete_strategy():
"""
delete strategy
:return: strategy html
"""
strategy_id = request.args.get('id')
strategy_location = get_strategy_location(strategy_id)
delete_strategy_by_user(strategy_location, strategy_id)
return redirect('strategies/1')
@application.route('/log_strategy')
def backtest_strategy():
"""
to help debugging and log strategy before entering into backtest loop
:return:
"""
strategy_id = request.args.get('id')
logger.info("**strategy id %s", str(strategy_id))
return "nothing"
@application.route('/backtest_progress')
def backtest_progress():
"""
backtest progress
:return:
"""
current_user_init()
strategy_id = request.args.get('id')
current_usr_id = current_user.id
n_days_back = 365 # we backtest using past 1 year's data
past_n_days = [
datetime.datetime.utcnow() -
datetime.timedelta(
days=i) for i in range(n_days_back)]
past_n_days = sorted(past_n_days)
s_module = importlib.import_module(
f"strategies.user_id_{current_usr_id}.current_strategy")
current_strategy = s_module.Strategy()
try:
strategy_cap = current_strategy.INIT_CAPITAL
except Exception as e_message:
logger.error(e_message)
def backtest():
"""
to backtest by iterating through each day
:return:
"""
pnl_df = {
'pnl': []
}
trades = collections.deque(maxlen=2) # note: we only keep track of today and last day
trades.append({'price': None, 'position': None})
for day_x in trange(n_days_back):
one_tenth = n_days_back // 10
if day_x % one_tenth == 0:
time.sleep(1)
progress = {0: min(100 * day_x // n_days_back, 100)}
trades.append({'price': current_strategy.get_price(), 'position': current_strategy.get_position()})
total_value_x = compute_pnl(trades[0].get('position'), trades[0].get('price'),
trades[1].get('price'), strategy_cap)
pnl_df['pnl'].append(total_value_x)
ret_string = f"data:{json.dumps(progress)}\n\n"
yield ret_string
yield f"data:{json.dumps({0: 100})}\n\n"
pnl_df['date'] = past_n_days
key = persist_to_s3(pnl_df, current_usr_id, strategy_id)
update_backtest_db(strategy_id, application.config["S3_BUCKET"], key)
return flask.Response(backtest(), mimetype='text/event-stream')
def persist_to_s3(pnl_df, current_usr, strategy_id):
"""
persist pnl dataframe to s3 under user and strategy path
:param pnl_df:
:param current_usr:
:param strategy_id:
:return: the key we persist to
"""
pnl_df = pd.DataFrame(pnl_df)
file_name = f'strategies/user_id_{current_usr}/backtest.csv'
try:
pnl_df.to_csv(file_name, index=True)
except Exception as e_msg:
logger.info(e_msg)
key = f"{current_usr}/backtest_{strategy_id}.csv"
_s3_client = s3_util.init_s3_client()
_s3_client.upload_file(file_name, application.config["S3_BUCKET"], key)
return key
def update_backtest_db(strategy_id, bucket, key):
"""
update backtest result to database
:param strategy_id:
:param bucket:
:param key:
:return:
"""
conn = rds.get_connection()
cursor = conn.cursor()
timestamp = datetime.datetime.utcnow()
query = "REPLACE INTO backtest.backtests (strategy_id, backtest_id," \
"pnl_location, last_modified_date) \
VALUES (%s,%s,%s,%s)"
cursor.execute(
query, (strategy_id, strategy_id,
f"s3://{bucket}/{key}", timestamp)
)
conn.commit()
def compute_pnl(previous_day_position, prev_day_price, current_day_price, init_cap):
"""
compute total values on a given day
:param previous_day_position: previous day position
:param prev_day_price: previous day price
:param current_day_price: current day price
:param init_cap initial capital
:return:
"""
pnl = 0
total_positions_usd = 0
if previous_day_position is None or prev_day_price is None:
return pnl
for ticker, percent in previous_day_position.items():
ticker_quantity = init_cap * percent / prev_day_price[ticker]
total_positions_usd += current_day_price[ticker] * ticker_quantity
pnl = total_positions_usd - init_cap
return pnl
@application.route('/results/', methods=['GET'])
@login_required
def user_results():
"""
Redirect to dosh route for visualization.
:return:
"""
current_user_init()
user_id = current_user.id
if type(user_id) == pd.DataFrame:
user_id = int(user_id['id'].iloc[0])
update_layout(user_id)
return redirect('/dash_plots')
@application.route('/dash_plots/', methods=['GET'])
@login_required
def render_reports():
"""
Redirect flask endpoint to dash server endpoint.
:return:
"""
return flask.redirect('/dash_plot')
@application.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
"""
send reset password request
:return:
"""
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RequestResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
send_reset_email(user)
flash('An email has been sent with instructions to reset your password.', 'info')
return redirect(url_for('login'))
return render_template('reset_request.html', title='Reset Password', form=form)
@application.route("/reset_password/<token>", methods=['GET', 'POST'])
def reset_token(token):
"""
reset secret token
:param token:
:return:
"""
if current_user.is_authenticated:
return redirect(url_for('home'))
user = User.verify_reset_token(token)
if user is None:
flash('That is an invalid or expired token', 'warning')
return redirect(url_for('reset_request'))
form = ResetPasswordForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user.password = hashed_password
db.session.commit()
flash('Your password has been updated! You are now able to log in', 'success')
return redirect(url_for('login'))
return render_template('reset_token.html', title='Reset Password', form=form)
def send_reset_email(user):
"""
send reset password request to the registered email
:param user:
:return:
"""
token = user.get_reset_token()
msg = Message('Password Reset Request',
sender='noreply@demo.com',
recipients=[user.email])
msg.body = f'''To reset your password, visit the following link:
{url_for('reset_token', token=token, _external=True)}
If you did not make this request then simply ignore this email and no changes will be made.
'''
mail.send(msg)
# helper functions
def current_user_init():
"""
current_user.field for oauth is pandas.Dataframe
we need to refactor current_user object
current_user is a global object
"""
conn = rds.get_connection()
if isinstance(current_user.email, str):
userid = pd.read_sql(
f"select id from backtest.user "
f"where email = '{current_user.email}';",
conn
)
current_user.id = int(userid['id'].iloc[0])
else:
current_user.email = str(current_user.email['email'].iloc[0])
userid = pd.read_sql(
f"select * from backtest.OAuth_user "
f"where email = '{current_user.email}';",
conn
)
current_user.id = int(userid['id'].iloc[0])
current_user.username = str(userid['username'].iloc[0])
current_user.image_file = str(userid['image_file'].iloc[0])
def save_picture(form_picture):
""" save user uploaded profile picture with formatted size in database
Args:
form_picture (picture in jpg format): user upload picture
Returns:
string: formatted picture string
"""
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(application.root_path, 'static/profile_pics',
picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
def get_user_strategies(user_id):
"""get user strategies according to user id
Args:
user_id (int): user identifier
Returns:
[type]: [description]
"""
strategies = rds.get_all_strategies(user_id)
return strategies
def get_strategy_location(strategy_id):
"""obtain the location of the strategy
Args:
strategy_id (int): strategy id
Returns:
location: location of the strategy
"""
conn = rds.get_connection()
strategies = pd.read_sql(
f"select * from backtest.strategies where strategy_id = {strategy_id};",
conn
)
s_loc = strategies['strategy_location'].iloc[0]
logger.info("[db] - %s}", s_loc)
return s_loc
def allowed_file(filename):
"""allowed file extension
Args:
filename ([string]): the file name including the extension
Returns:
[bool]: yes for allowed, no for not allowed
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in application.config[
"ALLOWED_EXTENSIONS"]
def check_upload_file(file):
"""check flask uploaded file
These attributes are also available
file.filename # The actual name of the file
file.content_type
file.content_length
file.mimetype
Args:
file ([request]): in flask.request["file"], io.byte type
"""
if file.filename == "":
return "Please select a file"
if not allowed_file(file.filename):
return "Your file extension type is not allowed"
if not file:
return "File not found. Please upload it again"
return "OK"
def check_py_validity(file, userid):
"""run pylint on file to check if correct
store file in local
Args:
file (str): flask file
userid(int)
new_foler: new_folder to save
"""
# keep a local copy of the file to run pylint
local_folder = os.path.join('strategies/', userid)
if not os.path.exists(local_folder):
os.makedirs(local_folder)
local_cnt = sum([1 for _ in os.listdir(local_folder)])
new_folder = "strategy" + str(local_cnt + 1)
local_strategy_folder = os.path.join(local_folder, new_folder)
os.makedirs(local_strategy_folder)
local_path = os.path.join(local_strategy_folder, file.filename)
logger.info("local testing path is %s", local_path)
file.save(local_path)
result = Run([local_path], do_exit=False)
# may be need threshold
logger.info(result.linter.stats)
if "global_note" not in result.linter.stats or \
result.linter.stats['global_note'] <= 0:
logger.info("wrong file, remove")
prefix = "has error:"
else:
prefix = "successful:"
logger.info(prefix)
if "successful" in prefix:
logger.info("uploaded: file has pylint score %s",
result.linter.stats['global_note'])
else:
logger.info("check does not pass")
response = prefix + local_path
return response
def upload_strategy_to_s3(
file, bucket_name, file_prefix):
"""
Notice that, in addition to ACL we set the ContentType key
in ExtraArgs to the file's content type. This is because by
default, all files uploaded to an S3 bucket have their
content type set to binary/octet-stream, forcing the
browser to prompt users to download the files instead of
just reading them when accessed via a public URL (which can
become quite annoying and frustrating for images and pdfs
for example)
Args:
file ([str]): local file path
bucket_name (str): bucket name
file_prefix (str): file prefix, like linxiao/strategy1
Returns:
[str]: upload file path
"""
filename = file.split('/')[-1]
upload_path = os.path.join(file_prefix, filename)
try:
logger.info("uploading file: to path %s", upload_path)
s3_client.upload_file(
file,
bucket_name,
upload_path,
)
except Exception as exp_msg:
logger.info("Something Happened: %s", exp_msg)
raise
return "{}{}".format(application.config["S3_LOCATION"], upload_path)
def delete_strategy_by_user(filepath, strategy_id=None):
"""delete a strategy
Args:
filepath (s3): real strategy path in s3, which is
the same as database
ASSUME THE FILEPATH is always valid
NOTE: Need to delete both s3 and database
:param strategy_id: default None
"""
logger.info(f"*****{filepath}\n\n")
bucket_name = application.config["S3_BUCKET"]
split_path = filepath.split('/')
prefix = "/".join(split_path[3:])
response = s3_client.list_objects_v2(
Bucket=bucket_name, Prefix=prefix
)