import os import pandas as pd import gradio as gr from langchain_community.vectorstores import FAISS from langchain_core.prompts import PromptTemplate from langchain_core.documents import Document from langchain.chains import RetrievalQA from langchain_openai import ChatOpenAI from langchain_huggingface import HuggingFaceEmbeddings # ------------------ SET API KEY ------------------ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") if not OPENAI_API_KEY: raise ValueError("❌ OPENAI_API_KEY not found. Please set it in Hugging Face Secrets.") # ------------------ CONFIG ------------------ csv_path = "./artifacts/1_gnn_forecast_confidence_final.csv" embedding_model_name = "BAAI/bge-small-en-v1.5" openai_model_name = "gpt-4" index_dir = "faiss_csv_index" # ------------------ STEP 1: Load Forecast CSV ------------------ try: df = pd.read_csv(csv_path) print("✅ Forecast data loaded") except Exception as e: raise FileNotFoundError(f"❌ Failed to load forecast CSV: {e}") tickers = sorted(df['Ticker'].unique()) # ------------------ STEP 2: Prepare Documents for RAG ------------------ documents = [ Document(page_content="; ".join([f"{col}: {val}" for col, val in row.items()]), metadata={"row": i}) for i, row in df.iterrows() ] # ------------------ STEP 3: Create FAISS Index ------------------ embedding_model = HuggingFaceEmbeddings(model_name=embedding_model_name) doc_texts = [doc.page_content for doc in documents] vector_index = FAISS.from_texts(doc_texts, embedding_model) vector_index.save_local(index_dir) # ------------------ STEP 4: Define Prompt for RAG ------------------ custom_prompt = PromptTemplate( input_variables=["context", "question"], template=""" You are a helpful assistant analyzing stock forecast confidence data. Context: {context} Question: {question} Answer:""" ) # ------------------ STEP 5: Load OpenAI GPT-4 Model ------------------ llm = ChatOpenAI(model_name=openai_model_name, temperature=0, openai_api_key=OPENAI_API_KEY) # ------------------ STEP 6: Setup RAG Chain ------------------ qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=vector_index.as_retriever(), chain_type="stuff", chain_type_kwargs={"prompt": custom_prompt} ) # ------------------ Forecast Viewer Logic ------------------ def get_forecast(ticker): filtered = df[df['Ticker'] == ticker] output = {} confidences = {} for horizon in [30, 180, 365]: row = filtered[filtered['Forecast_Horizon_Days'] == horizon] if not row.empty: price = row.iloc[0]['Predicted_Close_Price'] confidence = row.iloc[0]['Confidence_%'] output[horizon] = f"Price: {price:.2f}" confidences[horizon] = confidence else: output[horizon] = "No data available" confidences[horizon] = 0 return output[30], confidences[30], output[180], confidences[180], output[365], confidences[365] def get_related_stocks(ticker): filtered = df[df['Ticker'] == ticker] if not filtered.empty: return filtered.iloc[0]['Suggested_Related_Stocks'] else: return "No related stocks found." # ------------------ RAG Logic ------------------ def answer_question(query): try: result = qa_chain.invoke({"query": query}) return result["result"].replace("\\n", "\n") except Exception as e: return f"Error: {str(e)}" # ------------------ Gradio UI ------------------ with gr.Blocks(css=""" .column { display: flex; flex-direction: column; align-items: center; background-color: #f9f9f9; padding: 1em; margin: 0.5em; border-radius: 10px; } #forecast30 {background-color: #ffcccc} #forecast180 {background-color: #ccffcc} #forecast365 {background-color: #ccccff} .slider-vertical input[type=range] { writing-mode: bt-lr; -webkit-appearance: slider-vertical; width: 8px; height: 200px; } .slider-vertical .wrap { height: 200px; width: 50px; } """) as demo: with gr.Tab("📈 Forecast Viewer"): gr.Markdown("## 📈 Stock Forecast Viewer") ticker_dropdown = gr.Dropdown(label="Select Ticker", choices=tickers) with gr.Row(): with gr.Column(elem_classes="column"): forecast_30 = gr.Textbox(label="30 Days Forecast", elem_id="forecast30") confidence_30 = gr.Slider(label="30 Days Confidence", minimum=0, maximum=100, elem_classes="slider-vertical") with gr.Column(elem_classes="column"): forecast_180 = gr.Textbox(label="180 Days Forecast", elem_id="forecast180") confidence_180 = gr.Slider(label="180 Days Confidence", minimum=0, maximum=100, elem_classes="slider-vertical") with gr.Column(elem_classes="column"): forecast_365 = gr.Textbox(label="365 Days Forecast", elem_id="forecast365") confidence_365 = gr.Slider(label="365 Days Confidence", minimum=0, maximum=100, elem_classes="slider-vertical") related_button = gr.Button("Show Related Stocks") related_output = gr.Textbox(label="Suggested Related Stocks") ticker_dropdown.change( get_forecast, inputs=[ticker_dropdown], outputs=[forecast_30, confidence_30, forecast_180, confidence_180, forecast_365, confidence_365] ) related_button.click( get_related_stocks, inputs=[ticker_dropdown], outputs=[related_output] ) with gr.Tab("💬 Ask Anything (RAG Search)"): gr.Markdown("## 💬 Ask Stock Forecast Questions (powered by RAG and GPT-4)") query_input = gr.Textbox(placeholder="Ask a question about stock predictions...") query_button = gr.Button("Get Answer") query_output = gr.Textbox(label="Answer") query_button.click( answer_question, inputs=[query_input], outputs=[query_output] ) # ------------------ Launch ------------------ demo.launch()