import dotenv import gradio as gr from src.fetch_data import FetchData from src.fetch_forecast import FetchForecast from src.stock_analysis_agent import StockAnalyst from src.technical_analysis import TechnicalAnalysis def initialize_manual(): print(f'Initializing Stock-Analysis Agent') try: stock_analyst = StockAnalyst() message = "Stock-Analysis Agent initialized successfully.\n" except Exception as e: stock_analyst = None message = f"Error initializing Stock-Analysis Agent:\n{e}\n" return message, stock_analyst def find_matching_tickers(agent_instance, ticker): if agent_instance is None: return 'Stock-Analysis Agent is not initialized. Please initialize first.' try: df = agent_instance.tickerfinder.find_best_matching_ticker_or_title(ticker) except Exception as e: print(f'Error finding matching tickers for {ticker}: :\n{e}') df = None return df def ask_stock_agent(agent_instance, ticker): if agent_instance is None: return 'Stock-Analysis Agent is not initialized. Please initialize first.' ticker_exists = agent_instance.tickerfinder.does_ticker_exist(ticker) if ticker_exists: yield "Analysis in progress..." response = agent_instance.get_formatted_stock_summary(ticker) else: response = f""" Ticker symbol {ticker} is not listed by the U.S. Securities and Exchange Commission database, see: https://www.sec.gov/files/company_tickers.json. If you are not sure about the ticker symbol use the Ticker Finder to find the correct ticker. """ yield response def plot_stock(agent_instance, ticker): if agent_instance is None: return 'Stock-Analysis Agent is not initialized. Please initialize first.' ticker_exists = agent_instance.tickerfinder.does_ticker_exist(ticker) if ticker_exists: # fetch the forecasts dotenv.load_dotenv(dotenv.find_dotenv()) df_hist = FetchData(ticker, fetchperiodinweeks=12).run() df_past, df_fcst = FetchForecast(ticker, df_hist).run() # run the technical analysis _, fig = TechnicalAnalysis( ticker=ticker, df_hist=df_hist, df_past=df_past, df_fcst=df_fcst, plot_ta=True, savefig=False, debug=False).run() else: message = f"""Ticker {ticker} does not exist""" fig = TechnicalAnalysis(ticker).get_fetcherror_fig(message) return fig with gr.Blocks() as demo: gr.Markdown("# Stock Analysis Agent") # State to store the agent stock_analyst_state = gr.State() # Auto-initialize init_status = gr.Textbox(label="Init Status", interactive=False, value="Initializing…") # Initialize automatically when the page loads demo.load( fn=initialize_manual, inputs=None, outputs=[init_status, stock_analyst_state] ) # manual-initialize with button # message, stock_analyst = initialize_manual() # is this needed? # init_status = gr.Textbox(label="Initialization Status", interactive=False) # init_button = gr.Button("Initialize") # init_button.click( # fn=initialize_manual, # outputs=[init_status, stock_analyst_state] # Output: status message and the agent # ) print('Agent initialized successfully') # TickerFinder tool ticker_to_find = gr.Textbox(label="Ticker Finder: not sure what's the stock ticker symbol? Enter the company name you want to analyze, and I will try to help.") tf_output = gr.Markdown(label="Match Results") search_button = gr.Button("Search") search_button.click( fn=find_matching_tickers, inputs=[stock_analyst_state, ticker_to_find], outputs=[tf_output], api_name="ticker_finder" ) # Enter stock symbol ticker = gr.Textbox(label="Enter a stock ticker symbol to be analyzed (GOOG, MSFT, etc.)") analyze_button = gr.Button('Analyze Stock') md_output = gr.Markdown(label="Output Box") analyze_button.click( fn=ask_stock_agent, inputs=[stock_analyst_state, ticker], outputs=md_output, api_name="ask_stock_agent") plot_output = gr.Plot(label=ticker, format="png") analyze_button.click( fn=plot_stock, inputs=[stock_analyst_state, ticker], outputs=[plot_output], api_name="plot_stock") if __name__ == "__main__": # local: demo.launch(ssr_mode=False) # public link: # demo.launch(share=True, ssr_mode=False) # local with authentication # demo.launch(auth=("uname", "pwd"), ssr_mode=False)