Views
No views yet
1from transformers import AutoModelForCausalLM, AutoTokenizer
2import torch
3import json
4
5# Load model and tokenizer
6model_name = "jialeCharlotte/finbot"
7tokenizer = AutoTokenizer.from_pretrained(model_name)
8model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
9
10def analyze_sentiment(news_title, news_summary, ticker):
11 prompt = f"""You are a financial analyst in a leading hedge fund.
12Analyze the sentiment of the following financial news for the given stock ticker step by step.
13
14Title: "{news_title}"
15Summary: "{news_summary}"
16Stock Ticker: {ticker}
17
18Step 1: Identify key financial terms and their implications.
19Step 2: Determine whether the news suggests market optimism, pessimism, or neutrality for this specific stock.
20Step 3: Based on your analysis, classify the sentiment into one of the following categories:
21- "Bullish": If the news suggests confidence, growth, or positive impact on this stock.
22- "Bearish": If the news suggests decline, risks, or negative impact on this stock.
23- "Neutral": If the news is ambiguous or does not convey strong sentiment.
24
25Finally, **return only** the final result in valid JSON format, with the structure:
26{{
27 "ticker": "{ticker}",
28 "sentiment": "Bullish" | "Bearish" | "Neutral",
29 "sentiment_reasoning": "Provide a brief explanation of the sentiment analysis."
30}}
31
32Do not include any extra text or explanations outside the JSON.
33### Response:
34"""
35
36 inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
37
38 with torch.no_grad():
39 outputs = model.generate(
40 **inputs,
41 max_new_tokens=200,
42 do_sample=True,
43 temperature=0.7,
44 top_p=0.9,
45 pad_token_id=tokenizer.pad_token_id
46 )
47
48 response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
49
50 try:
51 # Parse the JSON response
52 result = json.loads(response)
53 return result
54 except json.JSONDecodeError:
55 # If the response isn't valid JSON, return the raw text
56 return {"error": "Failed to parse response", "raw_response": response}
57
58# Example usage
59news_title = "Apple Reports Record Q1 Revenue"
60news_summary = "Apple Inc. announced today that they have achieved record-breaking revenue in Q1 2025, exceeding analyst expectations by 15%."
61ticker = "AAPL"
62
63result = analyze_sentiment(news_title, news_summary, ticker)
64print(result)@misc{finbot2025,
author = {Charlotte Zhou, Zhilin Zhu},
title = {FinBot - Financial Sentiment Analyzer},
year = {2025},
publisher = {HuggingFace},
howpublished = {\url{https://huggingface.co/jialeCharlotte/finbot}}
}