File size: 7,467 Bytes
868fa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7457269
 
868fa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7457269
868fa55
 
7457269
868fa55
 
 
 
 
 
 
 
 
 
5f9cb55
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
import yfinance as yf
import pickle
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error
import gradio as gr
import pickle
import warnings
warnings.filterwarnings("ignore", category=FutureWarning, module="numpy._core.fromnumeric")

# Charger et préparer les données
df = pd.read_csv("datatset/sphist.csv")
df['Date'] = pd.to_datetime(df["Date"])
df = df.sort_values(by='Date', ascending=True)

year_i = -1
day_i = -1
mean_d = np.nan
std_d = np.nan
std_d_v = np.nan
df['std 5'] = np.nan
df['mean 5'] = np.nan
mean_y = np.nan
std_y = np.nan
ratio = np.nan
df['mean 365'] = np.nan
df['std 365'] = np.nan
j = 0
for i, elt in df.iterrows():
    if j==0:
        j+=1
        continue
    if df.iloc[j-1]['Date'] - df.iloc[0]['Date'] > timedelta(days=365):
        if year_i == -1:
            year_i = 0
        mean_y = np.mean(df.iloc[year_i:j-1]['Open'])
        std_y = np.std(df.iloc[year_i:j-1]['Open'])
        year_i += 1
    df.iloc[j, df.columns.get_loc("std 365")] = std_y
    df.iloc[j, df.columns.get_loc("mean 365")] = mean_y
    if df.iloc[j-1]['Date'] - df.iloc[0]['Date'] > timedelta(days=5):
        if day_i == -1:
            day_i = 0
        mean_d = np.mean(df.iloc[day_i:j-1]["Open"])
        std_d = np.std(df.iloc[day_i:j-1]['Open'])
        std_d_v = np.std(df.iloc[day_i:j-1]['Volume'])
        day_i += 1
    df.iloc[j, df.columns.get_loc("mean 5")] = mean_d
    df.iloc[j, df.columns.get_loc("std 5")] = std_d
    j += 1

# Ajouter des indicateurs utiles pour notre modèle de ML
df['5 Days Open'] = df['Open'].rolling(center=False, window=5).mean()
df['Year'] = df['Date'].apply(lambda x: x.year)
df['5 Days High'] = df['High'].rolling(center=False, window=5).mean()
df['5 Days Low'] = df['Low'].rolling(center=False, window=5).mean()
df['5 Days Volume'] = df['Volume'].rolling(center=False, window=5).mean()

# Déplacer la colonne d'un jour
df['5 Days Open'] = df['5 Days Open'].shift(1)
df = df.dropna(axis=0)
df = df.drop(df[df["Date"] < datetime(year=1951, month=1, day=3)].index, axis=0)
test = df[df['Date'] >= datetime(year=2013, month=1, day=1)]
train = df[df['Date'] < datetime(year=2013, month=1, day=1)]

# Entraîner le modèle
lr = LinearRegression().fit(train.drop(columns=["Open", 'High', 'Low', 'Volume', 'Adj Close', 'Close', 'Date']), train["Close"])
pred = lr.predict(test.drop(columns=["Open", 'High', 'Low', 'Volume', 'Adj Close', 'Close', 'Date']))

with open('linear_regression_model.pkl', 'wb') as file:
    pickle.dump(lr, file)
# Calculer les erreurs
err = mean_absolute_error(test["Close"], pred)
errP = mean_absolute_percentage_error(test["Close"], pred)

# Créer le DataFrame pour le tableau
result_df = pd.DataFrame({'Predictions': pred, 'Actual Close': test['Close']})

# Fonction pour afficher l'erreur et le tableau
def display_results():
    return str(err), str(errP), result_df

