Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
PyQQQ SDK
PyQQQ SDK
  • 빠른 시작
    • 준비 및 설치하기
    • 증권사
      • 한국투자증권
      • LS(구 이베스트투자)증권
    • 튜토리얼 시작하기
      • 주식시장 일정 조회하기
      • 삼성전자 시가총액 조회하기
      • OHLCV 데이터 조회하기
      • Broker API 호출하기
  • 사용자 가이드
    • PyQQQ CLI 사용하기
    • 배포된 전략 관리하기
    • KV 저장소 활용하기
    • API 키를 서버에 저장하고 사용하기
    • 거래내역 조회하기
    • 모의투자로 배우는 전략
      • 5분, 15분 이평선을 이용한 모의투자 (한투)
      • 간단한 모멘텀 전략 모의투자 (LS)
    • 백테스트로 전략 평가하기
    • NXT 거래소 이용하기
    • .qignore 파일로 배포 제외 규칙 설정하기
    • 고급 Hook 활용하기
    • Retry 설정으로 재시도 동작 제어하기
  • API 레퍼런스
    • API key
      • get_api_key
      • set_api_key
    • 증권사 (Brokerage)
      • pyqqq.brokerage.ebest.oauth
        • EBestAuth
        • host_url
        • websocket_url
        • get_token
        • issue_access_token
      • pyqqq.brokerage.ebest.domestic_stock
        • EBestDomesticStock
        • get_asset_list
        • get_price
        • get_stock_time_conclude
        • get_stock_minute_prices
        • get_stock_tick_data_today_yesterday
        • get_stock_chart_dwmy
        • get_stock_chart_minutes
        • get_account_deposit_orderable_total_evaluation
        • get_account_orderable_quantity
        • get_stock_balance
        • get_deposit_order_list
        • get_order_list
        • create_order
        • update_order
        • cancel_order
        • get_management_stocks
        • get_alert_stocks
        • listen_trade_event
        • listen_after_market_single_price_trade_event
        • listen_orderbook_event
        • listen_order_event
      • pyqqq.brokerage.ebest.simple
        • EBestSimpleDomesticStock
          • EBestSimpleDomesticStock
          • get_account
          • get_possible_quantity
          • get_positions
          • get_historical_daily_data
          • get_today_minute_data
          • get_price
          • get_price_for_multiple_stock
          • create_order
          • update_order
          • cancel_order
          • get_pending_orders
          • get_today_order_history
          • get_tick_data
          • listen_order_event
        • EBestStockOrder
          • EBestStockOrder
          • order_no
          • asset_code
          • side
          • quantity
          • price
          • filled_quantity
          • filled_price
          • pending_quantity
          • order_time
          • current_price
          • is_pending
          • org_order_no
          • order_type
          • req_type
        • EBestStockPosition
          • EBestStockPosition
          • asset_code
          • asset_name
          • quantity
          • average_purchase_price
          • current_price
          • current_value
          • current_pnl
          • current_pnl_value
      • pyqqq.brokerage.kis.oauth
        • KISAuth
        • host_url
        • get_token
        • issue_access_token
      • pyqqq.brokerage.kis.domestic_stock
        • KISDomesticStock
        • get_price
        • inquire_ccnl
        • inquire_daily_price
        • inquire_asking_price_exp_ccn
        • inquire_daily_itemchartprice
        • inquire_daily_indexchartprice
        • inquire_time_itemconclusion
        • inquire_time_overtimeconclusion
        • inquire_daily_overtimeprice
        • inquire_time_itemchartprice
        • inquire_time_indexchartprice
        • inquire_time_dailychartprice
        • inquire_price_2
        • inquire_daily_trade_volume
        • inquire_index_price
        • inquire_index_daily_price
        • inquire_index_category_price
        • search_info
        • search_stock_info
        • get_balance_sheet
        • get_financial_ratio
        • chk_holiday
        • get_foreign_institution_total
        • get_stock_condition_search_list
        • get_stock_condition_search_results
        • get_program_trade_by_stock
        • get_volume_rank
        • get_investor_trend_estimate
        • get_income_statement
        • get_dividend_schedule
        • order_cash
        • order_rvsecncl
        • inquire_psbl_rvsecncl
        • inquire_daily_ccld
        • inquire_balance
        • inquire_psbl_order
        • inquire_balance_rlz_pl
        • inquire_credit_psamount
        • inquire_account_balance
        • inquire_period_trade_profit
        • inquire_period_profit
        • nav_comparison_daily_trend
        • listen_order_event
      • pyqqq.brokerage.kis.overseas_stock
        • KISOverseasStock
        • get_price
        • get_dailyprice
        • inquire_daily_chartprice
        • inquire_search
        • get_price_detail
        • inquire_time_itemchartprice
        • inquire_time_indexchartprice
        • order
        • order_rvsecncl
        • order_resv
        • order_resv_ccnl
        • inquire_nccs
        • inquire_balance
        • inquire_ccnl
        • inquire_psamount
        • inquire_period_profit
        • inquire_asking_price
      • pyqqq.brokerage.kis.simple
        • KISSimpleDomesticStock
          • KISSimpleDomesticStock
          • get_account
          • get_possible_quantity
          • get_positions
          • get_historical_daily_data
          • get_today_minute_data
          • get_price
          • get_price_for_multiple_stock
          • get_orderbook
          • create_order
          • update_order
          • cancel_order
          • get_pending_orders
          • get_today_order_history
          • get_order
          • listen_order_event
        • KISStockOrder
          • KISStockOrder
          • order_no
          • asset_code
          • side
          • quantity
          • price
          • filled_quantity
          • filled_price
          • pending_quantity
          • order_time
          • current_price
          • is_pending
          • org_order_no
          • order_type
          • req_type
        • KISStockPosition
          • KISStockPosition
          • asset_code
          • asset_name
          • quantity
          • average_purchase_price
          • current_price
          • current_value
          • current_pnl
          • current_pnl_value
      • pyqqq.brokerage.kis.simple_overseas
        • KISSimpleOverseasStock
        • get_account
        • get_possible_quantity
        • get_positions
        • get_historical_daily_data
        • get_today_minute_data
        • get_price
        • create_order
        • update_order
        • cancel_order
        • daytime_order
        • daytime_update_order
        • daytime_cancel_order
        • schedule_order
        • cancel_scheduled_order
        • get_scheduled_orders
        • get_pending_orders
        • get_today_order_history
        • get_order_history
        • get_orderbook
      • pyqqq.brokerage.tracker
        • TradingTracker
        • positions
        • pending_orders
        • task
        • on_pending_order_update
        • on_position_update
        • start
        • stop
      • pyqqq.brokerage.helper
        • PyQQQAutoConnectionSingleton
        • _instance
        • _initialized
    • 시장 데이터 (Data)
      • pyqqq.data.realtime
        • get_all_last_trades
        • get_all_last_stock_quotes
      • pyqqq.data.ticks
        • get_tick_data
      • pyqqq.data.minutes
        • get_all_minute_data
        • get_all_day_data
        • get_orderbook
      • pyqqq.data.daily
        • get_all_ohlcv_for_date
        • get_ohlcv_by_codes_for_period
      • pyqqq.data.domestic
        • get_alert_stocks
        • get_management_stocks
        • get_rising_stocks
        • get_tickers
        • get_ticker_info
        • find_ticker_info
        • get_administrative_stocks
        • get_invest_alert_stocks
        • get_overheat_stocks
        • get_market_cap
        • get_market_cap_by_codes
        • get_investor_net_purchases
      • pyqqq.data.index
        • get_index_ohlcv_for_date
        • get_ohlcv_by_indices_for_period
      • pyqqq.data.us_stocks
        • get_ticker_info
        • get_ohlcv_by_codes_for_period
        • get_all_ohlcv_for_date
        • get_all_day_data
        • get_all_minute_data
    • 유틸리티 (Utils)
      • pyqqq.utils.array
        • chunk
      • pyqqq.utils.compute
        • quantize_krx_price
        • get_krx_tick_size
      • pyqqq.utils.kvstore
        • KVStore
        • get
        • set
        • delete
        • keys
        • clear
      • pyqqq.utils.limiter
        • CallLimiter
        • wait_limit_rate
        • limit_calls
      • pyqqq.utils.logger
        • get_logger
      • pyqqq.utils.market_schedule
        • MarketSchedule
        • full_day_closed
        • exchange
        • open_time
        • close_time
        • reason
        • is_full_day_closed
        • is_before_opening
        • is_after_closing
        • is_trading_time
        • get_market_schedule
        • get_last_trading_day
        • get_next_trading_day
        • get_trading_day_with_offset
      • pyqqq.utils.retry
        • RetryConfig
        • configure_retry
        • reset_retry_config
        • retry
      • pyqqq.utils.singleton
        • singleton
      • pyqqq.utils.position_classifier
        • PositionClassifier
        • set_initial_position
        • set_initial_order
        • update_positions
        • update_orders
        • clear_orders
        • get_sellable_quantity_by_auto
        • tagging_order_auto
        • print_current_status
        • start
    • 데이터 타입 (Data types)
      • OrderSide
      • OrderType
      • OrderRequestType
      • TransactionStatus
      • StockPosition
      • StockOrder
      • OrderEvent
      • TradingHistory
    • Backtest
      • pyqqq.backtest.environment
        • TradingEnvironment
          • TradingEnvironment
          • get_broker
          • get_clock
        • BacktestEnvironment
          • __init__
          • get_broker
          • get_clock
        • KISDomesticEnvironment
          • __init__
          • get_broker
          • get_clock
        • KISOverseasEnvironment
          • __init__
          • get_broker
          • get_clock
      • pyqqq.backtest.broker
        • BaseBroker
          • BaseBroker
          • get_account
          • get_minute_price
          • get_price
          • get_daily_price
          • get_pending_orders
          • get_positions
          • create_order
          • update_order
          • cancel_order
        • TradingBroker
          • TradingBroker
          • data_api
          • trading_api
          • get_minute_price
          • get_price
          • get_daily_price
          • get_orderbook
          • get_account
          • get_pending_orders
          • get_positions
          • create_order
          • update_order
          • cancel_order
        • MockBroker
          • MockBroker
          • clock
          • cash
          • trading_history
          • position_provider
          • time_unit
          • set_initial_cash
          • get_daily_price
          • get_minute_price
          • get_price
          • get_pending_orders
          • get_positions
          • create_order
          • update_order
          • cancel_order
          • show_trading_history_report
          • show_positions
      • pyqqq.backtest.positionprovider
        • BasePositionProvider
          • BasePositionProvider
          • get_positions
        • KISPositionProvider
          • KISPositionProvider
          • get_positions
        • EBestPositionProvider
          • EBestPositionProvider
          • get_positions
        • ManualPositionProvider
          • ManualPositionProvider
          • get_positions
        • BackPositionProvider
          • BackPositionProvider
          • get_positions
      • pyqqq.backtest.strategy
        • BaseStrategy
          • BaseStrategy
          • clock
          • broker
          • logger
          • run
      • pyqqq.backtest.wallclock
        • WallClock
          • WallClock
          • live_mode
          • tzinfo
          • on_time_change
          • on_before_time_change
          • now
          • today
          • is_alive
          • sleep
      • pyqqq.backtest.utils
        • print_invest_result
