Surya152002 commited on
Commit
cf00082
·
1 Parent(s): d85ee4a

Create app.py

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