Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ดึงอัตราแลกเปลี่ยนเงินตรา Real-time ด้วย Python


บทนำ

Python เหมาะสำหรับเรียก API ดึงอัตราแลกเปลี่ยน จะใช้ไลบรารี forex-python หรือ REST API โดยตรง

1. ใช้ forex-python (ง่ายที่สุด)

pip install forex-python

from forex_python.converter import CurrencyRates
c = CurrencyRates()

# อัตราล่าสุด
rate = c.get_rate('USD', 'THB')
print(f"1 USD = {rate} THB")

# อัตราในอดีต
import datetime
dt = datetime.datetime(2023, 1, 15)
historical = c.get_rate('USD', 'THB', dt)
print(f"Rate on 2023-01-15: {historical}")

2. ใช้ ExchangeRate-API (REST API)

import requests

# ต้องสมัคร API key ฟรีที่ exchangerate-api.com
API_KEY = "your_api_key"
url = f"https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD"

response = requests.get(url)
data = response.json()

if data['result'] == 'success':
    rates = data['conversion_rates']
    print(f"USD to THB: {rates['THB']}")
    print(f"USD to EUR: {rates['EUR']}")

3. ใช้ API อื่นๆ (Alpha Vantage, Fixer.io, ฯลฯ)

หลายบริการมี Free tier สำหรับการทดสอบ ควรตรวจสอบ rate limit และข้อมูลที่รองรับ

ข้อควรพิจารณา

  • forex-python: ใช้งานง่าย ออฟไลน์ได้ (มีข้อมูลเก่าในตัว) แต่อาจไม่ใช่ real-time จริง
  • REST API: ข้อมูล real-time จริง ต้องมีอินเทอร์เน็ตและ API key
  • ควร implement caching เพื่อลด API calls