-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
65 lines (51 loc) · 2.01 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
"""
This module contains the Flask app for stock prediction.
"""
from flask import Flask, render_template, jsonify
from flask_cors import CORS
import pandas as pd
import numpy as np
from tensorflow import keras
app = Flask(__name__)
CORS(app)
model = keras.models.load_model('model.h5')
# load the latest data from the CSV file
df_ = pd.read_csv('AAPL_daily_candles.csv')
@app.route('/')
def home():
"""
Renders the 'index.html' template, which serves as the homepage for the application.
Returns:
--------
str:
The rendered HTML content of the 'index.html' template.
"""
return render_template('index.html')
@app.route('/predict')
def predict():
"""
Load the latest data from a CSV file, prepare the data for training and testing the
machine learning model, train the model, make predictions on the test data,
calculate the mean squared error (MSE) and mean absolute error (MAE), calculate the accuracy,
and return a JSON response containing the accuracy, MSE, and a prediction for the next day.
Returns:
JSON: A JSON response containing the accuracy, MSE, and a prediction for the next day.
"""
# use the last 30 rows for testing and the rest for training
x_train = df_.iloc[:-30, 0].values.reshape(-1, df_.iloc[:-30, 0].shape[0], 1)
y_train = df_.iloc[:-30, 1].values
x_test = df_.iloc[-30:, 0].values.reshape(-1, df_.iloc[-30:, 0].shape[0], 1)
y_test = df_.iloc[-30:, 1].values
# train the model on the training data
model.fit(x_train, y_train, epochs=10)
# make predictions on the test data
y_pred = model.predict(x_test)
# calculate accuracy and MSE
mse = np.mean(np.square(y_pred - y_test))
mae = np.mean(np.abs(y_pred - y_test))
accuracy = (1 - mae) * 100
# get the prediction for the next day
next_day_prediction = model.predict(x_test[-1].reshape(1, 30, 1))[0][0]
return jsonify({'accuracy': accuracy, 'mse': mse, 'prediction': next_day_prediction})
if __name__ == '__main__':
app.run(debug=True)