ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 코스피와 환율 그래프(python3)
    카테고리 없음 2023. 8. 19. 13:55

    chatgpt가 짜준 소스코드

    import yfinance as yf
    import datetime
    import matplotlib.pyplot as plt
    
    start = datetime.datetime(2004, 1, 1)
    end = datetime.datetime.now()  # 현재 날짜로 업데이트
    
    # Fetch KOSPI index data
    kospi_data = yf.download("^KS11", start=start, end=end)
    
    # Fetch exchange rate data (USD/KRW)
    exchange_rate_data = yf.download("USDKRW=X", start=start, end=end)
    
    # Create a figure and a grid of subplots with adjusted figsize
    fig, ax1 = plt.subplots(figsize=(15, 5))  # 3배 크기 조정 (기본 크기는 (6.4, 4.8) 입니다.)
    
    # Plot KOSPI index on the left y-axis
    kospi_chart = ax1.plot(kospi_data['Close'], color='b', label='KOSPI Index')
    ax1.set_ylabel("KOSPI Index")
    ax1.yaxis.label.set_color('b')
    
    # Create a second y-axis for exchange rate on the right
    ax2 = ax1.twinx()
    exchange_rate_chart = ax2.plot(exchange_rate_data['Close'], color='r', label='USD/KRW Exchange Rate')
    ax2.set_ylabel("Exchange Rate (USD per KRW)")
    ax2.yaxis.label.set_color('r')
    
    # Combine the legends for both axes
    lines = kospi_chart + exchange_rate_chart
    labels = [line.get_label() for line in lines]
    ax1.legend(lines, labels, loc="upper left")
    
    # Print KOSPI data
    print("KOSPI Data:")
    print(kospi_data)
    print("KOSPI Close Median:", kospi_data['Close'].median())
    print(kospi_data['Close'].describe())
    print(kospi_data.corr())
    
    # Print exchange rate data
    print("\nExchange Rate Data:")
    print(exchange_rate_data)
    print("Exchange Rate Median:", exchange_rate_data['Close'].median())
    print(exchange_rate_data['Close'].describe())
    print(exchange_rate_data.corr())
    
    # Initialize the horizontal line for the mouse pointer
    horizontal_line = ax1.axhline(y=0, color='gray', linestyle='--', visible=False)
    
    # Offset for the horizontal line
    y_offset = 0.02 * (kospi_data['Close'].max() - kospi_data['Close'].min())
    
    # Function to update horizontal line
    def update_line(event):
        if not event.inaxes:
            horizontal_line.set_visible(False)
            fig.canvas.draw()
            return
    
        y = event.ydata
        horizontal_line.set_ydata([y, y])  # 시퀀스로 변경
        horizontal_line.set_visible(True)
        fig.canvas.draw()
    
    
    # Connect the update_line function to the figure's motion_notify_event
    fig.canvas.mpl_connect('motion_notify_event', update_line)
    
    plt.title("KOSPI Index and USD/KRW Exchange Rate")
    plt.xlabel("Date")
    
    plt.show()

     

Designed by Tistory.