# Définir le symbole du S&P 500
def predire(date):
    # Définir le symbole du S&P 500
    symbole = "^GSPC"

    # selected_date=datetime.fromtimestamp(date)
    day, month,year  = int(date.split('/')[0]),int(date.split('/')[1]),int(date.split('/')[2])
    print(year,month,day)
    # Définir la période
    def get_datas(year,month,day):
        date_debut = datetime(year=year-2, month=month, day=day)
        date_fin = datetime.now()

        # Télécharger les données
        data = yf.download(symbole, start=date_debut, end=date_fin)
        return data
    # Sélectionner les colonnes souhaitées
    df = get_datas(year,month,day)[['Open', 'High', 'Low', 'Close', 'Volume']]
    df['Date'] = df.index
    # Afficher les premières lignes

    def add_features(df):
        year_i = -1
        day_i = -1
        mean_d = np.nan
        std_d = np.nan
        df['std 5'] = np.nan
        df['mean 5'] = np.nan
        mean_y = np.nan
        std_y = np.nan
        df['mean 365'] = np.nan
        df['std 365'] = np.nan
        j = 0
        for i, elt in df.iterrows():
            if j==0:
                j+=1
                continue
            if (df.iloc[j-1]['Date'] - df.iloc[0]['Date'] > timedelta(days=365)).iloc[0]:
                if year_i == -1:
                    year_i = 0
                mean_y = np.mean(df.iloc[year_i:j-1]['Open'])
                std_y = np.std(df.iloc[year_i:j-1]['Open'])
                year_i += 1
            df.iloc[j, df.columns.get_loc("std 365")] = std_y
            df.iloc[j, df.columns.get_loc("mean 365")] = mean_y
            if (df.iloc[j-1]['Date'] - df.iloc[0]['Date'] > timedelta(days=5)).iloc[0]:
                if day_i == -1:
                    day_i = 0
                mean_d = np.mean(df.iloc[day_i:j-1]["Open"])
                std_d = np.std(df.iloc[day_i:j-1]['Open'])
                day_i += 1
            df.iloc[j, df.columns.get_loc("mean 5")] = mean_d
            df.iloc[j, df.columns.get_loc("std 5")] = std_d
            j += 1
        # Ajouter des indicateurs utiles pour notre modèle de ML
        df['5 Days Open'] = df['Open'].rolling(center=False, window=5).mean()
        df['Year'] = df['Date'].apply(lambda x: x.year)
        df['5 Days High'] = df['High'].rolling(center=False, window=5).mean()
        df['5 Days Low'] = df['Low'].rolling(center=False, window=5).mean()
        df['5 Days Volume'] = df['Volume'].rolling(center=False, window=5).mean()
        
        # Déplacer la colonne d'un jour
        df['5 Days Open'] = df['5 Days Open'].shift(1)
        
        df = df.dropna(axis=0)
        print(df.tail())
        return df

    df= add_features(df)
    test=df
    test.iloc[-2:-1]['Close']
    # Charger le modèle à partir du fichier pickle
    with open('linear_regression_model.pkl', 'rb') as file:
        lr = pickle.load(file)


    a= lr.predict(df[df['Date'] == datetime(year=year,month=month,day=day)].drop(columns=["Open", 'High', 'Low', 'Volume', 'Close', 'Date']))[-1],float(df[df['Date'] == datetime(year=year,month=month,day=day)]['Close'][symbole])

    return a




# Créer l'interface Gradio
with gr.Blocks() as demo:
    gr.Markdown("# Linear Regression Model Results")
    gr.Markdown("""This model was trained on S&P 500 stock price before 2013. The predictions below are taken betweek 2013 and 2015.
                
    0.4% of average error was reached using LinearRegression.""")
    with gr.Row():
        with gr.Column():
            error = gr.Textbox(label="Mean Absolute Error")
            errorP = gr.Textbox(label="Mean Absolute Percentage Error")
            table = gr.Dataframe(label="Predictions vs Actual Close Prices")

    with gr.Row():
        with gr.Column():
            btn = gr.Button("Show Results")
    gr.Markdown("## Dynamic prediction")
    gr.Markdown("Select a weekday before today and it will predict the close price of S&P 500 at your date.")
    with gr.Row():
        with gr.Column():
            date_input = gr.Textbox(label="Select Date (DD/MM/YYYY)")
            prediction = gr.Textbox(label="Prediction")
        with gr.Column():
            true_val = gr.Textbox("Real close price")
    with gr.Row():
        with gr.Column():
            btn2 = gr.Button("Predict for your date")
        
    btn.click(display_results, outputs=[error, errorP, table])
    btn2.click(predire, inputs=date_input, outputs=[prediction, true_val])
# Lancer l'interface Gradio
demo.launch()