File size: 11,460 Bytes
ba59952 868a13d ba59952 868a13d ba59952 868a13d ba59952 5819399 868a13d ba59952 868a13d ba59952 868a13d ba59952 868a13d ba59952 868a13d 5819399 ba59952 5819399 ba59952 5819399 ba59952 5819399 ba59952 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import os
import gradio as gr
from openai import OpenAI
from langchain.document_loaders import PyPDFLoader
# Initialize OpenAI client with environment variables
client = OpenAI(
base_url=os.environ.get("OPENAI_BASE_URL"),
api_key=os.environ.get("OPENAI_API_KEY")
)
# Your original prompt template
prompt_template = """
For any TYPE of document/pdf/filling STRICTLY stick to the format mentioned below:
📊 [Stock Name]
Type: [First, strictly scan through all the pages of the entire PDF thoroughly from start to end before proceeding, then consider categories such as Quarterly Results (a dedicated filing focused on financial performance for a specific quarter, containing a structured financial table with revenue, profit, expenses, and key financial metrics, often appearing on a single page within a multi-page PDF, also Note that if the type detected is 'Board Meeting Outcome', the system must first check whether the filing contains structured financial data such as that found in Quarterly or Annual Results filings, for example, a statement of consolidated unaudited financial results with standardized financial period headings and, in most cases, reclassify it accordingly as a Quarterly or Annual Result filing. All extraction and classification should strictly focus on consolidated numbers, ensuring that no standalone figures are used at any point), Investor Presentation (a broader document providing strategic insights, business outlook, and company initiatives, often structured with visuals and management commentary rather than just financial data), Earnings Conference Call (a transcript or summary of discussions between management and investors/analysts, focusing on qualitative insights, future guidance, and responses to analyst questions while referencing financial performance), Earnings Presentation (a structured report summarizing quarterly or annual financial performance, often used in earnings calls, containing key financial highlights, segment performance, management commentary, and forward-looking insights, typically presented as slides with charts and graphs), Annual Results, Corporate Announcement, Regulatory Filing, Board Meeting Outcome, Merger & Acquisition Announcement, Dividend Declaration, Stock Split / Bonus Issue, Preferential Allotment / QIP (Qualified Institutional Placement), Buyback Announcement, Credit Rating Update, Strategic Partnership, Legal Update, Operational Update, Investment Outlook, Press Release, Order Win, Expansion, Joint Venture, FII/DII Investment Disclosure, Pledge/Release of Shares, Insider Trading Disclosure, SEBI/Exchange Compliance Filing, Scheme of Arrangement / Demerger, Resignation / Appointment of Key Personnel, Shareholder Meeting (AGM/EGM) Notice & Outcome, ESOP / Employee Benefit Plan Update, Bankruptcy / Insolvency Proceedings, Litigation / Court Order Update, Policy Change / Government Regulation Impact, Capital Expenditure (Capex) Update, Debt Raising / Fundraising Activity, MoU / Agreement Signing, Technology or Product Launch, Environmental, Social & Governance (ESG) Report, Investment by Subsidiary / Associate Company, Foreign Collaboration / FDI Update, Management Commentary / Business Update, Stock Exchange Clarification / Response to Query, Patent / Intellectual Property Filing, R&D / Innovation Update, Market Share / Competitive Positioning Update, etc.]
Sentiment: [Carefully assess the overall sentiment of the document by considering both the quantitative financial metrics (e.g., revenue, EBITDA, PAT, and growth percentages) and the qualitative language used (e.g., tone, forward-looking statements, and risk factors). Use the following guidelines:
- Positive🟢: If the document shows strong performance, robust growth, and an optimistic tone about future prospects.
- Negative🔴: If the document reveals significant declines in key metrics or includes language that expresses caution or highlights severe risk factors.
- Neutral🟡: If the document presents mixed results, with improvements in some areas and declines in others, resulting in no clear overall trend.]
Exclude the heading 'Summary' and provide only the summarized content in the specified format
Summary:[You are an expert financial editor with experience at top global investment banks and financial publications (JP Morgan, Goldman Sachs, The Economic Times, Moneycontrol, etc.). Depending on the 'Type' it falls under mentioned below, your task is to generate a clear, accurate, and actionable summary of the stock filing following the given format instructions for each Type.
-If the type is 'Quarterly Result', identify the correct financial table, i.e., the statement of consolidated unaudited financial results, and strictly focus on consolidated results for extraction. Ensure that no standalone figures are used at any point in the extraction process. Then, standardize the reporting period: financial results tables generally follow one of two formats: (1) The first format includes headings such as "3 Months Ended" (e.g., 31.12.2024) for the latest current quarter, "Preceding 3 Months Ended" for the prior quarter, and "Corresponding 3 Months Ended in Previous Year" (e.g., 31.12.2023) for YoY comparison. It may also include "Year to Date Figures" and "Previous Financial Year Ended" for cumulative data. (2) The second format includes headings like "For the Quarter Ended" (with dates), "For the Nine Months Ended," and "For the Year Ended," which refers to the full previous fiscal year. To identify the latest quarter, look for the most recent date under the "Quarter Ended" section while ensuring it is not confused with "Nine Months Ended" or "Year Ended" data. Once the latest quarter is determined, the previous quarter is calculated by subtracting three months from this date, and the corresponding quarter from the previous financial year is calculated by subtracting twelve months. Convert quarter labels into the fiscal year format as follows: 31 December 2024 → Q3 FY25, 30 September 2024 → Q2 FY25, 30 June 2024 → Q1 FY25. Prioritize year-over-year (YoY) comparison by comparing the latest quarter’s key metrics with the same quarter from the previous financial year. If YoY data is unavailable, perform a quarter-over-quarter (QoQ) comparison instead. If the document is an annual report, compare the current financial year to the previous one using the same structured approach. Strictly ignore all other financial metrics such as EPS, margins, expenses, or other ratios. Format the final output strictly using consolidated numbers as follows: 🛒 Revenue from Operations : ( strictly extract and compare the latest current quarter consolidated numbers Vs consolidated numbers of the corresponding quarter from the previous financial year, and the increase/decrease percentage. Any mention of standalone figures should be disregarded ). 💸 Net Profit OR Net Loss : (detect whether it is profit or loss, strictly extract and compare the latest current quarter consolidated numbers Vs consolidated numbers of the corresponding quarter from the previous financial year, and the increase/decrease percentage. Standalone figures must be ignored ).
-If the type is 'Earnings Presentation,' extract key financial highlights, segment performance, operational updates, and management outlook. Prioritize major business insights over raw financial data unless they are essential for context. Summarize the final output in less than 60 words strictly in this format: 📊 Financial Highlights: (COMPARE the latest CURRENT quarter AND The corresponding quarter from the previous financial year, Comment on the amount as well as the up/down by X% YoY) (Revenue, EBITDA, Net Profit growth trends, margins, key financial ratios, and major cost drivers) /n 📦 Segment Performance: (Breakdown of revenue/profit by business segments, geographical growth, volume trends, demand-supply dynamics) /n 🏭 Operational Updates: (Efficiency improvements, capacity utilization, cost optimizations, supply chain insights, expansion plans) /n 🚀 Key Business Developments:(New product launches, strategic partnerships, order wins, major contracts, regulatory approvals) /n 🔮 Management Outlook: (Future growth plans, upcoming investments, market conditions, industry trends, and company strategy).
-If the type is 'Investor Presentation,' extract only strategic and forward-looking insights, avoiding well-known company information. Prioritize business expansion, competitive positioning, and future growth plans. Summarize the final output in less than 60 words strictly in this format: 🏢 Company Strategy & Vision: (Key focus areas, long-term goals, leadership priorities) /n 🚀 Growth & Expansion Plans: (Market expansion, acquisitions, CAPEX investments, product innovation) /n 🏆 Competitive Positioning: (Industry leadership, differentiation, unique value proposition, market share trends) /n 📦 Business Momentum: (Major partnerships, order wins, strategic collaborations, operational milestones) /n ⚡ Technology & Innovation: (R&D breakthroughs, AI/digital transformation, sustainability initiatives) /n 📅 Regulatory & Industry Trends: (Macro trends, government policies, sector-specific regulatory developments) /n 🔮 Outlook & Future Roadmap: (Management commentary on future strategy, key priorities, expected challenges/opportunities).
-For all other types except ('Quarterly Result', 'Earnings Conference Call' ,'Earnings Presentation', 'Investor Presentation'), Summarize in less than 60 words. Format the final output as: (Provide a concise, structured summary capturing the most critical insights. Include an impact statement within the last line of the paragraph if the news significantly affects the company’s future; otherwise, omit it)
1. Leave one blank line.
2. Add: Instant stock updates delivered by Stocker⚡
Ensure strict adherence to formatting and financial accuracy.
{text}
Instant stock updates delivered by Stocker⚡
"""
def analyze_pdf(file):
try:
# Load and process PDF
loader = PyPDFLoader(file.name)
docs = loader.load()
combined_text = " ".join([doc.page_content for doc in docs])
# Prepare the prompt
prompt = prompt_template.format(text=combined_text)
# Call OpenAI API
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a financial analyst summarizing stock filings."},
{"role": "user", "content": prompt}
],
temperature=0,
max_tokens=150 # Token limit set to 150
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"⚠️ Error: {str(e)}"
# Gradio interface
with gr.Blocks(title="Stocker - Financial Analysis") as app:
# Title
gr.Markdown("## 📈 Stocker: Financial Analysis")
# File Upload
with gr.Row():
pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
# Analyze Button
analyze_btn = gr.Button("Analyze", variant="primary")
# Output
output = gr.Textbox(label="Analysis Summary", lines=10, placeholder="Your summary will appear here...")
# Link button and output
analyze_btn.click(fn=analyze_pdf, inputs=pdf_input, outputs=output)
# Launch the app
if __name__ == "__main__":
app.launch() |