Update app.py
Browse files1212354567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061077891010810911011111212113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158151617181920212223242526272829303132333415916016136373839404116216316416516616716816917017117217317417517617717817918043181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244454647482452462472482492502512522532545051525325525625725825926026126226326426526626726826927027127227327427527627755565758596061626364656627827928028128228369284import gradio as grimport yfinance as yfimport osimport pandas as pdimport numpy as npfrom tabulate import tabulateimport yfinance as yfimport requestsfrom datetime import datetimeimport gradio as grfrom crewai import Crew, Agent, Task, Processfrom langchain_openai import ChatOpenAIfrom crewai_tools import tool
# API Keys setupdef setup_api_keys(): os.environ['OPENAI_API_KEY'] = "your-openai-api-key" # Replace with actual key os.environ['NEWSAPI_KEY'] = "488e80d0ecb2485ca8f0f824cd9f7360"
# Stock Analysis Tools@tooldef get_basic_stock_info(ticker: str) -> pd.DataFrame: stock = yf.Ticker(ticker) info = stock.info basic_info = pd.DataFrame({ 'Name': [info.get('longName', 'N/A')], 'Sector': [info.get('sector', 'N/A')], 'Industry': [info.get('industry', 'N/A')], 'Market Cap': [info.get('marketCap', 'N/A')], 'Current Price': [info.get('currentPrice', 'N/A')], '52 Week High': [info.get('fiftyTwoWeekHigh', 'N/A')], '52 Week Low': [info.get('fiftyTwoWeekLow', 'N/A')], 'Average Volume': [info.get('averageVolume', 'N/A')] }) return basic_info
@tooldef get_fundamental_analysis(ticker: str, period: str = '1y') -> pd.DataFrame: stock = yf.Ticker(ticker) history = stock.history(period=period) info = stock.info fundamental_analysis = pd.DataFrame({ 'PE Ratio': [info.get('trailingPE', 'N/A')], 'Forward PE': [info.get('forwardPE', 'N/A')], 'PEG Ratio': [info.get('pegRatio', 'N/A')], 'Price to Book': [info.get('priceToBook', 'N/A')], 'Dividend Yield': [info.get('dividendYield', 'N/A')], 'EPS (TTM)': [info.get('trailingEps', 'N/A')], 'Revenue Growth': [info.get('revenueGrowth', 'N/A')], 'Profit Margin': [info.get('profitMargins', 'N/A')], 'Free Cash Flow': [info.get('freeCashflow', 'N/A')], 'Debt to Equity': [info.get('debtToEquity', 'N/A')], 'Return on Equity': [info.get('returnOnEquity', 'N/A')], 'Operating Margin': [info.get('operatingMargins', 'N/A')], 'Quick Ratio': [info.get('quickRatio', 'N/A')], 'Current Ratio': [info.get('currentRatio', 'N/A')], 'Earnings Growth': [info.get('earningsGrowth', 'N/A')], 'Stock Price Avg (Period)': [history['Close'].mean()], 'Stock Price Max (Period)': [history['Close'].max()], 'Stock Price Min (Period)': [history['Close'].min()] }) return fundamental_analysis
def calculate_beta(stock_returns, market_ticker, period): market = yf.Ticker(market_ticker) market_history = market.history(period=period) market_returns = market_history['Close'].pct_change().dropna() aligned_returns = pd.concat([stock_returns, market_returns], axis=1).dropna() covariance = aligned_returns.cov().iloc[0, 1] market_variance = market_returns.var() return covariance / market_variance
def calculate_max_drawdown(prices): peak = prices.cummax() drawdown = (prices - peak) / peak return drawdown.min()
def calculate_sharpe_ratio(returns, risk_free_rate=0.02): excess_returns = returns - risk_free_rate/252 return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
def calculate_sortino_ratio(returns, risk_free_rate=0.02, target_return=0): excess_returns = returns - risk_free_rate/252 downside_returns = excess_returns[excess_returns < target_return] downside_deviation = np.sqrt(np.mean(downside_returns**2)) return np.sqrt(252) * excess_returns.mean() / downside_deviation
@tooldef get_stock_risk_assessment(ticker: str, period: str = "1y") -> pd.DataFrame: stock = yf.Ticker(ticker) history = stock.history(period=period) returns = history['Close'].pct_change().dropna() volatility = returns.std() * np.sqrt(252) beta = calculate_beta(returns, '^GSPC', period) var_95 = np.percentile(returns, 5) max_drawdown = calculate_max_drawdown(history['Close']) risk_assessment = pd.DataFrame({ 'Annualized Volatility': [volatility], 'Beta': [beta], 'Value at Risk (95%)': [var_95], 'Maximum Drawdown': [max_drawdown], 'Sharpe Ratio': [calculate_sharpe_ratio(returns)], 'Sortino Ratio': [calculate_sortino_ratio(returns)] }) return risk_assessment
def analyze_stock(ticker: str) -> str: """Performs comprehensive stock analysis.""" if not ticker: return "Please enter a stock ticker symbol"@tooldef get_technical_analysis(ticker: str, period: str = "1mo") -> pd.DataFrame: stock = yf.Ticker(ticker) history = stock.history(period=period) ticker = ticker.upper().strip() # Calculate indicators history['SMA_50'] = history['Close'].rolling(window=50).mean() history['SMA_200'] = history['Close'].rolling(window=200).mean() history['RSI'] = calculate_rsi(history['Close']) history['MACD'], history['Signal'] = calculate_macd(history['Close']) latest = history.iloc[-1] analysis = pd.DataFrame({ 'Indicator': [ 'Current Price', '50-day SMA', '200-day SMA', 'RSI (14-day)', 'MACD', 'MACD Signal', 'Trend', 'MACD Signal', 'RSI Signal' ], 'Value': [ f'${latest["Close"]:.2f}', f'${latest["SMA_50"]:.2f}', f'${latest["SMA_200"]:.2f}', f'{latest["RSI"]:.2f}', f'{latest["MACD"]:.2f}', f'{latest["Signal"]:.2f}', analyze_trend(latest), analyze_macd(latest), analyze_rsi(latest) ] }) return analysis
@tooldef get_stock_news(query: str, limit: int = 10, api_key: str = "488e80d0ecb2485ca8f0f824cd9f7360") -> pd.DataFrame: base_url = "https://newsapi.org/v2/everything" params = { "q": query, "language": "en", "sortBy": "publishedAt", "pageSize": limit, "apiKey": api_key } try: stock = yf.Ticker(ticker) info = stock.info # Basic Info basic_info = pd.DataFrame([{ 'Company Name': info.get('longName', 'N/A'), 'Sector': info.get('sector', 'N/A'), 'Industry': info.get('industry', 'N/A'), 'Market Cap': f"${info.get('marketCap', 0):,}", 'Current Price': f"${info.get('currentPrice', 0):.2f}", 'Previous Close': f"${info.get('previousClose', 0):.2f}", 'Open': f"${info.get('open', 0):.2f}", '52 Week High': f"${info.get('fiftyTwoWeekHigh', 0):.2f}", '52 Week Low': f"${info.get('fiftyTwoWeekLow', 0):.2f}", 'Volume': f"{info.get('volume', 0):,}", 'PE Ratio': f"{info.get('trailingPE', 0):.2f}", 'EPS': f"${info.get('trailingEps', 0):.2f}", 'Dividend Yield': f"{info.get('dividendYield', 0)*100:.2f}%" if info.get('dividendYield') else 'N/A', 'Beta': f"{info.get('beta', 0):.2f}", }]).T response = requests.get(base_url, params=params) response.raise_for_status() # Get historical data hist = stock.history(period='1mo') price_change = ((hist['Close'][-1] - hist['Close'][0]) / hist['Close'][0]) * 100 analysis = f"""=== {ticker} Stock Analysis === data = response.json() if "articles" not in data or not data["articles"]: return pd.DataFrame({"Error": [f"No news found for query '{query}'."]}) articles = data["articles"] news_data = [] for article in articles: news_entry = { "Title": article.get("title", "N/A"), "Publisher": article.get("source", {}).get("name", "N/A"), "Published": article.get("publishedAt", "N/A"), "Link": article.get("url", "N/A") } news_data.append(news_entry) return pd.DataFrame(news_data) except requests.exceptions.RequestException as e: return pd.DataFrame({"Error": [f"Failed to fetch news: {str(e)}"]})
{tabulate(basic_info, headers=['Value'], tablefmt='grid')}# Initialize Agents and Tasksdef initialize_crew(): llm = ChatOpenAI( model_name="gpt-4o-mini", temperature=0.2, max_tokens=2000, top_p=0.95, frequency_penalty=0.1, presence_penalty=0.1, streaming=False, request_timeout=180 ) stock_researcher = Agent( llm=llm, role="Stock Researcher", goal="Identify and research basic stock information", backstory="Junior stock researcher specializing in gathering basic stock information", tools=[get_basic_stock_info], verbose=True, allow_delegation=False ) financial_analyst = Agent( llm=llm, role="Financial Analyst", goal="Perform detailed stock analysis", backstory="Seasoned financial analyst with expertise in complex financial data", tools=[get_technical_analysis, get_fundamental_analysis, get_stock_risk_assessment], verbose=True, allow_delegation=False ) news_analyst = Agent( llm=llm, role="News Analyst", goal="Analyze stock-related news", backstory="Sharp news analyst specializing in stock market news", tools=[get_stock_news], verbose=True ) report_writer = Agent( llm=llm, role="Financial Report Writer", goal="Create comprehensive stock reports", backstory="Experienced financial writer", tools=[], verbose=True, allow_delegation=False ) return Crew( agents=[stock_researcher, financial_analyst, news_analyst, report_writer], tasks=[ collect_stock_info, perform_analysis, analyze_stock_news, generate_stock_report ], process=Process.sequential, manager_llm=llm )
Performance Metrics:• 30-Day Price Change: {price_change:.2f}%• Average Volume (30 days): {hist['Volume'].mean():,.0f}• Price Volatility (30 days): {hist['Close'].std():.2f}def analyze_stock(query): crew = initialize_crew() default_date = datetime.now().date() result = crew.kickoff(inputs={ "query": query, "default_date": str(default_date), "api_key": "488e80d0ecb2485ca8f0f824cd9f7360" }) return f"### Analysis Report:\n\n{result}"
Business Summary:{info.get('longBusinessSummary', 'No business summary available.')}""" return analysis# Gradio Interfacedef create_interface(): with gr.Blocks() as interface: gr.Markdown("# Advanced Stock Analysis Dashboard") gr.Markdown("Enter your Investment Query:") query_input = gr.TextArea( label="Your Financial ROBO Advisor", value="Analyse ABC stock?", lines=5, ) analyze_button = gr.Button("Analyze") analysis_output = gr.Markdown() def on_analyze(query): return analyze_stock(query) analyze_button.click(on_analyze, inputs=[query_input], outputs=[analysis_output]) gr.Markdown("---") gr.Markdown("Made by Manoj") except Exception as e: return f"Error analyzing {ticker}: {str(e)}\nPlease ensure you entered a valid ticker symbol."
# Create Gradio interfaceiface = gr.Interface( fn=analyze_stock, inputs=gr.Textbox(label="Enter Stock Ticker Symbol (e.g., AAPL, MSFT)"), outputs=gr.Textbox(label="Analysis Results", lines=20), title="Comprehensive Stock Analysis Tool", description="Enter a stock ticker symbol to get detailed analysis.", examples=[["AAPL"], ["MSFT"], ["GOOGL"]]) return interface
# Main executionif __name__ == "__main__": setup_api_keys() interface = create_interface() iface.launch() interface.launch()app.py+271-56