RizwanSajad commited on
Commit
663d47c
·
verified ·
1 Parent(s): 1eb156e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -64
app.py CHANGED
@@ -1,80 +1,67 @@
1
  # app.py
2
  import gradio as gr
 
3
  import pandas as pd
4
- import numpy as np
5
  import yfinance as yf
6
- from ta import add_all_ta_features
7
- from ta.utils import dropna
8
- from transformers import pipeline, AutoModelForQuestionAnswering, AutoTokenizer
9
- from sentence_transformers import SentenceTransformer
10
- import faiss
11
 
12
- # Load the dataset from Google Drive
13
- def load_data():
14
- url = "https://drive.google.com/uc?export=download&id=1N1bCVRSacs7_nENJzleqqNRHA22-H9B5"
15
- df = pd.read_csv(url)
16
- return df
17
 
18
- # Preprocess the data
19
- def preprocess_data(df):
20
- df = dropna(df)
21
- df = add_all_ta_features(df, open="Open", high="High", low="Low", close="Close", volume="Volume", fillna=True)
22
- return df
23
-
24
- # Train the FAISS index for RAG
25
- def train_faiss_index(df):
26
- model = SentenceTransformer('all-MiniLM-L6-v2')
27
- embeddings = model.encode(df['Close'].astype(str).tolist())
28
- dimension = embeddings.shape[1]
29
- index = faiss.IndexFlatL2(dimension)
30
- index.add(embeddings)
31
- return index, model
32
-
33
- # Load the QA model
34
- def load_qa_model():
35
- model_name = "deepset/roberta-base-squad2"
36
- model = AutoModelForQuestionAnswering.from_pretrained(model_name)
37
- tokenizer = AutoTokenizer.from_pretrained(model_name)
38
- qa_pipeline = pipeline("question-answering", model=model, tokenizer=tokenizer)
39
- return qa_pipeline
40
-
41
- # Get technical analysis
42
- def get_technical_analysis(df):
43
- analysis = {
44
- "SMA_50": df['Close'].rolling(window=50).mean().iloc[-1],
45
- "SMA_200": df['Close'].rolling(window=200).mean().iloc[-1],
46
- "RSI": df['momentum_rsi'].iloc[-1],
47
- "MACD": df['trend_macd_diff'].iloc[-1], # Updated for `ta` library
48
- }
49
- return analysis
50
-
51
- # RAG-based QA function
52
- def rag_qa(question, df, index, model, qa_pipeline):
53
- query_embedding = model.encode([question])
54
- distances, indices = index.search(query_embedding, k=1)
55
- context = df.iloc[indices[0][0]]['Close']
56
- result = qa_pipeline(question=question, context=str(context))
57
- return result['answer']
58
 
59
- # Gradio Interface
60
- def trading_analysis_app(question):
61
- df = load_data()
62
- df = preprocess_data(df)
63
- index, model = train_faiss_index(df)
64
- qa_pipeline = load_qa_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- analysis = get_technical_analysis(df)
67
- answer = rag_qa(question, df, index, model, qa_pipeline)
68
 
69
- return f"Technical Analysis: {analysis}\n\nAnswer: {answer}"
70
 
71
- # Gradio Interface
72
  iface = gr.Interface(
73
- fn=trading_analysis_app,
74
  inputs="text",
75
  outputs="text",
76
- title="RAG-based Trading Analysis",
77
- description="Enter your question about ICICIBANK's stock to get technical analysis and answers."
 
 
 
 
 
78
  )
79
 
 
80
  iface.launch()
 
1
  # app.py
2
  import gradio as gr
3
+ import torch
4
  import pandas as pd
5
+ from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
6
  import yfinance as yf
 
 
 
 
 
7
 
8
+ # Load the fine-tuned RAG model and tokenizer
9
+ tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-base")
10
+ retriever = RagRetriever.from_pretrained("facebook/rag-sequence-base", index_name="custom")
11
+ model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-base", retriever=retriever)
 
12
 
13
+ # Function to fetch and preprocess ICICI Bank data
14
+ def fetch_and_preprocess_data():
15
+ # Fetch ICICI Bank data using yfinance
16
+ ticker = "ICICIBANK.NS"
17
+ data = yf.download(ticker, start="2020-01-01", end="2023-01-01")
18
+
19
+ # Calculate technical indicators
20
+ data['MA_50'] = data['Close'].rolling(window=50).mean()
21
+ data['MA_200'] = data['Close'].rolling(window=200).mean()
22
+
23
+ return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Function to analyze trading data using the RAG model
26
+ def analyze_trading_data(question):
27
+ # Fetch and preprocess data
28
+ data = fetch_and_preprocess_data()
29
+
30
+ # Prepare context for the RAG model
31
+ context = (
32
+ f"ICICI Bank stock data:\n"
33
+ f"Latest Close Price: {data['Close'].iloc[-1]:.2f}\n"
34
+ f"50-Day Moving Average: {data['MA_50'].iloc[-1]:.2f}\n"
35
+ f"200-Day Moving Average: {data['MA_200'].iloc[-1]:.2f}\n"
36
+ )
37
+
38
+ # Combine question and context
39
+ input_text = f"Question: {question}\nContext: {context}"
40
+
41
+ # Tokenize the input
42
+ inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True)
43
+
44
+ # Generate the answer using the RAG model
45
+ outputs = model.generate(inputs['input_ids'])
46
 
47
+ # Decode the output to get the answer
48
+ answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
49
 
50
+ return answer
51
 
52
+ # Gradio interface
53
  iface = gr.Interface(
54
+ fn=analyze_trading_data,
55
  inputs="text",
56
  outputs="text",
57
+ title="ICICI Bank Trading Analysis",
58
+ description="Ask any question about ICICI Bank's trading data and get a detailed analysis.",
59
+ examples=[
60
+ "What is the current trend of ICICI Bank stock?",
61
+ "Is the 50-day moving average above the 200-day moving average?",
62
+ "What is the latest closing price of ICICI Bank?"
63
+ ]
64
  )
65
 
66
+ # Launch the app
67
  iface.launch()