Spaces:
Sleeping
Sleeping
File size: 9,678 Bytes
264c9bf | 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | #!/usr/bin/env python3
"""
Pre-Market Global Cues Analysis
Fetches and analyzes global market data before NSE opening to predict market sentiment
"""
import json
import yfinance as yf
from datetime import datetime, timedelta
from pathlib import Path
import pytz
BASE_DIR = Path(__file__).parent
PREMARKET_FILE = BASE_DIR / "premarket_cues.json"
IST = pytz.timezone('Asia/Kolkata')
def fetch_us_markets():
"""Fetch previous day's US market data"""
try:
symbols = {
"^GSPC": "S&P 500",
"^IXIC": "Nasdaq",
"^DJI": "Dow Jones"
}
results = {}
for symbol, name in symbols.items():
ticker = yf.Ticker(symbol)
hist = ticker.history(period="5d")
if len(hist) >= 2:
prev_close = hist['Close'].iloc[-2]
last_close = hist['Close'].iloc[-1]
change_pct = ((last_close - prev_close) / prev_close) * 100
results[name] = {
"close": float(last_close),
"change_pct": float(change_pct),
"sentiment": "BULLISH" if change_pct > 0.5 else ("BEARISH" if change_pct < -0.5 else "NEUTRAL")
}
return results
except Exception as e:
print(f"โ ๏ธ Error fetching US markets: {e}")
return {}
def fetch_asian_markets():
"""Fetch Asian market data"""
try:
symbols = {
"^N225": "Nikkei 225",
"^HSI": "Hang Seng"
}
results = {}
for symbol, name in symbols.items():
ticker = yf.Ticker(symbol)
hist = ticker.history(period="5d")
if len(hist) >= 2:
prev_close = hist['Close'].iloc[-2]
last_close = hist['Close'].iloc[-1]
change_pct = ((last_close - prev_close) / prev_close) * 100
results[name] = {
"close": float(last_close),
"change_pct": float(change_pct),
"sentiment": "BULLISH" if change_pct > 0.5 else ("BEARISH" if change_pct < -0.5 else "NEUTRAL")
}
return results
except Exception as e:
print(f"โ ๏ธ Error fetching Asian markets: {e}")
return {}
def fetch_sgx_nifty():
"""Fetch SGX Nifty data (using Nifty 50 as proxy)"""
try:
ticker = yf.Ticker("^NSEI")
hist = ticker.history(period="5d")
if len(hist) >= 2:
prev_close = hist['Close'].iloc[-2]
last_close = hist['Close'].iloc[-1]
change_pct = ((last_close - prev_close) / prev_close) * 100
return {
"close": float(last_close),
"change_pct": float(change_pct),
"sentiment": "BULLISH" if change_pct > 0.5 else ("BEARISH" if change_pct < -0.5 else "NEUTRAL")
}
except Exception as e:
print(f"โ ๏ธ Error fetching SGX Nifty: {e}")
return {}
def fetch_crude_oil():
"""Fetch Crude Oil prices"""
try:
ticker = yf.Ticker("CL=F")
hist = ticker.history(period="5d")
if len(hist) >= 2:
prev_close = hist['Close'].iloc[-2]
last_close = hist['Close'].iloc[-1]
change_pct = ((last_close - prev_close) / prev_close) * 100
return {
"price": float(last_close),
"change_pct": float(change_pct),
"sentiment": "BULLISH" if change_pct > 2 else ("BEARISH" if change_pct < -2 else "NEUTRAL")
}
except Exception as e:
print(f"โ ๏ธ Error fetching Crude Oil: {e}")
return {}
def fetch_dollar_index():
"""Fetch Dollar Index (DXY)"""
try:
ticker = yf.Ticker("DX-Y.NYB")
hist = ticker.history(period="5d")
if len(hist) >= 2:
prev_close = hist['Close'].iloc[-2]
last_close = hist['Close'].iloc[-1]
change_pct = ((last_close - prev_close) / prev_close) * 100
# For Indian markets, strong dollar is bearish
return {
"value": float(last_close),
"change_pct": float(change_pct),
"sentiment": "BEARISH" if change_pct > 0.5 else ("BULLISH" if change_pct < -0.5 else "NEUTRAL")
}
except Exception as e:
print(f"โ ๏ธ Error fetching Dollar Index: {e}")
return {}
def calculate_overall_sentiment(data):
"""Calculate overall market sentiment from all indicators"""
sentiments = []
weights = {
"us_markets": 0.35,
"asian_markets": 0.25,
"sgx_nifty": 0.25,
"crude_oil": 0.10,
"dollar_index": 0.05
}
score = 0
# US Markets
if "us_markets" in data:
for market, info in data["us_markets"].items():
if info["sentiment"] == "BULLISH":
score += weights["us_markets"] / len(data["us_markets"])
elif info["sentiment"] == "BEARISH":
score -= weights["us_markets"] / len(data["us_markets"])
# Asian Markets
if "asian_markets" in data:
for market, info in data["asian_markets"].items():
if info["sentiment"] == "BULLISH":
score += weights["asian_markets"] / len(data["asian_markets"])
elif info["sentiment"] == "BEARISH":
score -= weights["asian_markets"] / len(data["asian_markets"])
# SGX Nifty
if "sgx_nifty" in data and data["sgx_nifty"]:
if data["sgx_nifty"]["sentiment"] == "BULLISH":
score += weights["sgx_nifty"]
elif data["sgx_nifty"]["sentiment"] == "BEARISH":
score -= weights["sgx_nifty"]
# Crude Oil
if "crude_oil" in data and data["crude_oil"]:
if data["crude_oil"]["sentiment"] == "BULLISH":
score += weights["crude_oil"]
elif data["crude_oil"]["sentiment"] == "BEARISH":
score -= weights["crude_oil"]
# Dollar Index
if "dollar_index" in data and data["dollar_index"]:
if data["dollar_index"]["sentiment"] == "BULLISH":
score += weights["dollar_index"]
elif data["dollar_index"]["sentiment"] == "BEARISH":
score -= weights["dollar_index"]
# Determine overall sentiment
if score > 0.15:
return "BULLISH", score
elif score < -0.15:
return "BEARISH", score
else:
return "NEUTRAL", score
def fetch_premarket_data():
"""Fetch all pre-market data and save to file"""
print("๐ Fetching pre-market global cues...")
data = {
"timestamp": datetime.now(IST).strftime("%Y-%m-%d %H:%M:%S IST"),
"us_markets": fetch_us_markets(),
"asian_markets": fetch_asian_markets(),
"sgx_nifty": fetch_sgx_nifty(),
"crude_oil": fetch_crude_oil(),
"dollar_index": fetch_dollar_index()
}
# Calculate overall sentiment
sentiment, score = calculate_overall_sentiment(data)
data["overall_sentiment"] = sentiment
data["sentiment_score"] = round(score, 3)
# Save to file
with open(PREMARKET_FILE, 'w') as f:
json.dump(data, f, indent=2)
print(f"โ
Pre-market analysis complete: {sentiment} (Score: {score:.3f})")
return data
def load_premarket_data():
"""Load pre-market data from file"""
if PREMARKET_FILE.exists():
try:
with open(PREMARKET_FILE, 'r') as f:
return json.load(f)
except:
return None
return None
def is_premarket_data_fresh(max_age_hours=24):
"""Check if pre-market data is fresh"""
data = load_premarket_data()
if not data or "timestamp" not in data:
return False
try:
data_time = datetime.strptime(data["timestamp"], "%Y-%m-%d %H:%M:%S IST")
data_time = IST.localize(data_time)
age = datetime.now(IST) - data_time
return age.total_seconds() / 3600 < max_age_hours
except:
return False
def get_premarket_sentiment():
"""Get current pre-market sentiment (fetch if stale)"""
if not is_premarket_data_fresh():
print("๐ Pre-market data is stale, fetching fresh data...")
return fetch_premarket_data()
return load_premarket_data()
# Test function
if __name__ == "__main__":
print("๐ Pre-Market Global Cues Analysis")
print("=" * 60)
data = fetch_premarket_data()
print("\n๐ Summary:")
print(f"Overall Sentiment: {data['overall_sentiment']}")
print(f"Sentiment Score: {data['sentiment_score']}")
print(f"\nTimestamp: {data['timestamp']}")
if data.get("us_markets"):
print("\n๐บ๐ธ US Markets:")
for name, info in data["us_markets"].items():
print(f" {name}: {info['change_pct']:+.2f}% ({info['sentiment']})")
if data.get("asian_markets"):
print("\n๐ Asian Markets:")
for name, info in data["asian_markets"].items():
print(f" {name}: {info['change_pct']:+.2f}% ({info['sentiment']})")
if data.get("sgx_nifty"):
print(f"\n๐ธ๐ฌ SGX Nifty: {data['sgx_nifty']['change_pct']:+.2f}% ({data['sgx_nifty']['sentiment']})")
if data.get("crude_oil"):
print(f"\n๐ข๏ธ Crude Oil: ${data['crude_oil']['price']:.2f} ({data['crude_oil']['change_pct']:+.2f}%)")
if data.get("dollar_index"):
print(f"\n๐ต Dollar Index: {data['dollar_index']['value']:.2f} ({data['dollar_index']['change_pct']:+.2f}%)")
|