Back to top
View this page

print_invest_result¶

pyqqq.backtest.utils.print_invest_result(dataframe, initial_cash, risk_free_rate=0.02, save_csv=False, csv_path='invest_result.csv')[source]¶

투자 성과를 분석하고 주요 성과 지표를 계산하여 출력합니다.

이 함수는 일별 거래 데이터를 기반으로 CAGR, Sharpe Ratio, Maximum Drawdown 등의 주요 투자 성과 지표를 계산합니다. 휴장일은 자동으로 제외되며, 모든 지표는 연율화(252 거래일 기준)하여 계산됩니다.

Parameters:
  • dataframe (pandas.DataFrame) –

    일별 거래 결과가 담긴 데이터프레임

    • earn_money: 일별 수익 (매매 후 현금 + 보유 주식 가치 기준)

    • account_value: 일별 계좌 가치 없는 경우 earn_money와 initial_cash로 자동 계산

    • datetime.date 타입의 거래일

  • initial_cash (float) – 초기 투자 금액

  • risk_free_rate (float, optional) – 무위험 수익률(연율). Defaults to 0.02 (2%). Sharpe Ratio 계산에 사용됩니다.

  • save_csv (bool, optional) – 분석 결과를 CSV 파일로 저장할지 여부. Defaults to False.

  • csv_path (str, optional) – CSV 파일 저장 경로. Defaults to “invest_result.csv”.

