https://marketward.tistory.com/25
[Python/파이썬] 네이버증권API 활용 - 미국 주식 전체 종목 정보 가져오기
네이버증권 API를 활용하여 네이버에서 제공하는 미국 주식의 전체 종목을 리스트로 만들어 보겠습니다. 미국 주식에 대한 기본적인 API는 "뉴욕 거래소, 나스닥, 아멕스"로 3개의 api 주소를 찾았
marketward.tistory.com
https://marketward.tistory.com/27
[Python/파이썬] 네이버증권API 활용 - 미국 주식 종목 정보 가져오기
네이버증권API에서 미국 주식의 단일 종목 정보도 가져올 수 있어서 글을 남깁니다. https://api.stock.naver.com/stock/{종목 코드}/basic위와 같은 구조를 가지고 있으며, 예시로서...https://api.stock.naver.com/
marketward.tistory.com
네이버증권API에서 미국 주식의 전체 종목을 가져왔고, 개별 종목에 대해서도 정보를 가져올 수 있게 되었습니다.
자아... 무엇을 해볼 수 있을까 고민해보다가 고배당주를 찾아보고자 합니다.
import csv
import urllib.request
import json
from multiprocessing import Pool, cpu_count
from multiprocessing import freeze_support
def fetch_data(url):
try:
with urllib.request.urlopen(url) as response:
return json.loads(response.read().decode('utf-8'))
except Exception as e:
print(f"Error fetching data from {url}: {e}")
return None
def get_stock_list(exchange, page):
url = f"https://api.stock.naver.com/stock/exchange/{exchange}/marketValue?page={page}&pageSize=100"
data = fetch_data(url)
return [
(stock['reutersCode'], stock['stockName'])
for stock in data['stocks']
] if data else []
def find_high_dividend_stocks(stock_code, stock_name, input_rate):
url = f"https://api.stock.naver.com/stock/{stock_code}/basic"
data = fetch_data(url)
if not data:
return None
dividend_info = {item['key']: item['value'] for item in data.get('stockItemTotalInfos', [])}
yield_ratio = dividend_info.get("배당수익률")
if yield_ratio and yield_ratio != 'N/A' and float(yield_ratio.replace('%', '')) >= input_rate:
return {
"종목명": stock_name,
"배당수익률": yield_ratio,
"배당일": dividend_info.get("배당일"),
"배당락일": dividend_info.get("배당락일")
}
return None
# 종목이 워낙 많아서 multiprocessing을 사용 하겠습니다.
if __name__ == "__main__":
#pyinstaller 로 exe 만들 때 필요. 없으면 무한 멀티프로세싱의 늪으로 빠집니다...
freeze_support()
#"NYSE", "NASDAQ", "AMEX" 종목 리스트 가져오기
print("미국 주식의 종목 리스트를 가져오는 중...")
exchanges = ["NYSE", "NASDAQ", "AMEX"]
all_stocks = []
# 거래소별 데이터 병렬 처리
with Pool(cpu_count()) as pool: #CPU의 최대 쓰레드를 사용 하겠습니다.
for exchange in exchanges:
total_count = fetch_data(f"https://api.stock.naver.com/stock/exchange/{exchange}/marketValue")['totalCount']
pages = (total_count // 100) + 1
results = pool.starmap(get_stock_list, [(exchange, page) for page in range(1, pages + 1)])
for stocks in results:
all_stocks.extend(stocks)
input_rate = float(input("찾는 배당률(%)의 최소값을 숫자로 입력하세요 (예시 10.05): "))
print("찾는 중 입니다. 기다려주세요...")
# 고배당주 병렬 검색
high_dividend_stocks = []
with Pool(cpu_count()) as pool:
results = pool.starmap(find_high_dividend_stocks, [(code, name, input_rate) for code, name in all_stocks])
high_dividend_stocks = [res for res in results if res] # None 값 필터링
# CSV 파일로 저장
with open("high_dividend_stocks.csv", mode="w", newline="", encoding="ANSI") as file:
writer = csv.DictWriter(file, fieldnames=["종목명", "배당수익률", "배당일", "배당락일"])
writer.writeheader()
writer.writerows(high_dividend_stocks)
print(f"총 {len(high_dividend_stocks)}개의 고배당주가 high_dividend_stocks.csv 파일에 저장되었습니다.")
실행하시면... 배당률을 입력하도록 했습니다.
목표하시는 배당률을 입력하고 엔터를 누르시면... 검색이 시작 됩니다.
배당률 15% 이상 있을지 검색해 보았는데요.
"high_dividend_stocks.csv" 파일이 저장 되었습니다. 열어보니 55건이 나옵니다.
배당률이라는게 지난 배당 대비 현 주식의 가격으로 보여주기에 항상 보장되는 비율은 아닙니다.
그러니 종목 투자하실 때 다방면으로도 조사를 하시기 바랍니다!! (배당률 30% 이런건 뭔지 모르겠지만 그냥 무섭네요...)
'Python > 네이버증권API(New)' 카테고리의 다른 글
[네이버증권] 25년3월9일부터 "몇 층에서 샀을까?" 데이터 수집 그리고 조회 페이지 배포 (0) | 2025.03.19 |
---|---|
[Python/파이썬] 네이버증권 웹 크롤링 활용 - 몇 층에서 샀을까? (국장) (0) | 2025.02.16 |
[Python/파이썬] 네이버증권API 활용 - 미국 주식 종목 정보 가져오기 (0) | 2024.12.02 |
[Python/파이썬] 네이버증권API 활용 - 미국 주식 전체 종목 정보 가져오기 (7) | 2024.07.07 |
[Python/파이썬] 네이버증권API 활용 - json에서 값 찾기 (4) | 2024.03.18 |