{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4cd3ab08",
   "metadata": {
    "papermill": {
     "duration": 0.001876,
     "end_time": "2026-10-29T21:45:32.161652+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:32.159776+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "# S&P500 52주 신고가 종목 (업종별)\n",
    "한경 페이지에서 S&P500 구성종목을 동적 수집 → 52주 신고가 종목을 찾아 **업종별로 분류**한다.\n",
    "\n",
    "- 원본 Colab 스크립트를 로컬 이식하며 **일괄(batch) 다운로드**로 최적화 (수백 번 개별 호출 → 1~2회)\n",
    "- 번역(googletrans)은 선택: 미설치 시 자동으로 영문 사업요약 사용\n",
    "- 소스: https://www.hankyung.com/globalmarket/usa-stock-sp500"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b15a0e7c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:45:32.165325Z",
     "iopub.status.busy": "2026-10-29T21:45:32.165115Z",
     "iopub.status.idle": "2026-10-29T21:45:32.171191Z",
     "shell.execute_reply": "2026-10-29T21:45:32.170467Z"
    },
    "papermill": {
     "duration": 0.009135,
     "end_time": "2026-10-29T21:45:32.172141+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:32.163006+00:00",
     "status": "completed"
    },
    "tags": [
     "parameters"
    ]
   },
   "outputs": [],
   "source": [
    "# ── 파라미터 ──\n",
    "do_translate = False   # True로 하면 googletrans로 사업요약 한글 번역 시도 (미설치 시 자동 skip)\n",
    "max_tickers = 0        # 0 = 전체, 그 외 숫자면 후보 상위 N개만 (속도 제한용)\n",
    "high_tolerance = 0.005 # 현재가가 52주 최고가의 (1-이값) 이상이면 '신고가권'으로 인정\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dff3b9cc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:45:32.175868Z",
     "iopub.status.busy": "2026-10-29T21:45:32.175673Z",
     "iopub.status.idle": "2026-10-29T21:45:32.614954Z",
     "shell.execute_reply": "2026-10-29T21:45:32.614358Z"
    },
    "papermill": {
     "duration": 0.442405,
     "end_time": "2026-10-29T21:45:32.615914+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:32.173509+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import yfinance as yf\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import re, time, logging, requests\n",
    "from bs4 import BeautifulSoup\n",
    "from IPython.display import display\n",
    "logging.getLogger('yfinance').setLevel(logging.CRITICAL)\n",
    "logging.getLogger('urllib3').setLevel(logging.CRITICAL)\n",
    "\n",
    "# googletrans 는 선택 의존성 — 없으면 번역 없이 진행\n",
    "translator = None\n",
    "if do_translate:\n",
    "    try:\n",
    "        from googletrans import Translator\n",
    "        translator = Translator()\n",
    "    except Exception as e:\n",
    "        print(f'googletrans 사용 불가 ({e}) → 영문 요약 사용')\n",
    "        translator = None\n",
    "\n",
    "HK_URL = 'https://www.hankyung.com/globalmarket/usa-stock-sp500'\n",
    "HEADERS = {'User-Agent': 'Mozilla/5.0 (compatible; LocalScraper/1.0)'}\n",
    "BLACKLIST = {'USA','US','USD','S','P','SP','SNP','CPI','PPI','EPS','PE','YOY','QOQ',\n",
    "             'ETF','AI','EV','GDP','FOMC','FED','ECB','BOJ','SEC','IRS','NY','EU',\n",
    "             'BOOK','POLL','MAP','TESAT','AT','DR','WR','SBA','CH','JM','AO','JB','BF','RSS'}\n",
    "\n",
    "def clean_to_yahoo_symbol(sym):\n",
    "    s = sym.strip().upper().replace('.', '-')\n",
    "    return {'BRK.B':'BRK-B','BF.B':'BF-B'}.get(sym.upper(), s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "54770357",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:45:32.618488Z",
     "iopub.status.busy": "2026-10-29T21:45:32.618296Z",
     "iopub.status.idle": "2026-10-29T21:45:33.087893Z",
     "shell.execute_reply": "2026-10-29T21:45:33.087250Z"
    },
    "papermill": {
     "duration": 0.471712,
     "end_time": "2026-10-29T21:45:33.088652+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:32.616940+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "한경 S&P500 페이지에서 티커 수집 중...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "후보 티커 수: 482 (예시: ['TV', 'NVDA', 'AAPL', 'MSFT', 'A', 'GOOGL', 'C', 'GOOG', 'AMZN', 'AVGO', 'META', 'TSLA'])\n"
     ]
    }
   ],
   "source": [
    "def scrape_candidates(url):\n",
    "    html = requests.get(url, headers=HEADERS, timeout=30).text\n",
    "    soup = BeautifulSoup(html, 'lxml')\n",
    "    cands = []\n",
    "    has_hangul = re.compile(r'[가-힣]')\n",
    "    pat_paren = re.compile(r'\\(([A-Z]{1,6}(?:-[A-Z]{1,2})?)\\)')\n",
    "    for node in soup.find_all(string=True):\n",
    "        txt = str(node)\n",
    "        if has_hangul.search(txt):\n",
    "            for m in pat_paren.finditer(txt):\n",
    "                cands.append(m.group(1))\n",
    "    ticker_pat = re.compile(r'\\b[A-Z]{1,5}(?:-[A-Z]{1,2})?\\b')\n",
    "    for a in soup.find_all('a'):\n",
    "        text = a.get_text(' ', strip=True)\n",
    "        if text and len(text) <= 300 and has_hangul.search(text):\n",
    "            for c in ticker_pat.findall(text):\n",
    "                if c not in BLACKLIST:\n",
    "                    cands.append(c)\n",
    "    cleaned = []\n",
    "    for t in (clean_to_yahoo_symbol(x) for x in cands):\n",
    "        if 1 <= len(t) <= 6 and re.fullmatch(r'[A-Z\\-]+', t) and t not in cleaned:\n",
    "            cleaned.append(t)\n",
    "    return cleaned\n",
    "\n",
    "try:\n",
    "    print('한경 S&P500 페이지에서 티커 수집 중...')\n",
    "    candidates = scrape_candidates(HK_URL)\n",
    "except Exception as e:\n",
    "    print(f'스크래핑 실패: {e}')\n",
    "    candidates = []\n",
    "if max_tickers and max_tickers > 0:\n",
    "    candidates = candidates[:max_tickers]\n",
    "print(f'후보 티커 수: {len(candidates)} (예시: {candidates[:12]})')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c0cb3393",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:45:33.091233Z",
     "iopub.status.busy": "2026-10-29T21:45:33.091116Z",
     "iopub.status.idle": "2026-10-29T21:45:56.290776Z",
     "shell.execute_reply": "2026-10-29T21:45:56.290391Z"
    },
    "papermill": {
     "duration": 23.201748,
     "end_time": "2026-10-29T21:45:56.291423+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:33.089675+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "52주 신고가권 종목: 37개 → ['A', 'AAPL', 'ABBV', 'ALLE', 'AMGN', 'BBY', 'CB', 'CRL', 'DGX', 'EMR', 'FAST', 'FTV', 'GILD', 'HAS', 'HST', 'IEX', 'JCI', 'KDP', 'LH', 'LLY', 'MA', 'MO', 'MSI', 'MTD', 'NDAQ', 'NUE', 'PM', 'RVTY', 'SWK', 'TECH', 'TMO', 'TRGP', 'URI', 'VTRS', 'WAT', 'WSM', 'WST']\n"
     ]
    }
   ],
   "source": [
    "# ── 일괄 다운로드 후 52주 신고가 벡터 판정 (개별 호출 최소화) ──\n",
    "high_tickers = []\n",
    "if candidates:\n",
    "    raw = yf.download(candidates, period='1y', interval='1d',\n",
    "                      auto_adjust=False, progress=False)\n",
    "    close = raw['Close'] if isinstance(raw.columns, pd.MultiIndex) else raw[['Close']]\n",
    "    close = close.dropna(how='all')\n",
    "    for t in close.columns:\n",
    "        ser = close[t].dropna()\n",
    "        if ser.size < 20:\n",
    "            continue\n",
    "        if ser.iloc[-1] >= ser.max() * (1 - high_tolerance):\n",
    "            high_tickers.append(t)\n",
    "print(f'52주 신고가권 종목: {len(high_tickers)}개 → {high_tickers}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "53194b36",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:45:56.296119Z",
     "iopub.status.busy": "2026-10-29T21:45:56.296025Z",
     "iopub.status.idle": "2026-10-29T21:46:31.269246Z",
     "shell.execute_reply": "2026-10-29T21:46:31.268251Z"
    },
    "papermill": {
     "duration": 34.976362,
     "end_time": "2026-10-29T21:46:31.270875+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:45:56.294513+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def get_sector_and_profile(ticker):\n",
    "    sector, summary = 'Unknown', ''\n",
    "    try:\n",
    "        info = yf.Ticker(ticker).info\n",
    "        sector = info.get('sector', 'Unknown')\n",
    "        summary = info.get('longBusinessSummary', '') or ''\n",
    "    except Exception:\n",
    "        pass\n",
    "    if summary and translator is not None:\n",
    "        try:\n",
    "            summary = translator.translate(summary, src='en', dest='ko').text\n",
    "        except Exception:\n",
    "            pass\n",
    "    return sector, summary\n",
    "\n",
    "rows = []\n",
    "for t in high_tickers:\n",
    "    sector, summary = get_sector_and_profile(t)\n",
    "    rows.append({'Ticker': t, 'Sector': sector, 'Business Profile': summary})\n",
    "    time.sleep(0.3)\n",
    "high_df = pd.DataFrame(rows)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b37bc460",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:46:31.277182Z",
     "iopub.status.busy": "2026-10-29T21:46:31.277043Z",
     "iopub.status.idle": "2026-10-29T21:46:31.292467Z",
     "shell.execute_reply": "2026-10-29T21:46:31.291936Z"
    },
    "papermill": {
     "duration": 0.017659,
     "end_time": "2026-10-29T21:46:31.293105+00:00",
     "exception": false,
     "start_time": "2026-10-29T21:46:31.275446+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"high-report\"><div class=\"high-report__summary\"><div class=\"high-report__metric\"><span>S&amp;P500 52주 신고가권</span><strong>37</strong><small>종목</small></div><div class=\"high-report__metric\"><span>분포 업종</span><strong>9</strong><small>개</small></div><div class=\"high-report__metric\"><span>최다 업종</span><strong>Healthcare</strong><small>15종목</small></div></div><section><h2 class=\"high-report__section-title\">업종별 종목수</h2><div class=\"high-report__counts\"><div class=\"high-report__count-card\"><span>Healthcare</span><b>15</b></div><div class=\"high-report__count-card\"><span>Industrials</span><b>7</b></div><div class=\"high-report__count-card\"><span>Consumer Cyclical</span><b>3</b></div><div class=\"high-report__count-card\"><span>Consumer Defensive</span><b>3</b></div><div class=\"high-report__count-card\"><span>Financial Services</span><b>3</b></div><div class=\"high-report__count-card\"><span>Technology</span><b>3</b></div><div class=\"high-report__count-card\"><span>Basic Materials</span><b>1</b></div><div class=\"high-report__count-card\"><span>Energy</span><b>1</b></div><div class=\"high-report__count-card\"><span>Real Estate</span><b>1</b></div></div></section><section><h2 class=\"high-report__section-title\">업종별 상세</h2><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Healthcare</h3><span class=\"high-report__badge\">15종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">A</div><div class=\"high-report__profile\">Agilent Technologies, Inc. provides application focused solutions to the life sciences, diagnostics, and applied chemical markets worldwide. The company operates through three segments: Life Sciences and Diagnostics Markets, Agilent CrossLab, and Applied Markets. The Life Sciences and Diagnostics Markets segment offers liquid chromatography systems and components; and liquid chromatography mass spectrometry systems....</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">ABBV</div><div class=\"high-report__profile\">AbbVie Inc., a research-based biopharmaceutical company, engages in the research and development, manufacturing, commercializing, and sale of medicines and therapies worldwide. The company offers Skyrizi to treat autoimmune diseases; Rinvoq to treat inflammatory diseases; Imbruvica for the treatment of adult patients with blood cancers; Venclexta to treat blood cancers; Elahere to treat various cancer; and Epkinly to...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">AMGN</div><div class=\"high-report__profile\">Amgen Inc. discovers, develops, manufactures, and delivers human therapeutics worldwide. The company&#x27;s principal products include Enbrel for the treatment of rheumatoid arthritis, plaque psoriasis, and psoriatic arthritis; Otezla for the treatment of adult patients with plaque psoriasis, psoriatic arthritis, and oral ulcers associated with Behçet&#x27;s disease; Prolia to treat postmenopausal women with osteoporosis; XGEV...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">CRL</div><div class=\"high-report__profile\">Charles River Laboratories International, Inc. provides drug discovery, non-clinical development, and safety testing services in the United States, Europe, Canada, the Asia Pacific, and internationally. The Research Models and Services segment produces and sells rodents, and purpose-bred rats and mice for use by researchers. This segment also provides a range of services to assist its clients in supporting the use of...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">DGX</div><div class=\"high-report__profile\">Quest Diagnostics Incorporated provides diagnostic testing and services in the United States. The company develops and delivers diagnostic information services, such as routine, non-routine and advanced clinical testing, anatomic pathology testing, and other diagnostic information services. It also provides services under the Quest Diagnostics brand, as well as under the AmeriPath, Dermpath Diagnostics, ExamOne, and...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">GILD</div><div class=\"high-report__profile\">Gilead Sciences, Inc., a biopharmaceutical company, discovers, develops, and commercializes medicines in the areas of unmet medical need in the United States, Europe, and internationally. The company provides Biktarvy, Descovy, Genvoya, Odefsey, Sunlenca, Symtuza, and YeztugoFor the treatment of HIV-1 infection in patients. It also provides Epclusa, Livdelzi, and Vemlidy to treat chronic hepatitis C virus, primary bi...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">LH</div><div class=\"high-report__profile\">Labcorp Holdings Inc. provides laboratory services. It operates in Diagnostics Laboratories and Biopharma Laboratory Services segments. The company offers various tests, such as blood chemistry analyses, urinalyses, blood cell counts, thyroid tests, PAP tests, hemoglobin A1C, PSA, tests for sexually transmitted diseases, vitamin D testing, microbiology cultures and procedures, and alcohol and other substance abuse te...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">LLY</div><div class=\"high-report__profile\">Eli Lilly and Company discovers, develops, manufactures, and markets human pharmaceutical products in the United States, Europe, China, Japan, and internationally. The company offers cardiometabolic health products, including Basaglar, Humalog, Humalog Mix 75/25, Humalog U-100, Humalog U-200, Humalog Mix 50/50, insulin lispro, insulin lispro protamine, insulin lispro mix 75/25, Humulin, Humulin 70/30, Humulin N, Humu...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">MTD</div><div class=\"high-report__profile\">Mettler-Toledo International Inc. manufactures and supplies precision instruments and services in the Americas, Europe, Asia, and internationally. It operates through five segments: U.S. Operations, Swiss Operations, Western European Operations, Chinese Operations, and Other Operations. The company offers laboratory instruments, such as laboratory balances, liquid pipetting solutions, real-time analytics, titrators,...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">RVTY</div><div class=\"high-report__profile\">Revvity, Inc. provides health sciences solutions, technologies, and services. The company offers instruments, reagents, software, subscriptions, detection and imaging technologies, extended warranties, and training and services; and instruments, reagents, and assay platforms and software products for early detection of common and rare conditions, such as pregnancy and early childhood, as well as infectious disease te...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">TECH</div><div class=\"high-report__profile\">Bio-Techne Corporation, together with its subsidiaries, develops, manufactures, and sells life science reagents, instruments, and services for the research, diagnostics, and bioprocessing markets worldwide. It operates through two segments, Protein Sciences, and Diagnostics and Spatial Biology. The Protein Sciences segment develops and manufactures biological reagents used in various aspects of life science research,...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">TMO</div><div class=\"high-report__profile\">Thermo Fisher Scientific Inc. provides life sciences solutions, analytical instruments, specialty diagnostics, and laboratory products and biopharma services internationally. It operates through four segments: Life Sciences Solutions, Analytical Instruments, Specialty Diagnostics, and Laboratory Products and Biopharma Services. The Life Sciences Solutions segment includes reagents, instruments, and consumables for bi...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">VTRS</div><div class=\"high-report__profile\">Viatris Inc., together with its subsidiaries, operates as a healthcare company in North America, Europe, China, Taiwan, Hong Kong, Japan, Australia, New Zealand, rest of Asia, Africa, Latin America, and the Middle East. It operates in four segments: Developed Markets, Greater China, JANZ, and Emerging Markets. The company offers prescription brand drugs, generic drugs, complex generic drugs, and biosimilars. It also...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">WAT</div><div class=\"high-report__profile\">Waters Corporation provides analytical workflow solutions in Asia, the Americas, and Europe. The company operates through two segments, Waters and TA. The company designs, manufactures, sells, and services liquid chromatography, as well as mass spectrometry (MS) technology systems and supports products, including chromatography columns, and other consumable products. It also designs, manufactures, sells, and services...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">WST</div><div class=\"high-report__profile\">West Pharmaceutical Services, Inc. designs, manufactures, and sells containment and delivery systems for injectable drugs and healthcare products in the Americas, Europe, the Middle East, Africa, and the Asia Pacific. It operates in two segments, Proprietary Products and Contract-Manufactured Products. The Proprietary Products segment offers stoppers and seals for injectable packaging systems; syringe and cartridge c...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Industrials</h3><span class=\"high-report__badge\">7종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">ALLE</div><div class=\"high-report__profile\">Allegion plc engages in the provision of security products and solutions worldwide. It is operating through two segments: Allegion Americas and Allegion International. The company offers door controls, door control system, and exit devices; doors, glass and door systems, and accessories; electronic security products and access control systems, including time, attendance, and workforce productivity; and locks, lockset...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">EMR</div><div class=\"high-report__profile\">Emerson Electric Co., a technology and software company, provides various solutions in the Americas, Asia, the Middle East, Africa, and Europe. It operates through Final Control, Measurement &amp; Analytical, Discrete Automation, Safety &amp; Productivity, Control Systems &amp; Software, and Test &amp; Measurement segments. The Final Control segment provides control valves, isolation valves, shutoff valves, pressure relief valves, p...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">FAST</div><div class=\"high-report__profile\">Fastenal Company, together with its subsidiaries, engages in the wholesale distribution of industrial and construction supplies in the United States, Canada, Mexico, and internationally. It offers fasteners, and related industrial and construction supplies under the Fastenal name. The company&#x27;s fastener products include threaded fasteners, bolts, nuts, screws, studs, and related washers that are used in manufactured...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">IEX</div><div class=\"high-report__profile\">IDEX Corporation, together with its subsidiaries, provides applied solutions in the United States, North America, Europe, Asia, and internationally. It operates through three segments: Health &amp; Science Technologies (HST), Fluid &amp; Metering Technologies (FMT) and Fire &amp; Safety/Diversified Products (FSDP). The HST segment designs, produces, and distributes a range of precision fluidics, positive displacement pumps, powd...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">JCI</div><div class=\"high-report__profile\">Johnson Controls International plc, together with its subsidiaries, engages in engineering, manufacturing, commissioning, and retrofitting building products and systems in the Americas, Europe, the Middle East, Africa, and the Asia-Pacific. The company designs, manufactures, sells, installs, and services heating, ventilating, air conditioning, controls, building management, refrigeration, integrated electronic securi...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">SWK</div><div class=\"high-report__profile\">Stanley Black &amp; Decker, Inc. provides hand tools, power tools, outdoor products, and related accessories in the United States, Canada, Other Americas, Europe, and Asia. Its Tools &amp; Outdoor segment offers professional grade corded and cordless electric power tools and equipment, including drills, impact wrenches and drivers, grinders, saws, routers, concrete prep and placement tools, and sanders; pneumatic tools and f...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">URI</div><div class=\"high-report__profile\">United Rentals, Inc., through its subsidiaries, operates as an equipment rental company in the United States, Canada, Europe, Australia, and New Zealand. It operates through two segments, General Rentals and Specialty. The General Rentals segment rents general construction and industrial equipment, such as backhoes, skid-steer loaders, forklifts, earthmoving equipment, and material handling equipment; aerial work pla...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Consumer Cyclical</h3><span class=\"high-report__badge\">3종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">BBY</div><div class=\"high-report__profile\">Best Buy Co., Inc. offers technology products and solutions in the United States, Canada, and internationally. The company provides computing and mobile phone products, such as desktops, notebooks, and peripherals; mobile phones comprising related mobile network carrier commissions; networking products; tablets covering e-readers; smartwatches; and consumer electronics consisting of digital imaging, health and fitnes...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">HAS</div><div class=\"high-report__profile\">Hasbro, Inc. operates as a toy and game company in the United States, Europe, Canada, Mexico, Latin America, Australia, China, and Hong Kong. The company offers trading cards and collectibles, action figures, arts and crafts and creative play products, dolls, play sets, preschool toys, plush products, vehicles and toy-related specialty products, sports action products and accessories, and other consumer products; and...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">WSM</div><div class=\"high-report__profile\">Williams-Sonoma, Inc. operates as an omni-channel specialty retailer of various products for home the United States and internationally. The company provides cooking, dining, and entertaining products, such as cookware, tools, electrics, cutlery, tabletop and bar, outdoor, furniture, and a library of cookbooks. It offers home furnishings, home decor products and accessories, bedding, lighting, rugs, table essentials,...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Consumer Defensive</h3><span class=\"high-report__badge\">3종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">KDP</div><div class=\"high-report__profile\">Keurig Dr Pepper Inc. owns, manufactures, and distributors beverages and single serve brewing systems in the United States and internationally. The company operates through three segments: U.S. Refreshment Beverages, U.S. Coffee, and International. It manufactures and distributes branded concentrates, syrup, and finished beverages, as well as sales of owned brands and third-party brands; tea, cocoa, and other product...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">MO</div><div class=\"high-report__profile\">Altria Group, Inc., through its subsidiaries, manufactures and sells smokeable and oral tobacco products in the United States. It offers cigarettes primarily under the Marlboro brand; large cigars and pipe tobacco under the Black &amp; Mild brand; moist smokeless tobacco and oral tobacco products under the Copenhagen, Skoal, Red Seal, and Husky brands; oral nicotine pouches under the on! brand; and e-vapor products under...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">PM</div><div class=\"high-report__profile\">Philip Morris International Inc. operates as a tobacco company. The company offers cigarettes and smoke-free products, including heat-not-burn, e-vapor, and oral nicotine products under the IQOS, VEEV, and ZYN brands; and consumer accessories, such as lighters and matches. It also offers wellness products. The company was incorporated in 1987 and is headquartered in Stamford, Connecticut.</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Financial Services</h3><span class=\"high-report__badge\">3종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">CB</div><div class=\"high-report__profile\">Chubb Limited provides insurance and reinsurance products worldwide. It operates in six segments: North America Commercial Property and Casualty (P&amp;C) Insurance, North America Personal P&amp;C Insurance, North America Agricultural Insurance, Overseas General Insurance, Global Reinsurance, and Life Insurance. The company offers property and general liability, workers&#x27; compensation, and umbrella; professional and managemen...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">MA</div><div class=\"high-report__profile\">Mastercard Incorporated, a technology company, provides transaction processing and other payment-related products and services in the United States and internationally. The company offers products and services for account holders, merchants, financial institutions, digital partners, businesses, governments, and other organizations, such as programs that enable issuers to provide consumers with credits to defer paymen...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">NDAQ</div><div class=\"high-report__profile\">Nasdaq, Inc. operates as a technology company that serves capital markets and other industries in the United States and internationally. It operates through three segments: Capital Access Platforms, Financial Technology, and Market Services. The company distributes historical and real-time market data; develops and licenses Nasdaq-branded indices and financial products; provides investor relations intelligence, gover...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Technology</h3><span class=\"high-report__badge\">3종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">AAPL</div><div class=\"high-report__profile\">Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple Vision Pro, Apple TV, Apple Watch, Beats products, and HomePod, as well as Apple branded and third-party ac...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">FTV</div><div class=\"high-report__profile\">Fortive Corporation designs, develops, manufactures, and markets products, software, and services in the United States, China, and internationally. It operates through Intelligent Operating Solutions and Advanced Healthcare Solutions segments. The Intelligent Operating Solutions segment provides advanced instrumentation, software, and services, including maintenance, repair, measurement and condition monitoring, faci...</div></div><div class=\"high-report__item\"><div class=\"high-report__ticker\">MSI</div><div class=\"high-report__profile\">Motorola Solutions, Inc. provides public safety, government, defense, and enterprise security solutions in the United States, the United Kingdom, Canada, and internationally. It operates in two segments, Products and Systems Integration, and Software and Services. The Products and Systems Integration segment offers a portfolio of infrastructure, devices, accessories, and the implementation and integration of systems,...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Basic Materials</h3><span class=\"high-report__badge\">1종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">NUE</div><div class=\"high-report__profile\">Nucor Corporation engages in the manufacture and sale of steel and steel products. The company operates in three segments: Steel Mills, Steel Products, and Raw Materials. The Steel Mills segment produces hot-rolled, cold-rolled, and galvanized sheet steel products; plate steel products; wide-flange beams, beam blanks, and H-piling and sheet piling structural steel products; and bar steel products, such as blooms, bil...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Energy</h3><span class=\"high-report__badge\">1종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">TRGP</div><div class=\"high-report__profile\">Targa Resources Corp., together with its subsidiaries, owns, operates, acquires, and develops a portfolio of complementary domestic infrastructure assets in North America. It operates in two segments, Gathering and Processing, and Logistics and Transportation. The company is involved in gathering, compressing, treating, processing, transporting, and selling natural gas; storing, fractionating, treating, transporting,...</div></div></div></section><section class=\"high-report__sector\"><div class=\"high-report__sector-head\"><h3>Real Estate</h3><span class=\"high-report__badge\">1종목</span></div><div class=\"high-report__items\"><div class=\"high-report__item\"><div class=\"high-report__ticker\">HST</div><div class=\"high-report__profile\">Host Hotels &amp; Resorts, Inc. is an S&amp;P 500 company and is the largest lodging real estate investment trust and one of the largest owners of luxury and upper-upscale hotels. The Company currently owns 70 properties in the United States and five properties internationally totaling approximately 41,300 rooms. The Company also holds non-controlling interests in seven domestic joint ventures. Guided by a disciplined approa...</div></div></div></section></section></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import HTML, display\n",
    "from html import escape\n",
    "\n",
    "\n",
    "def _short_profile(text, limit=420):\n",
    "    text = \" \".join(str(text or \"\").split())\n",
    "    if len(text) <= limit:\n",
    "        return text\n",
    "    return text[:limit].rstrip() + \"...\"\n",
    "\n",
    "\n",
    "def _render_high_report(high_df, market_name):\n",
    "    if high_df.empty:\n",
    "        return f\"\"\"\n",
    "        <div class=\"high-report high-report--empty\">\n",
    "            <div class=\"high-report__metric\">\n",
    "                <span>{escape(market_name)} 52주 신고가권</span>\n",
    "                <strong>0</strong><small>종목</small>\n",
    "            </div>\n",
    "        </div>\n",
    "        \"\"\"\n",
    "\n",
    "    work = high_df.copy()\n",
    "    work[\"Sector\"] = work[\"Sector\"].fillna(\"Unknown\").astype(str)\n",
    "    work[\"Ticker\"] = work[\"Ticker\"].fillna(\"\").astype(str)\n",
    "    work[\"Business Profile\"] = work[\"Business Profile\"].fillna(\"\").astype(str)\n",
    "    counts = work.groupby(\"Sector\").size().sort_values(ascending=False)\n",
    "    ordered_sectors = counts.index.tolist()\n",
    "\n",
    "    count_cards = []\n",
    "    for sector, count in counts.items():\n",
    "        count_cards.append(\n",
    "            f'<div class=\"high-report__count-card\"><span>{escape(sector)}</span><b>{int(count)}</b></div>'\n",
    "        )\n",
    "\n",
    "    sector_sections = []\n",
    "    for sector in ordered_sectors:\n",
    "        group = work[work[\"Sector\"] == sector].sort_values(\"Ticker\")\n",
    "        items = []\n",
    "        for _, row in group.iterrows():\n",
    "            profile = _short_profile(row.get(\"Business Profile\", \"\"))\n",
    "            if not profile:\n",
    "                profile = \"사업 내용 설명이 없습니다.\"\n",
    "            items.append(\n",
    "                '<div class=\"high-report__item\">'\n",
    "                f'<div class=\"high-report__ticker\">{escape(row[\"Ticker\"])}</div>'\n",
    "                f'<div class=\"high-report__profile\">{escape(profile)}</div>'\n",
    "                '</div>'\n",
    "            )\n",
    "        sector_sections.append(\n",
    "            '<section class=\"high-report__sector\">'\n",
    "            '<div class=\"high-report__sector-head\">'\n",
    "            f'<h3>{escape(sector)}</h3>'\n",
    "            f'<span class=\"high-report__badge\">{len(group)}종목</span>'\n",
    "            '</div>'\n",
    "            f'<div class=\"high-report__items\">{\"\".join(items)}</div>'\n",
    "            '</section>'\n",
    "        )\n",
    "\n",
    "    return (\n",
    "        '<div class=\"high-report\">'\n",
    "        '<div class=\"high-report__summary\">'\n",
    "        f'<div class=\"high-report__metric\"><span>{escape(market_name)} 52주 신고가권</span><strong>{len(work)}</strong><small>종목</small></div>'\n",
    "        f'<div class=\"high-report__metric\"><span>분포 업종</span><strong>{len(counts)}</strong><small>개</small></div>'\n",
    "        f'<div class=\"high-report__metric\"><span>최다 업종</span><strong>{escape(str(counts.index[0]))}</strong><small>{int(counts.iloc[0])}종목</small></div>'\n",
    "        '</div>'\n",
    "        '<section><h2 class=\"high-report__section-title\">업종별 종목수</h2>'\n",
    "        f'<div class=\"high-report__counts\">{\"\".join(count_cards)}</div></section>'\n",
    "        '<section><h2 class=\"high-report__section-title\">업종별 상세</h2>'\n",
    "        f'{\"\".join(sector_sections)}</section>'\n",
    "        '</div>'\n",
    "    )\n",
    "\n",
    "\n",
    "display(HTML(_render_high_report(high_df, \"S&P500\")))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.13"
  },
  "papermill": {
   "default_parameters": {},
   "duration": 60.228299,
   "end_time": "2026-10-29T21:46:31.509257+00:00",
   "environment_variables": {},
   "exception": null,
   "input_path": "/Users/seog-yejun/룬샤시_공시정리/태버지/12. S&P500 52주 신고가 업종별.ipynb",
   "output_path": "/Users/seog-yejun/룬샤시_공시정리/태버지/12. S&P500 52주 신고가 업종별.ipynb",
   "parameters": {},
   "start_time": "2026-10-29T21:45:31.280958+00:00",
   "version": "2.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}