Fredtt3 commited on
Commit
10477f4
verified
1 Parent(s): 17526d3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import numpy as np
4
+ import pandas as pd
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.optim as optim
8
+ from datetime import datetime
9
+ from sklearn.preprocessing import MinMaxScaler
10
+
11
+ # Crear y entrenar el modelo
12
+ def train_model(x_train, y_train, input_size, prediction_days, dim_feedforward, epochs=100):
13
+ class Transformer(nn.Module):
14
+ def __init__(self, input_size, prediction_days, dim_feedforward):
15
+ super(Transformer, self).__init__()
16
+ self.input_size = input_size
17
+ self.fc1 = nn.Linear(input_size, dim_feedforward)
18
+ self.fc2 = nn.Linear(dim_feedforward, dim_feedforward * 2)
19
+ self.fc3 = nn.Linear(dim_feedforward * 2, dim_feedforward * 4)
20
+ self.fc4 = nn.Linear(dim_feedforward * 4, dim_feedforward * 8)
21
+ self.fc5 = nn.Linear(dim_feedforward * 8, dim_feedforward * 16)
22
+ self.fc6 = nn.Linear(dim_feedforward * 16, dim_feedforward * 32)
23
+ self.fc7 = nn.Linear(dim_feedforward * 32, dim_feedforward * 64)
24
+ self.fc8 = nn.Linear(dim_feedforward * 64, dim_feedforward * 128)
25
+ self.fc9 = nn.Linear(dim_feedforward * 128, dim_feedforward * 256)
26
+ self.fc10 = nn.Linear(dim_feedforward * 256, prediction_days)
27
+ self.dropout = nn.Dropout(0.2)
28
+
29
+ def forward(self, x):
30
+ x = x.reshape(-1, self.input_size)
31
+ x = self.fc1(x)
32
+ x = nn.functional.relu(x)
33
+ x = self.dropout(x)
34
+ x = self.fc2(x)
35
+ x = nn.functional.relu(x)
36
+ x = self.dropout(x)
37
+ x = self.fc3(x)
38
+ x = nn.functional.relu(x)
39
+ x = self.dropout(x)
40
+ x = self.fc4(x)
41
+ x = nn.functional.relu(x)
42
+ x = self.dropout(x)
43
+ x = self.fc5(x)
44
+ x = nn.functional.relu(x)
45
+ x = self.dropout(x)
46
+ x = self.fc6(x)
47
+ x = nn.functional.relu(x)
48
+ x = self.dropout(x)
49
+ x = self.fc7(x)
50
+ x = nn.functional.relu(x)
51
+ x = self.dropout(x)
52
+ x = self.fc8(x)
53
+ x = nn.functional.relu(x)
54
+ x = self.dropout(x)
55
+ x = self.fc9(x)
56
+ x = nn.functional.relu(x)
57
+ x = self.dropout(x)
58
+ x = self.fc10(x)
59
+
60
+ return x
61
+
62
+
63
+ model = Transformer(input_size=input_size, prediction_days=1, dim_feedforward=dim_feedforward)
64
+ criterion = nn.MSELoss()
65
+ optimizer = optim.Adam(model.parameters(), lr=0.001)
66
+
67
+ for epoch in range(epochs):
68
+ inputs = torch.from_numpy(x_train).float()
69
+ labels = torch.from_numpy(y_train).float().unsqueeze(1)
70
+
71
+ # Limpiando los gradientes
72
+ optimizer.zero_grad()
73
+
74
+ # Forward
75
+ outputs = model(inputs)
76
+ loss = criterion(outputs, labels)
77
+
78
+ # Backward y optimizaci贸n
79
+ loss.backward()
80
+ optimizer.step()
81
+
82
+ if (epoch + 1) % 10 == 0:
83
+ st.write("Epoch: {}/{} | Loss: {:.4f}".format(epoch + 1, epochs, loss.item()))
84
+
85
+ return model
86
+
87
+ # P谩gina principal
88
+ st.title("Stock Price Prediction")
89
+
90
+ # Interfaz para ingresar el ticket de la empresa
91
+ company = st.text_input("Enter the company ticket:")
92
+
93
+ # Interfaz para ingresar la cantidad de d铆as a predecir
94
+ prediction_days = st.slider("Enter the number of days to predict:", min_value=1, max_value=30, value=7)
95
+
96
+ # Bot贸n para iniciar el entrenamiento
97
+ if st.button("Start Training"):
98
+ # Descarga de datos hist贸ricos de la compa帽铆a deseada
99
+ ticker = yf.Ticker(company)
100
+ hist = ticker.history(start="2015-01-01", end=datetime.now())
101
+
102
+ # Escalando los datos
103
+ scaler = MinMaxScaler(feature_range=(0, 1))
104
+ scaled_data = scaler.fit_transform(hist["Close"].values.reshape(-1, 1))
105
+
106
+ # Creando el conjunto de entrenamiento
107
+ x_train = []
108
+ y_train = []
109
+
110
+ for i in range(prediction_days, len(scaled_data)):
111
+ x_train.append(scaled_data[i - prediction_days : i, 0])
112
+ y_train.append(scaled_data[i, 0])
113
+
114
+ x_train, y_train = np.array(x_train), np.array(y_train)
115
+ x_train = np.reshape(x_train, (x_train.shape[0], prediction_days))
116
+
117
+ # Entrenar el modelo
118
+ trained_model = train_model(x_train, y_train, input_size=x_train.shape[1], prediction_days=1, dim_feedforward=21)
119
+
120
+ # Predicci贸n
121
+ future_prediction = []
122
+ last_x = scaled_data[-prediction_days:]
123
+
124
+ for i in range(prediction_days):
125
+ future_input = torch.from_numpy(last_x).float().reshape(1, prediction_days)
126
+ future_price = trained_model(future_input)
127
+ future_prediction.append(future_price.detach().numpy()[0][0])
128
+ last_x = np.append(last_x[1:], future_price.detach().numpy().reshape(-1, 1))
129
+
130
+ # Desescalando los resultados
131
+ prediction = scaler.inverse_transform(np.array(future_prediction).reshape(-1, 1))
132
+
133
+ # Imprimiendo los resultados
134
+ st.subheader("Predictions:")
135
+ for i, price in enumerate(prediction):
136
+ st.write("Day {}: {:.2f}".format(i + 1, price[0]))
137
+
138
+ # Bot贸n de reinicio
139
+ if st.button("Reset"):
140
+ st.experimental_rerun()