Scriptone Scriptone

PyPI에 yfinance-pl을 공개했습니다

blog-image

개요

yfinance-pl을 PyPI에 공개했습니다. yfinance-rs를 래핑하여 Python에서 사용할 수 있도록 하고 타입 안전성을 강화한 주가 정보 취득 라이브러리입니다. 기존 yfinance와 달리 pd.DataFrame이 아닌 pl.DataFrame으로 데이터를 다룰 수 있습니다.

만든 이유

최근 Pandas의 대안으로 Polars를 사용할 기회가 있었고, 모던 라이브러리들이 Polars를 지원하면서 조금씩 보급되고 있습니다. Polars는 Rust로 만들어진 고성능 DataFrame 라이브러리로 Pandas보다 속도가 빠르고 메모리 소비가 적다는 등의 장점이 있습니다. 대량의 데이터 분석이나 Polars만으로 처리를 완결하는 데 있어서, 주식 분석의 입구인 yfinance가 순수하게 Polars를 지원하는 것이 원활한 분석과 뛰어난 개발자 경험 획득에 필요하다고 생각했습니다. Polars DataFrame인지 Pandas DataFrame인지 고민하지 않고 Polars로 분석하고 싶은 분들이 Polars만으로 분석할 수 있으면 좋겠다고 생각하여, yfinance-rs를 래핑하고 타입 안전성을 강화하여 yfinance-pl을 구현했습니다.

특징

yfinance 호환 API

yfinance와 동일한 API로 주가 데이터를 가져올 수 있습니다. 기존 yfinance를 사용한 코드를 최소한의 변경으로 마이그레이션할 수 있습니다.

import yfinance_pl as yf

ticker = yf.Ticker("AAPL")
history = ticker.history(period="1mo")

Rust 백엔드

yfinance-rs를 PyO3로 래핑하고 있어 데이터 취득 처리가 Rust로 실행됩니다.

타입 안전한 API

periodinterval 파라미터에는 Literal 타입을 사용하고 있어 IDE 자동 완성이 작동합니다.

# period에는 "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max" 지정 가능
# interval에는 "1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo" 지정 가능
history = ticker.history(period="1mo", interval="1d")

또한 TickerInfo, FastInfo, CalendarInfo 등의 반환값에는 TypedDict가 정의되어 있어 딕셔너리 키도 IDE에서 자동 완성됩니다.

yfinance와의 비교

항목yfinanceyfinance-pl
DataFrame 타입pd.DataFramepl.DataFrame
백엔드PythonRust (yfinance-rs)
Series 타입pd.Seriespl.DataFrame
타입 힌트부분적지원

지원 기능

yfinance-pl은 다음 기능을 지원합니다.

카테고리프로퍼티/메서드반환 타입
가격 이력history()pl.DataFrame
기업 정보info, fast_info, calendardict
배당·분할dividends, splits, actions, capital_gainspl.DataFrame
재무제표income_stmt, balance_sheet, cashflowpl.DataFrame
분기 재무quarterly_income_stmt, quarterly_balance_sheet, quarterly_cashflowpl.DataFrame
주주 정보major_holders, institutional_holders, mutualfund_holderspl.DataFrame
내부자insider_transactions, insider_roster_holderspl.DataFrame
애널리스트recommendations, upgrades_downgradespl.DataFrame
옵션options, option_chain()list[str], OptionChain

사용 예시

주가 이력 가져오기

import yfinance_pl as yf

ticker = yf.Ticker("AAPL")

# 최근 1개월 일별 데이터
history = ticker.history(period="1mo", interval="1d")
print(history)

출력 예시:

shape: (21, 7)
┌─────────────────────────┬────────────┬────────────┬────────────┬────────────┬──────────────┬───────────┐
│ date                    ┆ open       ┆ high       ┆ low        ┆ close      ┆ volume       ┆ dividends │
│ ---                     ┆ ---        ┆ ---        ┆ ---        ┆ ---        ┆ ---          ┆ ---       │
│ datetime[ns, UTC]       ┆ f64        ┆ f64        ┆ f64        ┆ f64        ┆ i64          ┆ f64       │
╞═════════════════════════╪════════════╪════════════╪════════════╪════════════╪══════════════╪═══════════╡
│ 2024-10-28 00:00:00 UTC ┆ 233.160004 ┆ 234.729996 ┆ 232.550003 ┆ 233.399994 ┆ 23819200     ┆ 0.0       │
│ ...                     ┆ ...        ┆ ...        ┆ ...        ┆ ...        ┆ ...          ┆ ...       │
└─────────────────────────┴────────────┴────────────┴────────────┴────────────┴──────────────┴───────────┘

재무제표 가져오기

# 손익계산서
income = ticker.income_stmt
print(income)

# 대차대조표
balance = ticker.balance_sheet
print(balance)

# 현금흐름표
cashflow = ticker.cashflow
print(cashflow)

옵션 체인 가져오기

# 사용 가능한 만기일 가져오기
dates = ticker.options
print(dates)

# 특정 만기일의 옵션 체인 가져오기
chain = ticker.option_chain("2024-12-20")
print(chain.calls)  # 콜 옵션
print(chain.puts)   # 풋 옵션

설치 방법

PyPI에 업로드되어 있으므로 pip로 설치 가능합니다. uv로도 물론 사용할 수 있습니다.

pip install yfinance-pl

또는:

uv add yfinance-pl

향후 업데이트

yfinance-rs의 업데이트에 맞춰 yfinance-pl도 업데이트할 예정입니다. Python 측에서도 타입 안전성 강화와 같이 사용하기 편해지는 업데이트가 있으면 구현해 나갈 것입니다.

링크

comment

댓글을 불러오는 중...