Prints:

다음 성과 지표들을 계산하여 출력합니다:

  1. CAGR (Compound Annual Growth Rate)
    • 연평균 성장률

    • (최종가치/초기가치)^(252/투자일수) - 1

  2. Sharpe Ratio
    • 무위험 수익률 대비 위험 조정 수익률

    • (초과수익률 평균/초과수익률 표준편차) * sqrt(252)

  3. Maximum Drawdown
    • 고점 대비 최대 하락폭

    • max(1 - 현재가치/누적최대가치)

Example:

import pandas as pd
import datetime as dtm

# 일별 거래 결과 데이터 준비
data = {
    'earn_money': [1000, 2000, -500, 1500],
    'account_value': [101000, 103000, 102500, 104000]
}
dates = [
    dtm.date(2023, 1, 2),
    dtm.date(2023, 1, 3),
    dtm.date(2023, 1, 4),
    dtm.date(2023, 1, 5)
]
df = pd.DataFrame(data, index=dates)

# 성과 분석 실행
print_invest_result(
    dataframe=df,
    initial_cash=100000,
    risk_free_rate=0.02,
    save_csv=True,
    csv_path="trading_results.csv"
)

Notes

  • 휴장일은 자동으로 제외됩니다 (is_full_day_closed 함수 사용)

  • 모든 수익률 지표는 252 거래일 기준으로 연율화됩니다

  • account_value가 제공되지 않은 경우, earn_money의 누적합과 initial_cash를 사용하여 자동 계산됩니다

  • 일별 수익률은 earn_money/account_value로 계산됩니다

  • 무위험 수익률은 일별로 환산되어 계산에 사용됩니다

Raises:

KeyError – dataframe에 필수 컬럼 ‘earn_money’가 없는 경우

Previous
pyqqq.backtest.utils
Copyright © 2025, Mylos & Mintmobile Inc
Made with Sphinx and @pradyunsg's Furo
On this page
  • print_invest_result
    • print_invest_result()