Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import yfinance as yf
|
5 |
+
import talib
|
6 |
+
import requests
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import logging
|
9 |
+
from tensorflow.keras.models import Sequential
|
10 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
11 |
+
from stable_baselines3 import PPO, DQN
|
12 |
+
from gym import Env, spaces
|
13 |
+
from selenium import webdriver
|
14 |
+
from selenium.webdriver.chrome.service import Service
|
15 |
+
from selenium.webdriver.chrome.options import Options
|
16 |
+
from selenium.webdriver.common.by import By
|
17 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
18 |
+
from selenium.webdriver.support import expected_conditions as EC
|
19 |
+
from bs4 import BeautifulSoup
|
20 |
+
import time
|
21 |
+
from webdriver_manager.chrome import ChromeDriverManager
|
22 |
+
import threading
|
23 |
+
import smtplib
|
24 |
+
from email.mime.text import MIMEText
|
25 |
+
from email.mime.multipart import MIMEMultipart
|
26 |
+
|
27 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
28 |
+
|
29 |
+
# Free API Alternative to Alpaca (Yahoo Finance)
|
30 |
+
BASE_URL = "https://query1.finance.yahoo.com/v8/finance/chart/"
|
31 |
+
|
32 |
+
def fetch_live_price(symbol):
|
33 |
+
try:
|
34 |
+
stock = yf.Ticker(symbol)
|
35 |
+
return stock.history(period="1d")["Close"].iloc[-1]
|
36 |
+
except Exception as e:
|
37 |
+
logging.error(f"Error fetching live price: {e}")
|
38 |
+
return None
|
39 |
+
|
40 |
+
# Optimized Web Scraping with Selenium Waits
|
41 |
+
def scrape_groww(symbol):
|
42 |
+
options = Options()
|
43 |
+
options.add_argument("--headless")
|
44 |
+
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
|
45 |
+
url = f"https://groww.in/stocks/{symbol.lower()}"
|
46 |
+
driver.get(url)
|
47 |
+
|
48 |
+
try:
|
49 |
+
price_element = WebDriverWait(driver, 10).until(
|
50 |
+
EC.presence_of_element_located((By.CLASS_NAME, "stock-price"))
|
51 |
+
)
|
52 |
+
price = float(price_element.text.replace(',', ''))
|
53 |
+
except Exception:
|
54 |
+
price = None
|
55 |
+
|
56 |
+
driver.quit()
|
57 |
+
return price
|
58 |
+
|
59 |
+
# Fetch Data with Additional Indicators
|
60 |
+
def fetch_data(symbol, interval='1m', period='5d'):
|
61 |
+
df = yf.download(symbol, interval=interval, period=period)
|
62 |
+
df['SMA_10'] = talib.SMA(df['Close'], timeperiod=10)
|
63 |
+
df['RSI'] = talib.RSI(df['Close'], timeperiod=14)
|
64 |
+
df['MACD'], df['MACD_signal'], _ = talib.MACD(df['Close'])
|
65 |
+
return df
|
66 |
+
|
67 |
+
# Improved LSTM Model
|
68 |
+
def train_lstm_model(data):
|
69 |
+
X, y = np.array([[data[i-10:i].values] for i in range(10, len(data))]), data['Close'][10:].values
|
70 |
+
model = Sequential([
|
71 |
+
LSTM(100, return_sequences=True, input_shape=(10, 1)),
|
72 |
+
Dropout(0.2),
|
73 |
+
LSTM(100),
|
74 |
+
Dense(50, activation='relu'),
|
75 |
+
Dense(1)
|
76 |
+
])
|
77 |
+
model.compile(optimizer='adam', loss='mse')
|
78 |
+
model.fit(X, y, epochs=20, batch_size=32)
|
79 |
+
return model
|
80 |
+
|
81 |
+
# Advanced RL-Based Trading Agent
|
82 |
+
class TradingEnv(Env):
|
83 |
+
def __init__(self):
|
84 |
+
self.action_space = spaces.Discrete(3)
|
85 |
+
self.observation_space = spaces.Box(low=0, high=1, shape=(10,), dtype=np.float32)
|
86 |
+
self.current_step = 0
|
87 |
+
self.balance = 10000
|
88 |
+
self.position = 0
|
89 |
+
self.history = []
|
90 |
+
|
91 |
+
def step(self, action):
|
92 |
+
reward = 0
|
93 |
+
done = False
|
94 |
+
if action == 0: # Buy
|
95 |
+
self.position += 1
|
96 |
+
reward -= 0.5 # Reduced penalty for transaction cost
|
97 |
+
elif action == 1: # Sell
|
98 |
+
if self.position > 0:
|
99 |
+
self.position -= 1
|
100 |
+
reward += 10 # Higher profit realization
|
101 |
+
elif action == 2: # Hold
|
102 |
+
reward += 0.2 # Slightly increased hold reward
|
103 |
+
self.current_step += 1
|
104 |
+
self.history.append((self.current_step, self.balance, self.position))
|
105 |
+
if self.current_step >= 200:
|
106 |
+
done = True
|
107 |
+
return np.random.random(10), reward, done, {}
|
108 |
+
|
109 |
+
env = TradingEnv()
|
110 |
+
model = PPO("MlpPolicy", env, verbose=1)
|
111 |
+
model.learn(total_timesteps=500000)
|
112 |
+
|
113 |
+
# Place Trade using Free API
|
114 |
+
def place_trade(symbol, action):
|
115 |
+
return {"status": "success", "symbol": symbol, "action": action}
|
116 |
+
|
117 |
+
# Email Alert System
|
118 |
+
def send_email_alert(subject, body):
|
119 |
+
sender_email = "[email protected]"
|
120 |
+
receiver_email = "[email protected]"
|
121 |
+
password = "your_password"
|
122 |
+
|
123 |
+
msg = MIMEMultipart()
|
124 |
+
msg['From'] = sender_email
|
125 |
+
msg['To'] = receiver_email
|
126 |
+
msg['Subject'] = subject
|
127 |
+
msg.attach(MIMEText(body, 'plain'))
|
128 |
+
|
129 |
+
with smtplib.SMTP('smtp.gmail.com', 587) as server:
|
130 |
+
server.starttls()
|
131 |
+
server.login(sender_email, password)
|
132 |
+
server.sendmail(sender_email, receiver_email, msg.as_string())
|
133 |
+
|
134 |
+
# Automated Trading and Alert System
|
135 |
+
def monitor_price(symbol, threshold):
|
136 |
+
while True:
|
137 |
+
price = fetch_live_price(symbol)
|
138 |
+
if price and price >= threshold:
|
139 |
+
send_email_alert("Stock Price Alert", f"{symbol} has reached {price}!")
|
140 |
+
place_trade(symbol, "sell")
|
141 |
+
break
|
142 |
+
time.sleep(60)
|
143 |
+
|
144 |
+
# Gradio UI
|
145 |
+
def stock_dashboard(symbol, threshold_price):
|
146 |
+
data = fetch_data(symbol)
|
147 |
+
fig, ax = plt.subplots()
|
148 |
+
ax.plot(data.index, data['Close'], label='Close Price')
|
149 |
+
ax.plot(data.index, data['SMA_10'], label='SMA 10', linestyle='dashed')
|
150 |
+
ax.legend()
|
151 |
+
|
152 |
+
live_price = fetch_live_price(symbol)
|
153 |
+
action = np.random.choice(["buy", "sell", "hold"])
|
154 |
+
place_trade(symbol, action)
|
155 |
+
|
156 |
+
return fig, f"Live Price: {live_price}", f"Trade Executed: {action}"
|
157 |
+
|
158 |
+
demo = gr.Interface(
|
159 |
+
fn=stock_dashboard,
|
160 |
+
inputs=["text", "number"],
|
161 |
+
outputs=["plot", "text", "text"],
|
162 |
+
title="AI-Powered Intraday Trading Agent",
|
163 |
+
description="Enter a stock symbol and set a price threshold to start trading."
|
164 |
+
)
|
165 |
+
|
166 |
+
demo.launch()
|