[파이썬] 웹 프레임워크를 이용한 실시간 주가 정보 제공

주가 정보는 투자자에게 매우 중요하며, 실시간으로 주가 정보를 제공하는 웹 애플리케이션은 많은 사람들이 사용하고 있습니다. Python은 다양한 웹 프레임워크를 제공하므로, 실시간 주가 정보를 제공하는 웹 애플리케이션을 개발하기에 이상적인 언어입니다.

이 블로그 포스트에서는 Python과 Django 웹 프레임워크를 사용하여 실시간 주가 정보를 제공하는 간단한 예제를 소개하겠습니다.

필요한 패키지 설치

먼저, 실시간 주가 정보를 가져오기 위해 Alpha Vantage API를 사용합니다. 이를 위해 alpha_vantage 패키지를 설치해야 합니다.

pip install alpha_vantage

또한, Django 웹 프레임워크를 사용하기 위해 django 패키지도 설치해야 합니다.

pip install django

Django 프로젝트 생성

Django 프로젝트를 생성하기 위해 다음 명령을 실행합니다.

django-admin startproject stocks
cd stocks

Django 앱 생성

Django 앱을 생성하기 위해 다음 명령을 실행합니다.

python manage.py startapp stock_prices

이제 stock_prices 폴더 내에 views.py, urls.py, templates 폴더를 생성합니다.

주가 정보 가져오기

stock_prices/views.py 파일을 열고 다음 코드를 작성합니다.

from django.shortcuts import render
from alpha_vantage.timeseries import TimeSeries
import os

def get_stock_prices():
    # 알파베티지 API 키를 환경 변수에서 가져옵니다.
    api_key = os.environ.get('ALPHA_VANTAGE_API_KEY')
    
    # Alpha Vantage API를 사용하여 실시간 주가 정보를 가져옵니다.
    ts = TimeSeries(key=api_key, output_format='pandas')
    data, meta_data = ts.get_intraday(symbol='AAPL',interval='1min', outputsize='full')
    
    return data

def stock_prices(request):
    # 주가 정보를 가져옵니다.
    prices = get_stock_prices()
    
    # 템플릿에 주가 정보를 전달합니다.
    context = {'prices': prices}
    return render(request, 'stock_prices.html', context)

주가 정보를 가져오기 위해 get_stock_prices 함수를 정의하고, 이를 이용해 stock_prices 함수에서 views.py에서 실시간 주가 정보를 가져옵니다.

URL 설정

stock_prices/urls.py 파일을 열고 다음 코드를 작성합니다.

from django.urls import path
from . import views

urlpatterns = [
    path('stock_prices/', views.stock_prices, name='stock_prices'),
]

이제 stock_prices/urls.py 파일에서 urls.py 파일 루트로 URL을 설정하여 해당 주소에서 주가 정보를 볼 수 있도록 합니다.

템플릿 작성

stock_prices/templates/stock_prices.html 파일을 열고 다음 코드를 작성합니다.


<!DOCTYPE html>
<html>
<head>
    <title>Stock Prices</title>
</head>
<body>
    <h1>Real-time Stock Prices</h1>
    <table>
        <thead>
            <tr>
                <th>Timestamp</th>
                <th>Open</th>
                <th>High</th>
                <th>Low</th>
                <th>Close</th>
                <th>Volume</th>
            </tr>
        </thead>
        <tbody>
            {% for index, row in prices.iterrows %}
            <tr>
                <td>{{ index }}</td>
                <td>{{ row['1. open'] }}</td>
                <td>{{ row['2. high'] }}</td>
                <td>{{ row['3. low'] }}</td>
                <td>{{ row['4. close'] }}</td>
                <td>{{ row['5. volume'] }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

주가 정보를 표시하기 위한 간단한 HTML 템플릿을 작성합니다.

프로젝트 실행

이제 Django 서버를 실행하여 실시간 주가 정보를 제공하는 웹 애플리케이션을 확인할 수 있습니다. 터미널에서 다음 명령을 실행합니다.

python manage.py runserver

웹 브라우저에서 http://localhost:8000/stock_prices/로 접속하여 실시간 주가 정보를 확인할 수 있습니다.

결론

Python과 Django를 사용하여 실시간 주가 정보를 제공하는 웹 애플리케이션을 만들었습니다. 물론 이 예제는 간단한 예제이며, 더 복잡한 기능을 추가하거나 다른 데이터 소스와 연동할 수도 있습니다. Python과 Django를 사용하면 간단하게 실시간 주가 정보를 제공하는 웹 애플리케이션을 개발할 수 있습니다.