from pykrx import stock
import time
from datetime import datetime
def get_stock_name(stock_code):
"""종목 이름 가져오기"""
try:
return stock.get_market_ticker_name(stock_code)
except:
return '종목명 불명'
def monitor_1minute(stock_code):
"""1분 동안 감시하고 고가, 저가, 종가를 기록하는 함수"""
prices = []
start_time = datetime.now()
print(f"1분 감시 시작: {start_time.strftime('%H:%M:%S')}")
# 1분(60초) 동안 5초마다 현재가 수집
for i in range(12): # 60초 ÷ 5초 = 12번
try:
current_price = stock.get_market_price_by_ticker(stock_code).iloc[0]['현재가']
prices.append(current_price)
now = datetime.now().strftime('%H:%M:%S')
print(f"[{now}] 현재가: {current_price:,}원")
except Exception as e:
print(f"현재가 가져오기 실패: {e}")
time.sleep(5) # 5초 대기
end_time = datetime.now()
if prices:
return {
'고가': max(prices),
'저가': min(prices),
'종가': prices[-1], # 마지막 가격이 종가
'시작시간': start_time,
'종료시간': end_time
}
else:
return None
def main():
# 주식 코드 입력 받기
stock_code = input("주식 코드를 입력하세요 (예: 005930): ")
# 종목 이름 가져오기
stock_name = get_stock_name(stock_code)
print(f"\n{stock_name} ({stock_code}) 무한 모니터링을 시작합니다.")
print("⚠️ 프로그램을 멈추려면 Ctrl+C를 누르세요")
print("🔄 프로그램이 계속 실행됩니다...\n")
cycle_count = 1
while True:
try:
print(f"🔍 === {cycle_count}번째 감시 시작 ===")
result = monitor_1minute(stock_code)
if result:
time.sleep(1)
start_str = result['시작시간'].strftime('%H:%M:%S')
end_str = result['종료시간'].strftime('%H:%M:%S')
print(f"\n{'='*60}")
print(f"📊 {stock_name} ({stock_code}) - {cycle_count}번째 결과")
print(f"📅 감시 기간: {start_str} ~ {end_str}")
print(f"📈 고가: {result['고가']:,}원")
print(f"📉 저가: {result['저가']:,}원")
print(f"💰 종가: {result['종가']:,}원")
print(f"{'='*60}\n")
else:
print("❌ 데이터를 가져올 수 없었습니다.\n")
cycle_count += 1
print("⏳ 2초 후 다음 감시를 시작합니다...")
time.sleep(2)
except KeyboardInterrupt:
print(f"\n🛑 사용자가 프로그램을 중단했습니다.")
print(f"📊 총 {cycle_count-1}번의 감시를 완료했습니다.")
break
except Exception as e:
print(f"❌ 오류 발생: {e}")
print("🔄 5초 후 다시 시도합니다...")
time.sleep(5)
continue
if name == "main":
main() 종목코드를 치면 오류가 나오는데 코드를 다듬어줘