rupt123's picture
Update app.py
89102cf verified
Raw History Blame Contribute Delete
24.5 kB
import os
import openai
import numpy as np
import pandas as pd
import gradio as gr
from getpass import getpass
#from google.colab import userdata
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
from langchain_openai import ChatOpenAI
from transformers import pipeline
import yfinance as yf
from datetime import datetime
#import streamlit as stp
#from langchain_groq import ChatGroq
import streamlit as stp
from crewai import Crew, Agent, Task, Process
from crewai import Crew, Agent, Task, Process
#from langchain_groq import ChatGroq # This might also need to be installed using pip
try:
from crewai_tools import Tool
except ImportError:
pass
from datetime import datetime
# Get current date/time
current_time = datetime.now()
#print(current_time)
#Read OPEN AI Key from user Data
#from google.colab import userdata
#api_key = os.getenv("OPENAI_API_KEY")
#os.environ['OPENAI_API_KEY'] = api_key
#openai.api_key = os.getenv('OPENAI_API_KEY')
#from google.colab import userdata
#api_key = os.get('NEWSAPI_KEY')
#os.environ['NEWSAPI_KEY'] = api_key
#openai.api_key = os.getenv('NEWSAPI_KEY')
openai_api_key = os.environ.get('OPENAI_API_KEY')
newsapi_key = os.environ.get('NEWSAPI_KEY')
# Step 1: Define the Alpha Vantage Tool
#class AlphaVantageTool:
#def __init__(self, api_key):
#self.api_key = api_key
#self.base_url = "https://www.alphavantage.co/query"
# Initialize the tool with your API key
#api_key = "YS8AMMVFZXSLK6HF" # Replace with your actual API key
#alpha_tool = AlphaVantageTool(api_key)
from crewai_tools import tool
@tool
def get_basic_info(ticker: str) -> pd.DataFrame:
"""Retrieves basic information about the funds/stocks.
For more information, you can perform technical analysis, assess fund/stock risk or perform fundamental analysis.
Params:
- ticker: The stock/fund ticker symbol.
"""
stock = yf.Ticker(ticker)
info = stock.info
basic_info = pd.DataFrame({
#Stocks
'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')],
#Mutual Funds
'Name': [info.get('longName', 'N/A')],
'Short Name': [info.get('shortName', 'N/A')],
'Ticker': [info.get('symbol', 'N/A')],
'Category': [info.get('category', 'N/A')],
'Fund Family': [info.get('fundFamily', 'N/A')],
'Name of the investment category': [info.get('categoryName', 'N/A')],
'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
@tool
def get_fundamental_analysis(ticker: str, period: str = '1y') -> pd.DataFrame:
"""
Performs fundamental analysis on a given fund/stock for a specific period.
Params:
- ticker: The fund/stock ticker symbol.
- period: The period to consider for historical data (default is 1 year) (available time-periods: ["1y", "2y", "5y", "10y", "ytd", "max"]).
Returns:
- DataFrame with fundamental metrics.
"""
stock = yf.Ticker(ticker)
# Fetch historical data for the given period
history = stock.history(period=period)
# Fetch latest available financial info
info = stock.info
fundamental_analysis = pd.DataFrame({
#Stocks
'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()],
#Mutual Funds
'Total Assets': [info.get('totalAssets', 'N/A')],
'Expense Ratio': [info.get('expenseRatio', 'N/A')],
'Beta 3Y': [info.get('beta3Year', 'N/A')],
'Rating': [info.get('morningStarRiskRating', 'N/A')],
'Overall Rating': [info.get('morningStarOverallRating', 'N/A')],
'Yield': [info.get('yield', 'N/A')],
'3 Year return': [info.get('threeYearReturn', 'N/A')],
'5 Year return': [info.get('fiveYearReturn', 'N/A')],
'10 Year return': [info.get('tenYearReturn', 'N/A')],
'YTD return': [info.get('ytdReturn', 'N/A')],
'Current NAV': [info.get('navPrice', 'N/A')],
'Previous close NAV': [info.get('previousClose', 'N/A')],
'Open NAV': [info.get('open', 'N/A')],
'52 week high': [info.get('fiftyTwoWeekHigh', 'N/A')],
'52 week low': [info.get('fiftyTwoWeekLow', 'N/A')],
'10-day average daily volume': [info.get('averageDailyVolume10Day', 'N/A')],
'3-month average daily volume': [info.get('averageDailyVolume3Month', 'N/A')],
'Last capital gain distributed': [info.get('lastCapGain', 'N/A')],
'Annual report expense ratio': [info.get('annualReportExpenseRatio', 'N/A')],
})
return fundamental_analysis
@tool
def get_stock_risk_assessment(ticker: str, period: str = "1y") -> pd.DataFrame:
"""Performs a risk assessment on a given stock.
Params:
- ticker: The fund/stock ticker symbol.
- period: The time period for historical data (default: "1y").
"""
stock = yf.Ticker(ticker)
history = stock.history(period=period)
# Calculate daily returns
returns = history['Close'].pct_change().dropna()
# Calculate risk metrics
volatility = returns.std() * np.sqrt(252) # Annualized volatility
beta = calculate_beta(returns, '^GSPC','^BSESN','^NSEI', period) # Beta relative to S&P 500 , BSE , NSE
var_95 = np.percentile(returns, 5) # 95% Value at Risk
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)],
'Risk score for 3 years': [info.get('threeYearRisk', 'N/A')],
})
return risk_assessment
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()
# Align the dates of stock and market returns
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
@tool
def get_technical_analysis(ticker: str, period: str = "1mo") -> pd.DataFrame:
"""Perform technical analysis on a given stock, fund will not have any technical analysis.
Params:
- ticker: The fund/stock ticker symbol.
- period: The time period for historical data (available time-periods: ["1d", "5d", "1mo", "3mo", "6mo"]).
"""
stock = yf.Ticker(ticker)
history = stock.history(period=period)
# 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
import requests
import pandas as pd
import os
# Retrieve API key
@tool
def get_stock_news(query: str, limit: int = 10, api_key: str = "488e80d0ecb2485ca8f0f824cd9f7360") -> pd.DataFrame:
"""
Fetches recent news articles related to a specific stock/fund using NewsAPI.
Params:
- query: Search term (e.g., stock/ fund ticker or company name).
- limit: The number of news articles to fetch.
- api_key: 488e80d0ecb2485ca8f0f824cd9f7360
Returns:
- A Pandas DataFrame containing the latest news articles.
"""
base_url = "https://newsapi.org/v2/everything"
params = {
"q": query,
"language": "en",
"sortBy": "publishedAt",
"pageSize": limit,
"apiKey": api_key
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status() # Raise HTTP errors if any
data = response.json()
if "articles" not in data or not data["articles"]:
return pd.DataFrame({"Error": [f"No news found for query '{query}'."]})
# Extract and format news articles
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)}"]})
def calculate_rsi(series, period=14):
delta = series.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def calculate_macd(series, short_window=12, long_window=26, signal_window=9):
short_ema = series.ewm(span=short_window, adjust=False).mean()
long_ema = series.ewm(span=long_window, adjust=False).mean()
macd = short_ema - long_ema
signal = macd.ewm(span=signal_window, adjust=False).mean()
return macd, signal
def analyze_trend(latest):
if latest['Close'] > latest['SMA_50'] > latest['SMA_200']:
return "Bullish"
elif latest['Close'] < latest['SMA_50'] < latest['SMA_200']:
return "Bearish"
else:
return "Neutral"
def analyze_macd(latest):
if latest['MACD'] > latest['Signal']:
return "Bullish"
else:
return "Bearish"
def analyze_rsi(latest):
if latest['RSI'] > 70:
return "Overbought"
elif latest['RSI'] < 30:
return "Oversold"
else:
return "Neutral"
def analyze_bollinger_bands(latest):
if latest['Close'] > latest['BB_Upper']:
return "Price above upper band (potential overbought)"
elif latest['Close'] < latest['BB_Lower']:
return "Price below lower band (potential oversold)"
else:
return "Price within bands"
def format_number(self, value):
if value != 'N/A':
return f'${value:,.2f}'
else:
return 'N/A'
def interpret_pe_ratio(self, trailing_pe):
if trailing_pe < 15:
return "Undervalued"
elif trailing_pe > 30:
return "Overvalued"
else:
return "Neutral"
def interpret_price_to_book(self, price_to_book):
if price_to_book < 1:
return "Undervalued"
elif price_to_book > 3:
return "Overvalued"
else:
return "Neutral"
# Load Model wtih parameters
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model_name="gpt-4o", # Specifies which model to use
temperature=0.1, # Controls randomness in responses
max_tokens=10000, # Maximum length of response
# top_p=0.95, # Cumulative probability for token sampling ..Since temperature is set this is commented as best practive
frequency_penalty=0.1, # Reduces repetition of similar words
presence_penalty=0.1, # Encourages discussing new topics
streaming=False, # Enables/disables incremental response output
request_timeout=240 # Maximum API response wait time
)
from langchain_openai import ChatOpenAI
from crewai import Agent
# Initialize the language model
llm = ChatOpenAI(model_name="gpt-4o")
stock_researcher = Agent(
llm=llm, # Pass the initialized language model instance
role="Stock /fund Researcher with expertise in Indian Stock and Mutual Fund",
goal="Determine the specific stock or mutual fund, including its ticker symbol, if available. If the ticker symbol is already known, retrieve essential details and fundamental information about the chosen stock or mutual fund to provide a comprehensive overview.If Ticker sysmol is unavailable try to provide the overview by the name of the fund.",
backstory="As an expert Indian stock or fund researcher skilled in collecting pertinent, foundational details about stocks and mutual funds, their respective companies, the broader industry context, and key performance insights of the stocks or funds being analyzed.",
tools=[get_basic_info],
verbose=True,
allow_delegation=False
)
financial_analyst = Agent(
llm=llm,
role="Financial Analyst with expertise in Indian Stock and Mutual Fund",
goal="Conduct a comprehensive analysis of the stock or mutual fund, integrating both fundamental and technical perspectives, with a focus on the aspects most pertinent to addressing the user's specific query.",
backstory="An experienced financial analyst adept at decoding intricate financial data and presenting actionable insights tailored to audiences with varying levels of financial expertise.",
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="Fetch recent news articles related to the stock/fund and their potential impact on performance",
backstory="A keen news analyst with a talent for rapidly processing information, evaluating its impact on stock or fund performance, and delivering clear, concise summaries tailored to key financial implications.",
tools=[get_stock_news],
verbose=True
)
report_writer = Agent(
role='Financial Report Writer',
goal='Compile all analyses into a well-structured, professional report that offers a comprehensive overview of the stock or fund, presenting insights in a clear, cohesive format for decision-making',
backstory='A skilled financial writer with a knack for producing clear, concise, and impactful reports, effectively translating complex financial data into accessible and engaging content.',
tools=[],
verbose=True,
allow_delegation=False,
llm=llm
)
collect_stock_info = Task(
description='''
1.Identify the ticker symbol(s) for the stock(s) or fund(s) mentioned in the user’s query, along with any specified timeframe. If the ticker is not provided, deduce the relevant ticker from the query.
2.If the query indicates a beginner user, offer simplified explanations of key financial terms. If no indication is given, assume the user has a strong understanding of financial concepts.
Only basic information about the stock or fund is expected for this task.
User query: {query}.
Your response should be based on:
Ticker: [identified stock/fund ticker]
Timeframe: [identified timeframe]
Analysis Focus: [key areas for analysis]
User Expertise: [assumed level of financial knowledge]
Key Concerns: [specific concerns highlighted]
News from the API key: [488e80d0ecb2485ca8f0f824cd9f7360]
''',
expected_output="Provide an overview of the stock or fund’s key financial metrics and performance, specifically addressing the aspects highlighted in the user's query. Include insights from multiple sources, offering relevant details and analysis to inform the user's decision-making.",
agent=stock_researcher,
dependencies=[],
context=[]
)
perform_analysis = Task(
description='''
Perform a detailed analysis of the stock or fund, aligned with the user's query and expertise level.
1.Utilize the appropriate tools (get_stock_info, get_fundamental_analysis, get_stock_risk_assessment, get_technical_analysis) based on the focus of the query. For example, if the question pertains to a stock’s fundamentals, exclude technical data.
2.Emphasize metrics and trends that are most relevant to the user's inquiry and timeframe.
3.Provide simplified explanations for complex financial terms if the user appears to be a novice.
4.Directly address the key concerns highlighted in the user's query interpretation.
5.Consider both historical performance and future outlook in your analysis.
User query: {query}.
''',
expected_output="A detailed analysis of the stock's / fund's financial and/or technical performance, directly addressing the user's query and concerns.",
agent=financial_analyst,
dependencies=[collect_stock_info],
context=[collect_stock_info]
)
analyze_stock_news = Task(
description='''
1.Use the get_stock_news tool to gather the latest news related to the stock or fund.
2.Conclude with a comprehensive assessment of how recent news may impact the stock or fund, considering its potential influence within the relevant timeframe.
Note: Re-fetching the news will return identical results.
''',
expected_output="A summary of recent news articles related to the stock/fund and their potential impact on performance.",
agent=news_analyst,
dependencies=[collect_stock_info],
context=[collect_stock_info]
)
generate_stock_report = Task(
description='''
Synthesize all gathered information and analyses into a comprehensive stock or fund report, precisely aligned with the user's query. The report should:
1.Begin with an Executive Summary that directly addresses the user's inquiry.
2.Include relevant sections tailored to the specific focus of the query.
3.Offer a clear Investment Recommendation that answers the user's question.
4.Conclude with a summary that ties all insights back to the original query.
Ensure that the report:
-Directly answers the user's specific question.
-Matches the user's implied level of expertise by adjusting the language and depth.
-Highlights the most relevant factors related to the user's concerns and timeframe.
-Uses clear, professional language with well-reasoned insights.
-Is formatted in markdown for ease of reading.
-Remains concise yet detailed, reiterating key points without redundancy.
-Provides a confident, expert recommendation, leaving no need for further analysis.
-Only includes relevant information based on the query, excluding unnecessary details such as technical analysis if the focus is on fundamentals.
User query: {query}.
''',
expected_output="A comprehensive yet detailed stock or fund report in markdown format that thoroughly addresses all elements of the user's query and offers a well-supported investment recommendation",
agent=report_writer,
dependencies=[collect_stock_info],
context=[collect_stock_info, perform_analysis, analyze_stock_news]
)
crew = 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
)
# Define 'query' and 'default_date' before calling crew.kickoff
query = "Analyze NVDA stock" # Replace with your desired query
import datetime
default_date = datetime.date.today()
crew.kickoff(inputs={
"query": query,
"default_date": str(default_date),
"api_key": "488e80d0ecb2485ca8f0f824cd9f7360" # Add the API key here
})
import gradio as gr
from datetime import datetime
from fpdf import FPDF
def analyze_stock_fund(query):
"""Perform stock/fund analysis using the given query."""
try:
default_date = datetime.now().date()
result = crew.kickoff(inputs={"query": query, "default_date": str(default_date)})
analysis_report = f"### Analysis Report:\n\n{result}"
# Create PDF with basic ASCII support instead of Unicode
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12) # Using built-in Arial font
# Simple text cleaning function
def clean_text(text):
return ''.join(char if ord(char) < 128 else ' ' for char in text)
pdf.cell(200, 10, txt=clean_text("Investment Advisory Analysis Report"), ln=True, align="C")
pdf.ln(10)
cleaned_report = clean_text(analysis_report)
pdf.multi_cell(0, 10, txt=cleaned_report)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_filename = f"analysis_report_{timestamp}.pdf"
try:
pdf.output(report_filename)
except Exception as e:
raise Exception(f"Failed to generate PDF: {str(e)}")
return analysis_report, report_filename
except Exception as e:
error_message = f"Error in analysis: {str(e)}"
return error_message, None
# Define the Gradio interface
with gr.Blocks() as interface:
gr.Markdown("# 💰 Robo_Financial_Buddy - Advanced Stock / Funds Analysis Advisory Report")
gr.Markdown("## Enter your Investment Query:")
query_input = gr.TextArea(
label="Your Financial ROBO Advisor",
value="Analyse ABC stock/Fund?",
lines=5,
)
analyze_button = gr.Button("Analyze")
analysis_output = gr.Markdown()
download_button = gr.File(label="Download PDF Report")
def on_analyze(query):
report, filename = analyze_stock_fund(query)
return report, filename
analyze_button.click(on_analyze, inputs=[query_input], outputs=[analysis_output, download_button])
gr.Markdown("---")
gr.Markdown("Made by Team 4")
# Launch the interface
interface.launch()