-
Notifications
You must be signed in to change notification settings - Fork 11
/
app.py
executable file
·464 lines (389 loc) · 14.1 KB
/
app.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
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
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
from predictStocks import predictStocks
from twitter_analyze import twitter_analyze
from yahoo_finance import Share
from datetime import datetime, timedelta
import requests
# import mysql.connector
app = Flask(__name__)
# cnx = mysql.connector.connect(user=os.environ['JW_USERNAME'], password=os.environ['JW_KEY'], host=os.environ['JW_HOST'], database='xcqk05aruwtw0kew')
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
res = json.dumps(res, indent=4)
print(res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
print r
return r
def processRequest(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
# logMessage(req)
if req.get("result").get("action") == "CurrentPrice.price":
res = makeWebhookResult(getStockCurrentPrice(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Prediction.stockForecast":
res = makeWebhookResult(getStockPrediction(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Feelings.analyze":
res = makeWebhookResult(getTwitterFeelings(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "DividendDate.Date":
res = makeWebhookResult(getStockDividendPayDate(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Stock.info":
res = makeWebhookResult(getStockInfo(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Stock.historical":
res = makeWebhookResult(getHistoricalData(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Decision.Classification":
res = makeWebhookResult(getStockClassification(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "input.welcome":
res = makeWebhookResult(getWelcome(req), req, stock_symbol)
return res
elif req.get("result").get("action") == "Visualize.chart":
res = makeWebhookResult(getChartURL(req), req, stock_symbol)
return res
else:
return {}
def getChartURL(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
chart_url = "https://www.etoro.com/markets/" + stock_symbol + "/chart"
return chart_url
def logMessage(req):
print "LOGGING!"
originalRequest = req.get("originalRequest")
source = ''
if originalRequest != None:
source = originalRequest.get("source")
if source != 'facebook':
print "not from facebook"
return
data = originalRequest.get("data")
time_stamp = data.get("timestamp")
sender_id = data.get("sender").get("id")
# recipient_id = data.get("recipient").get("id")
message = data.get("message")
text = message.get("text")
# log incoming messagesw
response = requests.post("http://api.botimize.io/messages?apikey=ZG2H9YHCZJQS9JTOTXXHL842QDGK5VHI", data={
"platform": "facebook",
"direction": "incoming",
"raw": {
"object":"page",
"entry":[
{
"id":"986319728104533",
"time":1458692752478,
"messaging":[
{
"sender":{
"id":sender_id
},
"recipient":{
"id":"986319728104533"
}
}
]
}
]
}
})
print response
print response.content
print "Success"
def getWelcome(req):
response = 'Hi! I am here to help predict financial markets. My predictions are not 100% accurate!'
return response
# analyze feelings intent
def getTwitterFeelings(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
if stock_symbol is None:
return None
twitter_analyzer = twitter_analyze()
twitter_data = twitter_analyzer.analyze_feelings(stock_symbol)
print 'Twitter data:'
print twitter_data
data = {}
data['positive'] = twitter_data[0]
data['negative'] = twitter_data[1]
data['neutral'] = twitter_data[2]
total = data['positive'] + data['negative'] + data['neutral']
positive_percent = percentage(data['positive'], total)
negative_percent = percentage(data['negative'], total)
neutral_percent = percentage(data['neutral'], total)
data_string = 'positive: ' + str(positive_percent) + '% negative: ' + str(negative_percent) + '% neutral: ' + str(neutral_percent) + '%'
return data_string
# make percentage and round
def percentage(part, whole):
return round(100 * float(part)/float(whole), 2)
# for intent prediction
def getStockPrediction(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
time = parameters.get("date-period")
if stock_symbol is None:
return None
num_of_days = 3
if time != '' and time is not None:
num_of_days = extract_days(time)
prediction = predictStocks()
predicted_values = prediction.stocksRegression(stock_symbol, int(num_of_days))
predicted_list = predicted_values.tolist()
clean_list = cleanPrediction(predicted_list)
return '\n'.join(str(v) for v in clean_list)
def cleanPrediction(list_prices):
clean_list = []
for price in list_prices:
price_float = float(price[0])
str_price = '%.2f' % price_float
clean_list.append(str_price)
return clean_list
# invest or not
def getStockClassification(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
time = parameters.get("date-period")
if stock_symbol is None:
return None
num_of_days = 14
if time != '' and time is not None:
num_of_days = extract_days(time)
prediction = predictStocks()
predicted_values = prediction.stocksNeuralNet(stock_symbol, int(num_of_days))
predicted_decision = predicted_values.tolist()[-1][0]
if time != '' and time is not None:
return predicted_decision.lower() + ' (decision for next ' + str(num_of_days-1) + ' days)'
return predicted_decision.lower() + ' (decision for next two weeks)'
def extract_days(time):
num_days = 3
dates = time.split('/')
if dates is not None:
first = datetime.strptime(dates[0], "%Y-%m-%d").date()
second = datetime.strptime(dates[1], "%Y-%m-%d").date()
num_days = (second - first).days+1
else:
dates = time.split(' ')
if dates is not None:
if dates[0].isdigit():
num_days = int(dates[0])
return num_days
# intent current price
def getStockCurrentPrice(req):
# db test
# print 'Accessing database'
# cursor = cnx.cursor(buffered = True)
# str_call = 'SELECT * FROM USER_BASIC_INFO'
# cursor.execute(str_call);
# data = cursor.fetchone()
# cnx.commit()
# cursor.close()
# print data
# db test
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
if stock_symbol is None:
return None
prediction = predictStocks()
current_price = prediction.getCurrentPrice(stock_symbol)
return str(current_price)
# intent dividend date
def getStockDividendPayDate(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
if stock_symbol is None:
return None
stock = Share(stock_symbol)
pay_date = stock.get_dividend_pay_date()
if pay_date is None:
return 'No Dividend Date Avaliable'
return str(pay_date)
def getStockInfo(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
if stock_symbol is None:
return None
stock = Share(stock_symbol)
info = stock.get_info()
return str(info)
# last 5 days data
def getHistoricalData(req):
result = req.get("result")
parameters = result.get("parameters")
stock_symbol = parameters.get("stock_symbol")
if stock_symbol is None:
return None
last_days = 5
past_days_ago = datetime.now() - timedelta(days=last_days)
past_days_ago_str = past_days_ago.strftime('%Y-%m-%d')
now = datetime.now().date()
now_str = now.strftime('%Y-%m-%d')
stock = Share(stock_symbol)
return str(stock.get_historical(past_days_ago_str, now_str))
# return to API.AI
def makeWebhookResult(data, req, stock_symbol):
action = req.get("result").get("action")
originalRequest1 = req.get("originalRequest")
source = ''
if originalRequest1 != None:
source = originalRequest1.get("source")
if action == "CurrentPrice.price":
speech = "Current Price for the stock is $" + str(data)
next_speech = "Predict " + stock_symbol
# news_speech = "News for " + stock_symbol
# news_url = "http://finance.yahoo.com/quote/" + stock_symbol
chart_speech = "Chart for " + stock_symbol
chart_url = "https://www.etoro.com/markets/" + stock_symbol + "/chart"
feelings_speech = 'Feelings ' + stock_symbol
if source == 'facebook':
return {
"speech": speech,
"displayText": speech,
"source": "apiai-wallstreetbot-webhook",
"data": {
"facebook": {
"attachment": {
"type": "template",
"payload": {
"template_type":"button",
"text":speech,
"buttons":[
{
"type":"web_url",
"url":chart_url,
"title":chart_speech,
"webview_height_ratio": "compact"
},
{
"type":"postback",
"title":next_speech,
"payload":next_speech
},
{
"type":"postback",
"title":feelings_speech,
"payload":feelings_speech
}
]
}
}
}
}
}
elif action == "Prediction.stockForecast":
speech = "Predicted price for coming days: " + str(data)
elif action == "Feelings.analyze":
speech = "Feelings for " + stock_symbol + ": " + str(data)
elif action == "Decision.Classification":
speech = "I think we should " + str(data) + " " + stock_symbol
if source == 'facebook':
return {
"speech": speech,
"displayText": speech,
"source": "apiai-wallstreetbot-webhook",
"data": {
"facebook": {
"text":speech + '. Type away more questions!',
"quick_replies":[
{
"content_type":"text",
"title":"Need help?",
"payload":"Help"
}
]
}
}
}
elif action == "input.welcome":
speech = str(data)
elif action == "Visualize.chart":
speech = 'Here is your chart:'
chart_url = str(data)
chart_speech = "Chart for " + stock_symbol
if source == 'facebook':
return {
"speech": speech,
"displayText": speech,
"source": "apiai-wallstreetbot-webhook",
"data": {
"facebook": {
"attachment": {
"type": "template",
"payload": {
"template_type":"button",
"text":speech,
"buttons":[
{
"type":"web_url",
"url":chart_url,
"title":chart_speech,
"webview_height_ratio": "compact"
},
]
}
}
}
}
}
else:
speech = str(data)
print("Response:")
print(speech)
return {
"speech": speech,
"displayText": speech,
"source": "apiai-wallstreetbot-webhook"
}
#gif example
# Image example
# "data": {
# "facebook": {
# "attachment": {
# "type": "image",
# "payload": {
# "url": "https://www.testclan.com/images/testbot/siege/weapons/assault-rifles.jpg"
# }
# }
# }
# }
# quick reply template
# "message":{
# "text":"Pick a color:",
# "quick_replies":[
# {
# "content_type":"text",
# "title":"Red",
# "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
# },
# {
# "content_type":"text",
# "title":"Green",
# "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
# }
# ]
# }
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print "Starting app on port %d" % port
app.run(debug=False, port=port, host='0.0.0.0')