🧾 영웅문4 OpenAPI + Python 완전 정복 - 9단계: 자동 리포트 (Notion, Google Sheets, Telegram) 연동

반응형

OpenAPI + Python 완전 정복 - 9단계: 자동 리포트 (Notion, Google Sheets, Telegram) 연동

✅ 9단계 개요: 전략 기록 → 알림 → 리포트까지 자동화

자동매매가 끝나면 아래 작업이 필요합니다:

  • 결과를 기록한다
  • 외부에 전송한다 (Notion / Sheets / Telegram)
  • 공유/백업/분석/모니터링용 로그 자동화

✅ “자동매매 시스템의 뇌 + 입 + 손” 이 되는 확장 기능입니다.


📋 STEP 1. Google Sheets 자동 기록 연동

🔹 사전 준비

  1. 구글 서비스 계정 생성
  2. Google Sheets API 활성화 (다운로드)
  3. credentials.json 다운로드
  4. 공유 권한을 서비스 계정 메일에 부여

🔹 설치 및 코드 예시

bash

pip install gspread oauth2client
python

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
client = gspread.authorize(creds)

sheet = client.open("자동매매 결과").worksheet("전략기록")

def write_to_sheet(data: dict):
    sheet.append_row([
        data['date'], data['code'], data['strategy'],
        data['cum_return'], data['start_price'], data['end_price']
    ])

✅ 실행 예시:

python

write_to_sheet({
    "date": "2025-04-09",
    "code": "005930",
    "strategy": "MA 골든크로스",
    "cum_return": 12.3,
    "start_price": 78900,
    "end_price": 88900
})

📬 STEP 2. Telegram 자동 알림 전송

🔹 봇 생성

  1. @BotFather에게 메시지 → /newbot
  2. 봇 이름 & 토큰 받기
  3. @userinfobot로 채팅 ID 확인

🔹 메시지 전송 코드

python

import requests

def send_telegram_alert(message, bot_token, chat_id):
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    payload = {"chat_id": chat_id, "text": message}
    requests.post(url, data=payload)

📦 알림 예시:

python

send_telegram_alert("✅ 자동매매 완료\n종목: 삼성전자\n수익률: +12.3%", bot_token, chat_id)

🧾 STEP 3. Notion 자동 리포트 기록

🔹 사전 준비

  1. Notion Integration 생성 (다운로드)
  2. 데이터베이스 생성 후 공유 권한 부여
  3. NOTION_TOKEN, DATABASE_ID 확보

🔹 설치 및 코드 예시

bash

pip install notion-client
python

from notion_client import Client

notion = Client(auth="NOTION_TOKEN")

def write_to_notion(data: dict):
    notion.pages.create(
        parent={"database_id": "DATABASE_ID"},
        properties={
            "날짜": {"date": {"start": data['date']}},
            "종목": {"title": [{"text": {"content": data['code']}}]},
            "전략": {"rich_text": [{"text": {"content": data['strategy']}}]},
            "수익률": {"number": data['cum_return']}
        }
    )

📷 Notion에 자동 기록된 예시

lua

| 날짜       | 종목     | 전략         | 수익률  |
|------------|----------|--------------|---------|
| 2025-04-09 | 005930   | MA 골든크로스 | +12.3% |

🔁 STEP 4. 하나의 함수로 통합

python

def report_all(data):
    write_to_sheet(data)
    write_to_notion(data)
    send_telegram_alert(
        f"📊 자동매매 결과\n종목: {data['code']}\n전략: {data['strategy']}\n수익률: {data['cum_return']}%",
        bot_token="XXXX", chat_id="YYYY"
    )

✅ 전체 자동 리포트 구조 요약

📷 자동매매 보고서 연동 구조

플랫폼 목적 설명
Google Sheets 기록 및 백업 일자별 전략/수익률 저장
Telegram 실시간 알림 실시간 매매 결과 수신
Notion 대시보드화 전략 결과 정리 / 공유용 대시보드
반응형