PROSTLE commited on
Commit
f22ac5e
Β·
unverified Β·
1 Parent(s): 7f5afe0

Add files via upload

Browse files
backend/technical_signals.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Technical signal scoring.
3
+ Converts raw indicator values into a directional score (-1 to +1).
4
+ Each signal has an individual sub-score; the aggregate is weighted.
5
+ """
6
+
7
+ from __future__ import annotations
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+
12
+ def score_technical_signals(df: pd.DataFrame) -> dict:
13
+ """
14
+ Analyze technical indicators and return a composite score.
15
+
16
+ Returns:
17
+ {
18
+ "score": float (-1 to +1),
19
+ "direction": "bullish" | "bearish" | "neutral",
20
+ "signals": {name: {"score": float, "value": float, "interpretation": str}},
21
+ }
22
+ """
23
+ latest = df.iloc[-1]
24
+ signals = {}
25
+
26
+ # ── 1. RSI (weight: 25%) ──────────────────────────
27
+ rsi = float(latest.get("RSI", 50))
28
+ if rsi >= 75:
29
+ rsi_score = -0.8 # overbought β†’ bearish
30
+ rsi_interp = "Overbought"
31
+ elif rsi >= 65:
32
+ rsi_score = -0.3
33
+ rsi_interp = "Slightly overbought"
34
+ elif rsi <= 25:
35
+ rsi_score = 0.8 # oversold β†’ bullish
36
+ rsi_interp = "Oversold"
37
+ elif rsi <= 35:
38
+ rsi_score = 0.3
39
+ rsi_interp = "Slightly oversold"
40
+ else:
41
+ rsi_score = 0.0
42
+ rsi_interp = "Neutral"
43
+ signals["RSI"] = {"score": rsi_score, "value": round(rsi, 2), "interpretation": rsi_interp}
44
+
45
+ # ── 2. MACD Crossover (weight: 25%) ───────────────
46
+ macd = float(latest.get("MACD", 0))
47
+ macd_signal = float(latest.get("MACD_Signal", 0))
48
+ macd_diff = macd - macd_signal
49
+ if abs(macd_diff) < 0.01:
50
+ macd_score = 0.0
51
+ macd_interp = "Neutral"
52
+ elif macd_diff > 0:
53
+ macd_score = min(0.8, macd_diff * 10) # bullish crossover
54
+ macd_interp = "Bullish crossover"
55
+ else:
56
+ macd_score = max(-0.8, macd_diff * 10) # bearish crossover
57
+ macd_interp = "Bearish crossover"
58
+ signals["MACD"] = {"score": round(macd_score, 3), "value": round(macd_diff, 4), "interpretation": macd_interp}
59
+
60
+ # ── 3. SMA Trend (weight: 20%) ────────────────────
61
+ price = float(latest["Close"])
62
+ sma20 = float(latest.get("SMA_20", price))
63
+ sma50 = float(latest.get("SMA_50", price))
64
+ above_sma20 = price > sma20
65
+ above_sma50 = price > sma50
66
+ sma20_above_50 = sma20 > sma50 # golden cross
67
+
68
+ if above_sma20 and above_sma50 and sma20_above_50:
69
+ sma_score = 0.7 # strong uptrend
70
+ sma_interp = "Strong uptrend (Golden Cross)"
71
+ elif above_sma20 and above_sma50:
72
+ sma_score = 0.4
73
+ sma_interp = "Uptrend"
74
+ elif not above_sma20 and not above_sma50 and not sma20_above_50:
75
+ sma_score = -0.7 # strong downtrend
76
+ sma_interp = "Strong downtrend (Death Cross)"
77
+ elif not above_sma20 and not above_sma50:
78
+ sma_score = -0.4
79
+ sma_interp = "Downtrend"
80
+ else:
81
+ sma_score = 0.0
82
+ sma_interp = "Mixed trend"
83
+ signals["SMA_Trend"] = {"score": sma_score, "value": round(price - sma20, 2), "interpretation": sma_interp}
84
+
85
+ # ── 4. Bollinger Band Width (weight: 15%) ─────────
86
+ bb_width = float(latest.get("BB_Width", 0))
87
+ bb_upper = float(latest.get("BB_Upper", price))
88
+ bb_lower = float(latest.get("BB_Lower", price))
89
+
90
+ if price >= bb_upper * 0.99:
91
+ bb_score = -0.5 # near upper band β†’ reversal risk
92
+ bb_interp = "Near upper band"
93
+ elif price <= bb_lower * 1.01:
94
+ bb_score = 0.5 # near lower band β†’ bounce potential
95
+ bb_interp = "Near lower band"
96
+ else:
97
+ bb_score = 0.0
98
+ bb_interp = "Within bands"
99
+ signals["Bollinger"] = {"score": bb_score, "value": round(bb_width, 4), "interpretation": bb_interp}
100
+
101
+ # ── 5. ATR Volatility (weight: 15%) ───────────────
102
+ atr = float(latest.get("ATR", 0))
103
+ atr_pct = (atr / price * 100) if price > 0 else 0
104
+ if atr_pct > 3.0:
105
+ atr_score = -0.3 # high volatility = risk
106
+ atr_interp = "High volatility"
107
+ elif atr_pct > 2.0:
108
+ atr_score = -0.1
109
+ atr_interp = "Moderate volatility"
110
+ else:
111
+ atr_score = 0.1
112
+ atr_interp = "Low volatility"
113
+ signals["ATR"] = {"score": atr_score, "value": round(atr_pct, 2), "interpretation": atr_interp}
114
+
115
+ # ── Weighted composite ────────────────────────────
116
+ weights = {"RSI": 0.25, "MACD": 0.25, "SMA_Trend": 0.20, "Bollinger": 0.15, "ATR": 0.15}
117
+ composite = sum(signals[k]["score"] * weights[k] for k in weights)
118
+ composite = max(-1.0, min(1.0, composite))
119
+
120
+ if composite > 0.15:
121
+ direction = "bullish"
122
+ elif composite < -0.15:
123
+ direction = "bearish"
124
+ else:
125
+ direction = "neutral"
126
+
127
+ return {
128
+ "score": round(composite, 3),
129
+ "direction": direction,
130
+ "signals": signals,
131
+ }
backend/test_sentiment_upgrades.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import sys
3
+ import os
4
+ sys.path.append(os.path.join(os.getcwd(), "backend"))
5
+
6
+ from sentiment import analyze_sentiment, _is_relevant, _check_overrides, _is_noise
7
+
8
+ # Test Cases
9
+ headlines = [
10
+ # 1. Guidance Cut (Should be Negative Override)
11
+ "L&T Technology Services cuts revenue forecast, sees mid single-digit growth",
12
+
13
+ # 2. Irrelevant Noise (Should be Filtered)
14
+ "106-year-old retailer closing all stores in Chapter 11 bankruptcy",
15
+
16
+ # 3. Metadata Hallucination (Should be Filtered)
17
+ "ICICI Bank Ltd",
18
+
19
+ # 4. Legit Positive News (Should remain Positive)
20
+ "RBI approves ICICI Group stake hike in eight banks",
21
+
22
+ # 5. Generic Noise (Should be Filtered)
23
+ "Reliance share price live updates",
24
+
25
+ # 6. Alias Check: Tata Steel (Should be Relevant now)
26
+ "Tata Steel reports 10% growth in production",
27
+
28
+ # 7. Alias Check: Bajaj Finance (Should be Relevant now)
29
+ "Bajaj Finance profit jumps 20%",
30
+ ]
31
+
32
+ ticker_icici = "ICICIBANK.NS"
33
+ ticker_tata = "TATASTEEL.NS"
34
+ ticker_bajaj = "BAJFINANCE.NS"
35
+
36
+ print("--- Unit Tests ---")
37
+ print(f"1. Is '106-year-old retailer...' relevant for ICICI? {_is_relevant(headlines[1], ticker_icici)} (Expected: False)")
38
+ print(f"2. Is 'ICICI Bank Ltd' noise? {_is_noise(headlines[2])} (Expected: True)")
39
+ print(f"3. Override score for 'cuts revenue forecast': {_check_overrides(headlines[0])} (Expected: -0.8)")
40
+ print(f"4. Is 'Tata Steel reports...' relevant for TATASTEEL? {_is_relevant(headlines[5], ticker_tata)} (Expected: True)")
41
+ print(f"5. Is 'Bajaj Finance profit...' relevant for BAJFINANCE? {_is_relevant(headlines[6], ticker_bajaj)} (Expected: True)")
42
+
43
+ print("\n--- Full Analysis Simulation ---")
44
+ # Mocking fetch_news_headlines is hard without mocking the module,
45
+ # so we'll test the logic components directly as above.