Surya152002 commited on
Commit
821b9f1
·
1 Parent(s): 8ae32d4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ from sklearn.preprocessing import MinMaxScaler
5
+ from tensorflow.keras.models import load_model
6
+ import plotly.graph_objs as go
7
+ import numpy as np
8
+ import base64
9
+
10
+ # Function to make predictions using the LSTM model
11
+ def make_predictions(model, data, scaler, look_back, prediction_days):
12
+ predictions = []
13
+ scaled_data = scaler.transform(data[-look_back:].reshape(-1, 1))
14
+ scaled_data = scaled_data.reshape((1, look_back, 1))
15
+
16
+ for _ in range(prediction_days):
17
+ # Make the prediction
18
+ predicted_price = model.predict(scaled_data)
19
+ # Inverse transform to get the actual price
20
+ predicted_price = scaler.inverse_transform(predicted_price)
21
+ predictions.append(predicted_price.ravel()[0])
22
+
23
+ # Append prediction to scaled_data for making subsequent predictions
24
+ next_input = scaler.transform(predicted_price.reshape(-1, 1))
25
+ scaled_data = np.append(scaled_data[:, 1:, :], [next_input], axis=1)
26
+
27
+ return predictions
28
+
29
+
30
+ # Function to download prediction data as a CSV file
31
+ def get_table_download_link(df):
32
+ csv = df.to_csv(index=True)
33
+ b64 = base64.b64encode(csv.encode()).decode()
34
+ href = f'<a href="data:file/csv;base64,{b64}" download="predictions.csv">Download CSV file</a>'
35
+ return href
36
+
37
+
38
+ # Streamlit app layout
39
+ st.title('Real-time Crypto Prediction with LSTM')
40
+
41
+ # User input parameters (no longer in the sidebar)
42
+ st.header('User Input Parameters')
43
+ ticker = st.selectbox('Select Ticker', ('BTC-USD', 'ETH-USD', 'LTC-USD'))
44
+ start_date = st.date_input('Start date', pd.to_datetime('2021-01-01'))
45
+ end_date = st.date_input('End date', pd.to_datetime('today'))
46
+ look_back = st.number_input('Look Back Period',value=60)
47
+ prediction_days = st.slider('Days to Predict', 1, 30, 5)
48
+
49
+ # Load pre-trained LSTM model and scaler
50
+ with st.spinner('Loading model and scaler...'):
51
+ model = load_model('./best_model.h5') # make sure to use the correct path to your model
52
+ scaler = MinMaxScaler(feature_range=(0, 1)) # Assuming the scaler was fitted to the training data
53
+
54
+ # Fetch historical data from yfinance
55
+ with st.spinner(f'Downloading {ticker} data...'):
56
+ data = yf.download(ticker, start=start_date, end=end_date)
57
+ st.success('Downloaded data successfully!')
58
+
59
+ # Prepare data for prediction
60
+ data_close = data['Close'].values.reshape(-1, 1)
61
+ scaler.fit(data_close)
62
+
63
+ # Make real-time prediction
64
+ if len(data_close) >= look_back:
65
+ with st.spinner('Making predictions...'):
66
+ predictions = make_predictions(model, data_close, scaler, look_back, prediction_days)
67
+ # Convert predictions to a list of Python floats
68
+ predictions_list = [float(pred) for pred in predictions]
69
+ st.success('Predictions made successfully!')
70
+
71
+ # Plot the results using Plotly
72
+ fig = go.Figure()
73
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines+markers', name='Close Price'))
74
+ # Add predicted prices to the plot
75
+ prediction_dates = pd.date_range(start=data.index[-1], periods=prediction_days+1, closed='right')
76
+ fig.add_trace(go.Scatter(x=prediction_dates, y=predictions_list, mode='lines+markers', name='Predicted Price', marker=dict(color='red')))
77
+ fig.update_layout(title='Cryptocurrency Price Prediction', xaxis_title='Date', yaxis_title='Price', legend_title='Legend')
78
+ st.plotly_chart(fig, use_container_width=True)
79
+
80
+
81
+
82
+
83
+ # Display download link for predictions with actual prices included
84
+ prediction_dates = pd.date_range(start=data.index[-1], periods=prediction_days+1, closed='right')
85
+ prediction_df = pd.DataFrame(index=prediction_dates)
86
+ prediction_df['Predicted Price'] = predictions_list
87
+ prediction_df['Actual Price'] = data['Close'][-prediction_days:].values
88
+ st.markdown(get_table_download_link(prediction_df), unsafe_allow_html=True)
89
+
90
+ # Display the last prediction
91
+ st.write(f'Last Predicted Closing Price for {ticker}: ${predictions_list[-1]:.2f}')
92
+
93
+ # Simulate investment results based on predictions
94
+ # Simulate investment results based on the last prediction
95
+ initial_account_balance = 1000000
96
+ account_balance_predicted = initial_account_balance
97
+ account_balance_actual = initial_account_balance
98
+
99
+ # Get the last actual closing price and the last predicted price
100
+ last_invest_price = data['Close'].iloc[-prediction_days-1] # Price at which we "buy"
101
+ last_sell_price_predicted = predictions_list[-1] # Predicted price at which we "sell"
102
+ last_sell_price_actual = data['Close'].iloc[-prediction_days] if prediction_days <= len(data['Close']) else last_sell_price_predicted
103
+
104
+ # Update account balances based on the last day's prediction and actual price
105
+ account_balance_predicted += (last_sell_price_predicted - last_invest_price) * (account_balance_predicted / last_invest_price)
106
+ account_balance_actual += (last_sell_price_actual - last_invest_price) * (account_balance_actual / last_invest_price)
107
+
108
+
109
+ # Assuming investing at the closing price and selling at the next day's predicted/actual price
110
+ for i in range(1, prediction_days + 1):
111
+ invest_price = data['Close'].iloc[-i-1] # Price at which we "buy"
112
+ sell_price_predicted = predictions_list[-i] # Predicted price at which we "sell"
113
+ sell_price_actual = data['Close'].iloc[-i] if i <= len(data['Close']) else sell_price_predicted
114
+
115
+ # Update account balances
116
+ account_balance_predicted += (sell_price_predicted - invest_price) * (account_balance_predicted / invest_price)
117
+ account_balance_actual += (sell_price_actual - invest_price) * (account_balance_actual / invest_price)
118
+
119
+ # Display simulated investment results
120
+ st.write(f"Initial Account Balance: ${initial_account_balance:,.2f}")
121
+ st.write(f"Account Balance based on Predictions: ${account_balance_predicted:,.2f}")
122
+ st.write(f"Account Balance based on Actual Prices: ${account_balance_actual:,.2f}")
123
+
124
+ else:
125
+ st.error('Not enough data to make a prediction.')
126
+
127
+ # Refresh the page to update the predictions
128
+ if st.button("Refresh Predictions"):
129
+ st.experimental_rerun()