Surya152002 commited on
Commit
07e7203
·
1 Parent(s): 5769387

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from statsmodels.tsa.arima.model import ARIMA
5
+ from sklearn.preprocessing import StandardScaler
6
+ import streamlit as st
7
+ import pickle
8
+ import numpy as np
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ from sklearn.metrics.pairwise import cosine_similarity
11
+ import nltk
12
+ from nltk.corpus import stopwords
13
+ from nltk.tokenize import word_tokenize
14
+ import os # Added for file path handling
15
+ import openai
16
+
17
+
18
+ openai.api_key = "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"
19
+
20
+ # Download the necessary NLTK datasets
21
+ nltk.download('punkt')
22
+ nltk.download('stopwords')
23
+
24
+ # Function to preprocess data
25
+ def preprocess_data(df):
26
+ # Handle missing values by forward filling
27
+ df = df.fillna(method='ffill')
28
+
29
+ # Optionally, handle any remaining missing values by backward filling
30
+ df = df.fillna(method='bfill')
31
+
32
+ # Optionally, standardize (scale) the data to have zero mean and unit variance
33
+ scaler = StandardScaler()
34
+ df[df.columns] = scaler.fit_transform(df[df.columns])
35
+
36
+ return df
37
+
38
+ def trading_advice(actual, prediction):
39
+ """
40
+ Provide trading advice based on prediction and actual prices.
41
+ """
42
+ if prediction > actual:
43
+ return "Based on the predictions, you might consider buying."
44
+ elif prediction < actual:
45
+ return "Based on the predictions, you might consider selling."
46
+ else:
47
+ return "The price seems stable. You might consider holding."
48
+
49
+ def chatbot_response(user_input, predefined_responses):
50
+ # Tokenize and vectorize user input and predefined responses
51
+ vectorizer = TfidfVectorizer(tokenizer=lambda text: nltk.word_tokenize(text, language='english'),
52
+ stop_words=stopwords.words('english'))
53
+ vectors = vectorizer.fit_transform([user_input] + predefined_responses)
54
+
55
+ # Calculate cosine similarities
56
+ cosine_matrix = cosine_similarity(vectors)
57
+
58
+ # Find the most similar predefined response to the user's input
59
+ response_idx = np.argmax(cosine_matrix[0][1:])
60
+
61
+ return predefined_responses[response_idx]
62
+
63
+ def get_gpt3_response(user_input):
64
+ prompt = f"Answer questions related to cryptocurrency.\n\nUser: {user_input}\nBot:"
65
+ response = openai.Completion.create(
66
+ engine="text-davinci-002",
67
+ prompt=prompt,
68
+ max_tokens=50 # You can adjust this based on response length
69
+ )
70
+ return response.choices[0].text
71
+
72
+
73
+ # Streamlit app
74
+ def main():
75
+ st.title("Cryptocurrency Price Prediction and Trading Bot")
76
+
77
+ # Specify the path to the CSV file
78
+ csv_path = '/content/crypto_dataset (9).csv' # Update with your specific file path
79
+
80
+ # Check if the CSV file exists at the specified path
81
+ if not os.path.exists(csv_path):
82
+ st.error("The specified CSV file does not exist. Please provide a valid file path.")
83
+ return
84
+
85
+ # Read and preprocess the input data
86
+ input_data = pd.read_csv(csv_path, parse_dates=['Timestamp'], index_col='Timestamp')
87
+ input_data = preprocess_data(input_data)
88
+
89
+ # List of coins
90
+ coins = ['BTC-USD Close', 'ETH-USD Close', 'LTC-USD Close']
91
+
92
+ # Get user's choice of cryptocurrency
93
+ coin_choice = st.selectbox("Select a cryptocurrency", coins)
94
+
95
+ # Train ARIMA model if needed
96
+ if coin_choice == "BTC-USD Close":
97
+ coin_model_path = 'btc-usd_close_model.pkl' # Update with your desired model path
98
+ coin_column = 'BTC-USD Close'
99
+ elif coin_choice == "ETH-USD Close":
100
+ coin_model_path = 'eth-usd_close_model.pkl' # Update with your desired model path
101
+ coin_column = 'ETH-USD Close'
102
+ else:
103
+ coin_model_path = 'ltc-usd_close_model.pkl' # Update with your desired model path
104
+ coin_column = 'LTC-USD Close'
105
+
106
+ # Check if the model exists, if not, train it
107
+ if not os.path.exists(coin_model_path):
108
+ # Split the data into training and testing sets
109
+ train_size = int(len(input_data) * 0.8)
110
+ train, test = input_data[:train_size], input_data[train_size:]
111
+
112
+ # Build and train the ARIMA model
113
+ model = ARIMA(train[coin_column], order=(5, 1, 0)) # Example order, you can tune this
114
+ model_fit = model.fit()
115
+
116
+ # Save the trained model using pickle
117
+ with open(coin_model_path, 'wb') as model_file:
118
+ pickle.dump(model_fit, model_file)
119
+
120
+ # Load the model using pickle
121
+ with open(coin_model_path, 'rb') as model_file:
122
+ model_fit = pickle.load(model_file)
123
+
124
+ # Make predictions
125
+ predictions = model_fit.forecast(steps=len(input_data))
126
+
127
+ # Display predictions
128
+ st.header("Price Predictions")
129
+ st.write(predictions)
130
+
131
+ # Visualize results
132
+ st.header("Price Prediction Chart")
133
+ fig, ax = plt.subplots(figsize=(10, 6))
134
+ ax.plot(input_data.index, input_data[coin_column], label='Actual')
135
+ ax.plot(input_data.index, predictions, label='Predicted', linestyle='--')
136
+ ax.set_title(f'{coin_choice} Price Prediction')
137
+ ax.legend()
138
+ st.pyplot(fig)
139
+
140
+ # Chatbot live interaction
141
+
142
+ st.header("Chat with Trading Bot")
143
+
144
+ user_message = st.text_input("You: ")
145
+ predefined_responses = [
146
+ "The predicted price for the next period is {}.".format(predictions.iloc[-1]),
147
+ trading_advice(input_data[coin_column].iloc[-1], predictions.iloc[-1]),
148
+ "I am here to help with your cryptocurrency trading decisions.",
149
+ "Can you specify your query?"
150
+ ]
151
+
152
+ if user_message:
153
+ if "predict" in user_message.lower() or "forecast" in user_message.lower():
154
+ bot_reply = trading_advice(input_data[coin_column].iloc[-1], predictions.iloc[-1])
155
+ else:
156
+ bot_reply = get_gpt3_response(user_message)
157
+ st.write(f"Bot: {bot_reply}")
158
+
159
+ if __name__ == "__main__":
160
+ main()
161
+