CoolFace
Apppublic

Krishna2903/crypto

sourceHugging Faceopenrailupdated 2y agoView on Hugging Face
0likes
app.py248 linesDownload Raw Back to root
1import numpy as np
2import pandas as pd
3import matplotlib.pyplot as plt
4from pandas_datareader import data
5from keras.models import load_model
6import streamlit as st
7import plotly.graph_objects as go
8import datetime as dt
9import yfinance as yf
10import pandas_ta as ta
11from plotly.subplots import make_subplots
12from datetime import timedelta
13from sklearn.preprocessing import MinMaxScaler
14
15st.set_page_config(page_title='CryptoPredict 2.0', page_icon=':chart_with_upwards_trend:')
16st.title('CryptoCurrency Price Prediction')
17
18
19stocks = [ 'BTC-USD', 'ETH-USD', 'BNB-USD', 'SOL-USD', 'ADA-USD', 'XRP-USD', 'DOT-USD', 'DOGE-USD',
20          'AVAX-USD', 'LTC-USD', 'MATIC-USD', 'SHIB-USD']
21
22
23
24st.markdown('#')
25
26with st.expander(""):
27    col1, col2, col3 = st.columns([1, 1, 1])
28
29
30
31    col2.markdown("CRYPTO CURRENCIES")
32    col2.markdown("""
33    | Cryptocurrency | Ticker Symbol |
34    | --- | --- |
35    | Bitcoin | BTC-USD |
36    | Ethereum | ETH-USD |
37    | Binance Coin | BNB-USD |
38    | Solana | SOL-USD |
39    | Cardano | ADA-USD |
40    | XRP | XRP-USD |
41    | Polkadot | DOT-USD |
42    | Dogecoin | DOGE-USD |
43    | Avalanche | AVAX-USD |
44    | Litecoin | LTC-USD |
45    | Polygon | MATIC-USD |
46    | Shiba Inu | SHIB-USD |
47    """)
48
49
50
51
52user_input = st.selectbox('Enter Stock Ticker', stocks)
53
54st.markdown('# ')
55
56st.markdown('##### Select The Date Range For Technical Analysis')
57
58START = st.date_input('START:', value=pd.to_datetime("2017-01-01"))
59TODAY = st.date_input('END (Today):', value=pd.to_datetime("today"))
60
61stock_info = yf.Ticker(user_input).fast_info
62
63# stock_info.keys() for other properties you can explore
64
65
66st.subheader(user_input)
67
68
69def load_data(user_input):
70    yf.pdr_override()
71    daata = data.get_data_yahoo(user_input, start=START, end=TODAY)
72    daata.reset_index(inplace=True)
73    return daata
74
75
76df = load_data(user_input)
77
78# describing data
79
80st.subheader('Data Range 2017-Today')
81# df= df.reset_index()
82
83st.write(df.tail(10))
84st.write(df.describe())
85# Force lowercase (optional)
86df.columns = [x.lower() for x in df.columns]
87
88
89
90st.subheader("Prediction of Stock Price")
91
92# train test split
93data_training = pd.DataFrame(df['close'][0:int(len(df) * 0.70)])
94data_testing = pd.DataFrame(df['close'][int(len(df) * 0.70): int(len(df))])
95
96st.write("training data: ", data_training.shape)
97st.write("testing data: ", data_testing.shape)
98
99# scaling of data using min max scaler (0,1)
100
101
102scaler = MinMaxScaler(feature_range=(0, 1))
103
104data_training_array = scaler.fit_transform(data_training)
105
106# Load model
107model = load_model("lstm_model_2.h5")
108
109# testing part
110past_100_days = data_training.tail(30)
111
112final_df = past_100_days.append(data_testing, ignore_index=True)
113
114input_data = scaler.fit_transform(final_df)
115
116x_test = []
117y_test = []
118
119for i in range(100, input_data.shape[0]):
120    x_test.append(input_data[i - 100: i])
121    y_test.append(input_data[i, 0])
122x_test, y_test = np.array(x_test), np.array(y_test)
123
124y_predicted = model.predict(x_test)
125
126scaler = scaler.scale_
127
128scale_factor = 1 / scaler[0]
129
130y_predicted = y_predicted * scale_factor
131
132y_test = y_test * scale_factor
133
134
135
136st.subheader('Stock Price Prediction by Date')
137
138df1 = df.reset_index()['close']
139scaler = MinMaxScaler(feature_range=(0, 1))
140df1 = scaler.fit_transform(np.array(df1).reshape(-1, 1))
141
142# datemax="24/06/2022"
143datemax = dt.datetime.strftime(dt.datetime.now() - timedelta(1), "%d/%m/%Y")
144datemax = dt.datetime.strptime(datemax, "%d/%m/%Y")
145x_input = df1[:].reshape(1, -1)
146temp_input = list(x_input)
147temp_input = temp_input[0].tolist()
148
149date1 = st.date_input("Enter Date in this format yyyy-mm-dd")
150
151result = st.button("Predict")
152# st.write(result)
153if result:
154    from datetime import datetime
155
156    my_time = datetime.min.time()
157    date1 = datetime.combine(date1, my_time)
158    # date1=str(date1)
159    # date1=dt.datetime.pastime(time_str,"%Y-%m-%d")
160
161    nDay = date1 - datemax
162    nDay = nDay.days
163
164    date_rng = pd.date_range(start=datemax, end=date1, freq='D')
165    date_rng = date_rng[1:date_rng.size]
166    lst_output = []
167    n_steps = x_input.shape[1]
168    i = 0
169
170    while i <= nDay:
171
172        if len(temp_input) > n_steps:
173            # print(temp_input)
174            x_input = np.array(temp_input[1:])
175            print("{} day input {}".format(i, x_input))
176            x_input = x_input.reshape(1, -1)
177            x_input = x_input.reshape((1, n_steps, 1))
178            # print(x_input)
179            yhat = model.predict(x_input, verbose=0)
180            print("{} day output {}".format(i, yhat))
181            temp_input.extend(yhat[0].tolist())
182            temp_input = temp_input[1:]
183            # print(temp_input)
184            lst_output.extend(yhat.tolist())
185            i = i + 1
186        else:
187            x_input = x_input.reshape((1, n_steps, 1))
188            yhat = model.predict(x_input, verbose=0)
189            print(yhat[0])
190            temp_input.extend(yhat[0].tolist())
191            print(len(temp_input))
192            lst_output.extend(yhat.tolist())
193            i = i + 1
194    res = scaler.inverse_transform(lst_output)
195    # output = res[nDay-1]
196
197    output = res[nDay]
198
199    st.write("*Predicted Price for Date :*", date1, "*is*", np.round(output[0], 2))
200    st.success('The Price is {}'.format(np.round(output[0], 2)))
201
202    # st.write("predicted price : ",output)
203
204    predictions = res[res.size - nDay:res.size]
205    print(predictions.shape)
206    predictions = predictions.ravel()
207    print(type(predictions))
208    print(date_rng)
209    print(predictions)
210    print(date_rng.shape)
211
212
213    @st.cache_data
214    def convert_df(df):
215        return df.to_csv().encode('utf-8')
216
217
218    df = pd.DataFrame(data=date_rng)
219    df['Predictions'] = predictions.tolist()
220    df.columns = ['Date', 'Price']
221    st.write(df)
222    csv = convert_df(df)
223    st.download_button(
224        "Press to Download",
225        csv,
226        "file.csv",
227        "text/csv",
228        key='download-csv'
229    )
230    # visualization
231
232    fig = plt.figure(figsize=(10, 6))
233    xpoints = date_rng
234    ypoints = predictions
235
236    plt.plot(xpoints, ypoints, color='blue', marker='o', linestyle='-', linewidth=2,
237             markersize=5)  # Customize line style and marker
238    plt.xticks(rotation=45, fontsize=10)  # Rotate x-axis labels and adjust fontsize
239    plt.yticks(fontsize=10)  # Adjust fontsize of y-axis labels
240    plt.xlabel('Date', fontsize=12)  # Set x-axis label and adjust fontsize
241    plt.ylabel('Price', fontsize=12)  # Set y-axis label and adjust fontsize
242    plt.title('Cryptocurrency Price Prediction', fontsize=14)  # Set plot title and adjust fontsize
243    plt.grid(True, linestyle='--', alpha=0.5)  # Add grid lines with linestyle and transparency
244    plt.tight_layout()  # Adjust layout to prevent clipping of labels
245
246    # Display the plot in Streamlit
247    st.pyplot(fig)
248