-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_stock_alerts.py
More file actions
155 lines (118 loc) · 4.74 KB
/
Copy pathcheck_stock_alerts.py
File metadata and controls
155 lines (118 loc) · 4.74 KB
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
#!/usr/bin/env python3
"""
股價警報檢查工具
檢查美股是否接近支撐點或壓力點
"""
import json
import yfinance as yf
from datetime import datetime
# 警報距離閾值(百分比)
ALERT_THRESHOLD = 3.0
def load_stock_data(filename='stock_data_20260125.json'):
"""載入股票資料"""
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
def get_current_price(ticker, is_tw_stock=False):
"""取得即時股價"""
try:
# 台股需要加上 .TW 後綴
symbol = f"{ticker}.TW" if is_tw_stock else ticker
stock = yf.Ticker(symbol)
data = stock.history(period='1d', interval='1m')
if not data.empty:
return data['Close'].iloc[-1]
# 如果即時資料失敗,嘗試取得最新收盤價
info = stock.info
return info.get('currentPrice') or info.get('regularMarketPrice')
except Exception as e:
print(f"⚠️ 無法取得 {ticker} 的股價: {e}")
return None
def check_alert(stock, current_price):
"""檢查是否接近支撐點或壓力點"""
alerts = []
# 檢查支撐點
if stock['shortSupport']:
support = stock['shortSupport']
distance_to_support = ((current_price - support) / support) * 100
if 0 <= distance_to_support <= ALERT_THRESHOLD:
alerts.append({
'type': '接近支撐點',
'level': support,
'distance': distance_to_support
})
# 檢查壓力點
if stock['shortPressure']:
pressure = stock['shortPressure']
distance_to_pressure = ((pressure - current_price) / current_price) * 100
if 0 <= distance_to_pressure <= ALERT_THRESHOLD:
alerts.append({
'type': '接近壓力點',
'level': pressure,
'distance': distance_to_pressure
})
return alerts
def check_stocks(stocks, category_name, is_tw_stock=False):
"""檢查股票並顯示警報"""
alert_count = 0
for stock in stocks:
ticker = stock['code']
name = stock['name']
# 取得即時股價
current_price = get_current_price(ticker, is_tw_stock)
if current_price is None:
continue
# 檢查警報
alerts = check_alert(stock, current_price)
if alerts:
alert_count += 1
currency = 'NT$' if is_tw_stock else '$'
print(f"🔔 {name} ({ticker})")
print(f" 目前價位: {currency}{current_price:.2f}")
for alert in alerts:
print(f" ⚠️ {alert['type']}: {currency}{alert['level']:.2f} (距離 {alert['distance']:.2f}%)")
print(f" 週變化: {stock['weeklyChange']}")
print(f" 風險等級: {stock['riskLevel']}")
# 顯示支撐點和壓力點
if stock['shortSupport']:
print(f" 支撐點: {currency}{stock['shortSupport']:.2f}")
if stock['shortPressure']:
print(f" 壓力點: {currency}{stock['shortPressure']:.2f}")
print()
return alert_count
def main():
"""主程式"""
print("=" * 80)
print(f"📊 台美股警報檢查 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 80)
print()
# 載入資料
data = load_stock_data()
tw_stocks = [s for s in data['stocks'] if s['category'] == '台股類']
us_stocks = [s for s in data['stocks'] if s['category'] == '美股類']
total_alert_count = 0
# 檢查台股
print(f"🇹🇼 正在檢查 {len(tw_stocks)} 支台股...")
print()
tw_alert_count = check_stocks(tw_stocks, '台股', is_tw_stock=True)
total_alert_count += tw_alert_count
if tw_alert_count == 0:
print(f"✅ 台股:目前沒有股票接近支撐點或壓力點({ALERT_THRESHOLD}%範圍內)")
print()
print("-" * 80)
print()
# 檢查美股
print(f"🇺🇸 正在檢查 {len(us_stocks)} 支美股...")
print()
us_alert_count = check_stocks(us_stocks, '美股', is_tw_stock=False)
total_alert_count += us_alert_count
if us_alert_count == 0:
print(f"✅ 美股:目前沒有股票接近支撐點或壓力點({ALERT_THRESHOLD}%範圍內)")
print()
print("=" * 80)
if total_alert_count == 0:
print(f"✅ 所有股票都沒有接近支撐點或壓力點({ALERT_THRESHOLD}%範圍內)")
else:
print(f"📢 共有 {total_alert_count} 支股票觸發警報 (台股: {tw_alert_count}, 美股: {us_alert_count})")
print("=" * 80)
if __name__ == '__main__':
main()