박하늘

backtest update

1 var express = require('express'); 1 var express = require('express');
2 const request = require('request'); 2 const request = require('request');
3 const TARGET_URL = 'https://api.line.me/v2/bot/message/reply' 3 const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
4 -const TOKEN = "sGB5EZq14+Lu4sc6Gt6NJ1Sx/rDtE1BsTyfZeNX42XVVjcgX1kk6/Uj1H40IQ1X3y8MzJLvKGifhioNCJLWQkWH2i95EtNDQyGn7Iqu6MnQRE7pg/z7klGgswS9974s0EKX90FcCfAIndNSYAG+d5gdB04t89/1O/w1cDnyilFU=" 4 +const PUSH_TARGET_URL = 'https://api.line.me/v2/bot/message/push'
5 +const TOKEN = "OVIxKODBqM8Pn2dpFtFeSLsDbBvApfTu88rh8wFGOzfvgvPjmBH0A4XKii97VxIDO9shYyTix4qGq32vwvL895Rbss5VSVEiU/XG5lOdyTLgECkSQKOdObSetZwcVHbGmzZJ+0Cz5vZrB5KuImOwrwdB04t89/1O/w1cDnyilFU="
5 const fs = require('fs'); 6 const fs = require('fs');
6 const path = require('path'); 7 const path = require('path');
7 const HTTPS = require('https'); 8 const HTTPS = require('https');
8 -const domain = "2016100990.oss2021.tk" 9 +const domain = "2017103989.oss2021.tk"
9 const sslport = 23023; 10 const sslport = 23023;
10 const bodyParser = require('body-parser'); 11 const bodyParser = require('body-parser');
11 var app = express(); 12 var app = express();
...@@ -13,6 +14,7 @@ var app = express(); ...@@ -13,6 +14,7 @@ var app = express();
13 var stockarr = []; 14 var stockarr = [];
14 var pastreply = ""; 15 var pastreply = "";
15 var tatic =""; 16 var tatic ="";
17 +var backtest = 0;
16 app.use('/simages', express.static(__dirname + '/src')); 18 app.use('/simages', express.static(__dirname + '/src'));
17 app.use(bodyParser.json()); 19 app.use(bodyParser.json());
18 app.post('/hook', function (req, res) { 20 app.post('/hook', function (req, res) {
...@@ -26,34 +28,32 @@ app.post('/hook', function (req, res) { ...@@ -26,34 +28,32 @@ app.post('/hook', function (req, res) {
26 console.log('[request message]', eventObj.message); 28 console.log('[request message]', eventObj.message);
27 if(eventObj.type == 'postback') 29 if(eventObj.type == 'postback')
28 { 30 {
29 - if(eventObj.postback.data == 'action=datetemp&selectId=1' && pastreply == "비중 추천"){ 31 + if(eventObj.postback.data == 'action=datetemp&selectId=1' && backtest == 0)
30 - console.log(stockarr); 32 + {
31 weight_recommend(eventObj.replyToken, eventObj.postback.params.date) 33 weight_recommend(eventObj.replyToken, eventObj.postback.params.date)
34 + stockarr.splice(0, stockarr.length);
32 tatic = "" 35 tatic = ""
33 pastreply = "" 36 pastreply = ""
34 } 37 }
35 - else 38 + else if(eventObj.postback.data == 'action=datetemp&selectId=1' && backtest == 1)
36 { 39 {
37 - optimizer(eventObj.replyToken, eventObj.postback.params.date) 40 + optimizer(eventObj.source.userId, eventObj.postback.params.date)
38 stockarr.splice(0, stockarr.length); 41 stockarr.splice(0, stockarr.length);
42 + tatic = ""
43 + pastreply = ""
44 + backtest = 0;
39 } 45 }
40 } 46 }
41 else 47 else
42 - { console.log(eventObj.message.text) 48 + {
43 - console.log(pastreply)
44 if(eventObj.message.text == '도움말' || eventObj.message.text == '주가 도움말' || eventObj.message.text == '비중 추천 도움말' || eventObj.message.text == '백테스트 도움말') 49 if(eventObj.message.text == '도움말' || eventObj.message.text == '주가 도움말' || eventObj.message.text == '비중 추천 도움말' || eventObj.message.text == '백테스트 도움말')
45 { 50 {
46 printhelp(eventObj.replyToken, eventObj.message.text) 51 printhelp(eventObj.replyToken, eventObj.message.text)
47 } 52 }
48 - else if(eventObj.message.text == '백테스트')
49 - {
50 - date(eventObj.replyToken, eventObj.message.text)
51 - }
52 else if (eventObj.message.text == '주가') 53 else if (eventObj.message.text == '주가')
53 { 54 {
54 basicinform_pre(eventObj.replyToken, eventObj.message.text) 55 basicinform_pre(eventObj.replyToken, eventObj.message.text)
55 pastreply = '주가' 56 pastreply = '주가'
56 - console.log(pastreply);
57 } 57 }
58 else if ( pastreply == '주가' && eventObj.message.text.indexOf(' ') == -1){ 58 else if ( pastreply == '주가' && eventObj.message.text.indexOf(' ') == -1){
59 basicinform(eventObj.replyToken, eventObj.message.text) 59 basicinform(eventObj.replyToken, eventObj.message.text)
...@@ -62,9 +62,13 @@ app.post('/hook', function (req, res) { ...@@ -62,9 +62,13 @@ app.post('/hook', function (req, res) {
62 weight_1(eventObj.replyToken, eventObj.message.text) 62 weight_1(eventObj.replyToken, eventObj.message.text)
63 pastreply = '비중 추천' 63 pastreply = '비중 추천'
64 } 64 }
65 - else if (pastreply = '비중 추천' && eventObj.message.text.indexOf(' ') != -1){ 65 + else if (eventObj.message.text == '백테스트'){
66 + weight_1(eventObj.replyToken, eventObj.message.text)
67 + pastreply = '비중 추천'
68 + backtest = 1
69 + }
70 + else if (pastreply == '비중 추천' && eventObj.message.text.indexOf(' ') != -1){
66 var holder = eventObj.message.text.split(' ') 71 var holder = eventObj.message.text.split(' ')
67 - console.log("holder",holder)
68 var i; 72 var i;
69 for(i = 0; i < holder.length; i++) 73 for(i = 0; i < holder.length; i++)
70 { 74 {
...@@ -74,7 +78,7 @@ app.post('/hook', function (req, res) { ...@@ -74,7 +78,7 @@ app.post('/hook', function (req, res) {
74 pastreply = "전략" 78 pastreply = "전략"
75 } 79 }
76 80
77 - else if (pastreply = "전략" && (eventObj.message.text == 'gmv' || eventObj.message.text == 'ms') || eventObj.message.text == 'rp'){ 81 + else if (pastreply == "전략" && (eventObj.message.text == 'gmv' || eventObj.message.text == 'ms') || eventObj.message.text == 'rp'){
78 tatic = eventObj.message.text 82 tatic = eventObj.message.text
79 pastreply = "비중 추천" 83 pastreply = "비중 추천"
80 date(eventObj.replyToken, eventObj.message.text) 84 date(eventObj.replyToken, eventObj.message.text)
...@@ -257,7 +261,7 @@ function printhelp(replyToken, message){ ...@@ -257,7 +261,7 @@ function printhelp(replyToken, message){
257 "messages":[ 261 "messages":[
258 { 262 {
259 "type":"text", 263 "type":"text",
260 - "text":"사용자 : 비중 추천 도움말\n챗봇 : 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자 : 종목명 입력 (ex 삼성전자, LG전자 ...)\n챗봇: 전략을 선택해주세요. (gmv, ms , rp)\n사용자: gmv, ms, rp 중 입력\n챗봇 : 케이스에 맞게 함수 실행 후 비중 출력" 264 + "text":"사용자 : 비중 추천\n챗봇 : 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자: 종목명 입력\n챗봇: 시작할 날짜를 입력해주세요\n사용자 : 종목명 입력 (ex 삼성전자, LG전자 ...)\n챗봇: 전략을 선택해주세요. (gmv, ms , rp)\n사용자: gmv, ms, rp 중 입력\n챗봇 : 케이스에 맞게 함수 실행 후 비중 출력"
261 } 265 }
262 ] 266 ]
263 } 267 }
...@@ -278,7 +282,7 @@ function printhelp(replyToken, message){ ...@@ -278,7 +282,7 @@ function printhelp(replyToken, message){
278 "messages":[ 282 "messages":[
279 { 283 {
280 "type":"text", 284 "type":"text",
281 - "text":"사용자 : 백테스트 도움말\n챗봇: 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자: 종목명 입력\n챗봇: 시작할 날짜를 입력해주세요\n사용자: 입력\n챗봇: 전략을 선택해주세요 (gmv, ms , rp)\n사용자: gmv,ms,rp 중 입력\n챗봇: 함수 실행 후 그래프 출력" 285 + "text":"사용자 : 백테스트\n챗봇: 포트폴리오에 넣을 종목을 선택해주세요(2 종목 이상)\n사용자: 종목명 입력\n챗봇: 시작할 날짜를 입력해주세요\n사용자: 입력\n챗봇: 전략을 선택해주세요 (gmv, ms , rp)\n사용자: gmv,ms,rp 중 입력\n챗봇: 함수 실행 후 그래프 출력"
282 } 286 }
283 ] 287 ]
284 } 288 }
...@@ -299,7 +303,7 @@ function printhelp(replyToken, message){ ...@@ -299,7 +303,7 @@ function printhelp(replyToken, message){
299 "messages":[ 303 "messages":[
300 { 304 {
301 "type":"text", 305 "type":"text",
302 - "text":"사용자 : 주가 도움말\n챗봇: 종목명을 알려주세요.\n사용자: 종목명 입력 (ex 삼성전자)\n챗봇 : 현재가 거래량 전일대비 수익률" 306 + "text":"사용자 : 주가\n챗봇: 종목명을 알려주세요.\n사용자: 종목명 입력 (ex 삼성전자)\n챗봇 : 현재가 거래량 전일대비 수익률"
303 } 307 }
304 ] 308 ]
305 } 309 }
...@@ -394,7 +398,7 @@ function basicinform(replyToken, message) { ...@@ -394,7 +398,7 @@ function basicinform(replyToken, message) {
394 398
395 } 399 }
396 400
397 -function optimizer(replyToken, sdate) { 401 +function optimizer(userid, sdate) {
398 sdate = sdate.toString(); 402 sdate = sdate.toString();
399 var pystring = '' 403 var pystring = ''
400 var i; 404 var i;
...@@ -406,16 +410,16 @@ function optimizer(replyToken, sdate) { ...@@ -406,16 +410,16 @@ function optimizer(replyToken, sdate) {
406 pystring += sdate; 410 pystring += sdate;
407 console.log(pystring); 411 console.log(pystring);
408 const spawn = require("child_process").spawn; 412 const spawn = require("child_process").spawn;
409 - const process = spawn("python", ["optimizer.py", pystring]); 413 + const process = spawn("python", ["optimizer.py", pystring, 'backtest', tatic]);
410 const Callback = (data) => { 414 const Callback = (data) => {
411 request.post( 415 request.post(
412 { 416 {
413 - url: TARGET_URL, 417 + url: PUSH_TARGET_URL,
414 headers: { 418 headers: {
415 'Authorization': `Bearer ${TOKEN}` 419 'Authorization': `Bearer ${TOKEN}`
416 }, 420 },
417 json: { 421 json: {
418 - "replyToken":replyToken, 422 + "to": userid,
419 "messages":[ 423 "messages":[
420 { 424 {
421 "type":"text", 425 "type":"text",
......
...@@ -606,36 +606,37 @@ else: ...@@ -606,36 +606,37 @@ else:
606 for i in range(len(args)-1): 606 for i in range(len(args)-1):
607 assets.append(args[i]) 607 assets.append(args[i])
608 gravity.append(0) 608 gravity.append(0)
609 + data = back_test().backtest_data(assets,gravity,args[-1], '2021-06-01',10000000,6, 'monthly', sys.argv[3])
609 610
610 - data = back_test().backtest_data(assets,gravity,args[-1], '2021-06-01',10000000,6, 'monthly', 'gmv')
611 611
612 612
613 - #data = back_test().backtest_data(['삼성전자','LG전자','호텔신라'],[0.1,0.1,0.8],'2020-01-01', '2021-01-02',10000000,6, 'monthly', 'gmv') 613 +
614 - # data = back_test().backtest_data(['삼성전자','LG전자'],[0.1,0.1],'2020-01-01', '2021-01-02',10000000,6, 'monthly', 'gmv') 614 +#data = back_test().backtest_data(['삼성전자','LG전자','카카오','호텔신라'],[0,0,0,0],'2020-01-01', '2021-01-02',10000000,6, 'monthly', 'ms')
615 - x = data['pfo_return'][0]['Date'] 615 +# data = back_test().backtest_data(['삼성전자','LG전자'],[0.1,0.1],'2020-01-01', '2021-01-02',10000000,6, 'monthly', 'gmv')
616 - y = data['pfo_return'][0]['acc_return ratio'] 616 +x = data['pfo_return'][0]['Date']
617 - y2 = data['bench'][0]['KOSPI_acc_return'] 617 +y = data['pfo_return'][0]['acc_return ratio']
618 - y3 = data['bench'][0]['S&P500_acc_return'] 618 +y2 = data['bench'][0]['KOSPI_acc_return']
619 - x_ticks = [] 619 +y3 = data['bench'][0]['S&P500_acc_return']
620 - for i,j in enumerate(x): 620 +x_ticks = []
621 +for i,j in enumerate(x):
621 if (i % 6) == 0: 622 if (i % 6) == 0:
622 x_ticks.append(j) 623 x_ticks.append(j)
623 else: 624 else:
624 x_ticks.append('') 625 x_ticks.append('')
625 - x_ticks[-1]= x[-1] 626 +x_ticks[-1]= x[-1]
626 - plt.figure(figsize=(10,5)) 627 +plt.figure(figsize=(10,5))
627 - ax=plt.gca() 628 +ax=plt.gca()
628 - ax.xaxis.set_major_locator(ticker.MultipleLocator(12)) 629 +ax.xaxis.set_major_locator(ticker.MultipleLocator(12))
629 - plt.plot(x,y,label = 'gmv result') 630 +plt.plot(x,y,label = 'gmv result')
630 - plt.plot(x,y2 ,label = 'kospi result') 631 +plt.plot(x,y2 ,label = 'kospi result')
631 - plt.plot(x,y3, label = 's&p500 result') 632 +plt.plot(x,y3, label = 's&p500 result')
632 - plt.xticks(x_ticks,rotation=60) 633 +plt.xticks(x_ticks,rotation=60)
633 - plt.xlabel('Date') 634 +plt.xlabel('Date')
634 - plt.ylabel('Return') 635 +plt.ylabel('Return')
635 - plt.title('result') 636 +plt.title('result')
636 - plt.legend() 637 +plt.legend()
637 - plt.show() 638 +plt.show()
638 - plt.savefig("./src/test.png", dpi = 100) 639 +plt.savefig("./src/test.png", dpi = 100)
639 - print("end") 640 +print("end")
640 641
641 642
......