MacDash commited on
Commit
adc52c1
·
verified ·
1 Parent(s): 4dacf90

Update App.py

Browse files
Files changed (1) hide show
  1. App.py +50 -96
App.py CHANGED
@@ -1,97 +1,51 @@
1
- import requests
2
- import pandas as pd
3
- import numpy as np
4
- from sklearn.ensemble import RandomForestClassifier
5
- from textblob import TextBlob
6
- import tweepy
7
- import time
8
-
9
- class ExplosiveGrowthBot:
10
- def __init__(self):
11
- self.api_key = "YOUR_BINANCE_API_KEY"
12
- self.base_url = "https://api.binance.com"
13
- self.model = RandomForestClassifier()
14
- self.data = pd.DataFrame()
15
- self.twitter_api = self.setup_twitter_api()
16
-
17
- def setup_twitter_api(self):
18
- """Set up Twitter API for sentiment analysis."""
19
- consumer_key = "YOUR_TWITTER_CONSUMER_KEY"
20
- consumer_secret = "YOUR_TWITTER_CONSUMER_SECRET"
21
- access_token = "YOUR_TWITTER_ACCESS_TOKEN"
22
- access_token_secret = "YOUR_TWITTER_ACCESS_SECRET"
23
-
24
- auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
25
- auth.set_access_token(access_token, access_token_secret)
26
- return tweepy.API(auth)
27
-
28
- def fetch_market_data(self, symbol="BTCUSDT", interval="1h", limit=100):
29
- """Fetch historical market data from Binance."""
30
- url = f"{self.base_url}/api/v3/klines"
31
- params = {"symbol": symbol, "interval": interval, "limit": limit}
32
- response = requests.get(url, params=params)
33
- if response.status_code == 200:
34
- data = response.json()
35
- df = pd.DataFrame(data, columns=["timestamp", "open", "high", "low", "close", "volume", "_", "_", "_", "_", "_"])
36
- df["close"] = df["close"].astype(float)
37
- df["volume"] = df["volume"].astype(float)
38
- return df
39
  else:
40
- print("Error fetching market data:", response.text)
41
- return None
42
-
43
- def analyze_sentiment(self, keyword):
44
- """Analyze sentiment from Twitter."""
45
- tweets = self.twitter_api.search_tweets(q=keyword, count=100, lang="en")
46
- sentiments = []
47
- for tweet in tweets:
48
- analysis = TextBlob(tweet.text)
49
- sentiments.append(analysis.sentiment.polarity)
50
- return np.mean(sentiments)
51
-
52
- def train_model(self, df):
53
- """Train the AI model to predict explosive growth."""
54
- df["target"] = (df["close"].pct_change() > 0.05).astype(int) # Label: 1 if price increased by >5%
55
- features = df[["close", "volume"]].dropna()
56
- target = df["target"].dropna()
57
- self.model.fit(features[:-1], target)
58
-
59
- def predict_growth(self, latest_data):
60
- """Predict whether the asset will experience explosive growth."""
61
- prediction = self.model.predict([latest_data])
62
- return prediction[0]
63
-
64
- def execute_trade(self, symbol, action):
65
- """Simulate trade execution."""
66
- print(f"Executing {action} trade for {symbol}...")
67
-
68
- def run(self):
69
- """Main loop for the bot."""
70
- symbols_to_watch = ["BTCUSDT", "ETHUSDT", "DOGEUSDT"]
71
-
72
- while True:
73
- for symbol in symbols_to_watch:
74
- # Fetch market data
75
- df = self.fetch_market_data(symbol=symbol)
76
- if df is not None:
77
- # Analyze sentiment
78
- sentiment_score = self.analyze_sentiment(symbol.replace("USDT", ""))
79
- print(f"Sentiment score for {symbol}: {sentiment_score}")
80
-
81
- # Train model and make predictions
82
- self.train_model(df)
83
- latest_data = df.iloc[-1][["close", "volume"]].values
84
- prediction = self.predict_growth(latest_data)
85
-
86
- # Decision-making based on prediction and sentiment
87
- if prediction == 1 and sentiment_score > 0.5: # Strong buy signal
88
- self.execute_trade(symbol, "BUY")
89
- elif prediction == 0 and sentiment_score < -0.5: # Strong sell signal
90
- self.execute_trade(symbol, "SELL")
91
-
92
- time.sleep(300) # Wait 5 minutes before checking again
93
-
94
- if __name__ == "__main__":
95
- bot = ExplosiveGrowthBot()
96
- bot.run()
97
-
 
1
+ import gradio as gr
2
+ from src.data_fetcher import fetch_crypto_data, fetch_stock_data, fetch_sentiment_data
3
+ from src.model import train_model, predict_growth
4
+ from src.visualizer import plot_price_trends, plot_sentiment_trends
5
+
6
+ def analyze_asset(asset_type, symbol):
7
+ """
8
+ Analyze a stock or cryptocurrency symbol.
9
+ Fetches market data, performs sentiment analysis,
10
+ trains AI model, and provides predictions with visualizations.
11
+ """
12
+ try:
13
+ if asset_type == "Crypto":
14
+ market_data = fetch_crypto_data(symbol)
15
+ elif asset_type == "Stock":
16
+ market_data = fetch_stock_data(symbol)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  else:
18
+ return "Invalid asset type."
19
+
20
+ sentiment_score = fetch_sentiment_data(symbol)
21
+ train_model(market_data)
22
+ latest_data = market_data.iloc[-1][["close", "volume"]].values.tolist()
23
+ prediction = predict_growth(latest_data)
24
+
25
+ price_plot = plot_price_trends(market_data)
26
+ sentiment_plot = plot_sentiment_trends(symbol)
27
+
28
+ action = "BUY" if prediction == 1 else "SELL"
29
+ result = {
30
+ "Symbol": symbol,
31
+ "Sentiment Score": f"{sentiment_score:.2f}",
32
+ "Prediction": action,
33
+ "Visualizations": [price_plot, sentiment_plot],
34
+ }
35
+ return result
36
+
37
+ except Exception as e:
38
+ return {"Error": str(e)}
39
+
40
+ # Gradio Interface
41
+ asset_type_input = gr.Radio(["Crypto", "Stock"], label="Asset Type")
42
+ symbol_input = gr.Textbox(label="Enter Symbol (e.g., BTCUSDT or AAPL)")
43
+ output_result = gr.JSON(label="Analysis Results")
44
+
45
+ gr.Interface(
46
+ fn=analyze_asset,
47
+ inputs=[asset_type_input, symbol_input],
48
+ outputs=output_result,
49
+ title="Explosive Growth Bot",
50
+ description="Predicts explosive growth in stocks and cryptocurrencies using AI.",
51
+ ).launch()