The Relationship between news and stocks 18
2022. 8. 5. 23:05ㆍProject/뉴스기사로 인한 주가 등락 예측
728x90
반응형
코드
로컬 모델서버
from flask import Flask, request
from konlpy.tag import Kkma, Okt
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import keras
import re
app1 = Flask(__name__)
@app1.route('/') # 테스트용
def index() :
return '모델 서버 입니다. 여기로 직접 접근하면 안됩니다.'
@app1.route('/result', methods=['POST','GET']) # http://아이피:포트/api
def api() :
data = request.get_data()
value = str(data, 'utf-8')
value = clean_text(value)
return sentiment_predict(value)
def clean_text(d):
text = re.sub(r'\([^)]*\)', '', d)
text = re.sub(r'\[[^]]*\]', '', text)
text = re.sub(r'\<[^>]*\>', '', text)
pattern = r'[^가-힣0-9a-zA-Z\s]'
text = re.sub(pattern, ' ', text)
text = re.sub(r'사진', ' ', text)
text = re.sub(r'.*뉴스', ' ', text)
text = re.sub("\n", ' ', text)
text = re.sub(" +", " ", text)
return text
def sentiment_predict(new_sentence):
tokenizer = Tokenizer(43662, oov_token='OOV')
stopwords = [r'상승.*', r'하락.*', r'급등.*', r'급락.*', '상승세', '하락세', '폭등', '폭락', '오름세', '약세', '강세', '의', '가', '이', '은', '들', '는', '좀', '잘', '걍', '과', '도', '를', '으로', '자', '에', '와', '한', '하다', '에', '은', '는', '하']
new_token = [word for word in Okt().morphs(new_sentence) if word not in stopwords and not word.isdigit()]
tokenizer.fit_on_texts(new_token)
new_sequences = tokenizer.texts_to_sequences([new_token])
new_pad = pad_sequences(new_sequences, maxlen=800)
loaded_model = keras.models.load_model("./TextCNN_best_model(learning_rate).h5")
score = float(loaded_model.predict(new_pad))
return f'{score:.4f}'
if __name__ == '__main__' :
app1.run('0.0.0.0', port=5001, debug=True) # 포트 포워딩 필요
AWS 서버
from flask import Flask, render_template, request, session, redirect, url_for
import requests
from flaskext.mysql import MySQL
from datetime import timedelta
mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'stocks'
app.config['MYSQL_DATABASE_PASSWORD'] = 'Stocks!'
app.config['MYSQL_DATABASE_DB'] = 'User_Info'
app.config['MYSQL_DATABASE_HOST'] = 'AWS 주소'
app.config['MYSQL_DATABASE_PORT'] = 3306
app.secret_key = "9de85b1db330eddaf2a3e861d23db198baafee41a968f8365f4f9acf60fb2e09"
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=5) # 5분후 자동 로그아웃
mysql.init_app(app)
@app.route('/')
@app.route('/index')
def index():
if not session.get('userid'):
return render_template('index.html'), 200
#로그인 세션정보가 없을 경우
else:
userid = session.get('userid')
return render_template('index.html', userid=userid)
@app.route('/result', methods=["GET","POST"])
def result():
text = request.form.get('text')
time = request.form.get('time')
res = requests.post('http://외부 아이피 주소/result', data=text.encode('utf-8')) # 포트 포워딩 필요
value = float(res.text)
positive = value * 100
negative = (1 - value) * 100
return render_template('result.html', value = float(res.text), text=text, time=time, positive=positive, negative=negative), 200
@app.route('/notce')
def notice():
return render_template('notice.html'), 200
@app.route('/register', methods=['GET','POST'])
def register():
if request.method == 'POST':
userid = request.form.get('userid')
username = request.form.get('username')
password = request.form.get('password')
re_password = request.form.get('re_password')
conn = mysql.connect()
cursor = conn.cursor()
sql = "INSERT IGNORE INTO user_info VALUES ('%s', '%s', '%s')" % (userid, password, username)
cursor.execute(sql)
data = cursor.fetchall()
if not data and password == re_password:
conn.commit()
return redirect(url_for('index'))
else:
conn.rollback()
return "Register Failed"
cursor.close()
conn.close()
return render_template('register.html'), 200
@app.route('/login', methods=['GET','POST'])
def login():
if request.method=='GET':
return render_template('login.html')
else:
userid = request.form.get('userid')
password = request.form.get('password')
conn = mysql.connect()
cursor = conn.cursor()
sql = "SELECT userid, username FROM user_info WHERE userid = %s AND password = %s"
value = (userid, password)
cursor.execute("set names utf8")
cursor.execute(sql, value)
data = cursor.fetchall()
cursor.close()
conn.close()
if data != (): # 쿼리 데이터가 존재하면
session['userid'] = userid # userid를 session에 저장한다.
session['username'] = data[0][1]
return redirect('/index')
else:
return redirect('/login') # 쿼리 데이터가 없으면 출력
@app.route('/logout', methods=['GET'])
def logout():
session.pop('userid', None)
return redirect('/index')
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
포드 포워딩 ( SK )
SK 공유기 홈페이지 ( http://192.168.35.1 )
IP 추가
728x90
반응형
'Project > 뉴스기사로 인한 주가 등락 예측' 카테고리의 다른 글
The Relationship between news and stocks 19 (0) | 2022.08.08 |
---|---|
The Relationship between news and stocks 17 (0) | 2022.08.05 |
The Relationship between news and stocks 16 (0) | 2022.08.03 |
The Relationship between news and stocks 15 (0) | 2022.08.03 |
The Relationship between news and stocks 14 (0) | 2022.08.02 |