Skip to content

Instantly share code, notes, and snippets.

@Leon2xiaowu
Last active March 12, 2026 01:38
Show Gist options
  • Select an option

  • Save Leon2xiaowu/43cffb70ef004f523b69f6fa3993f7f4 to your computer and use it in GitHub Desktop.

Select an option

Save Leon2xiaowu/43cffb70ef004f523b69f6fa3993f7f4 to your computer and use it in GitHub Desktop.
自动更新港股通(深交所)的买入结算汇兑比率到Beancount
#!/usr/bin/env python3
import requests
import os
import random
def fetch_exchange_rate():
random_number = random.random()
# 获取深交所结算汇兑比率
url = f"https://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=SGT_LSHL&TABKEY=tab2&random={random_number}"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
for item in data:
if "metadata" in item and item["metadata"].get("name") == "结算汇兑比率":
return item["data"]
print("Error: Unable to fetch exchange rate data.")
exit(1)
except Exception as e:
print(f"Error: {e}")
exit(1)
def read_file_content(filepath):
if os.path.exists(filepath):
with open(filepath, "r") as file:
return file.readlines()
return []
def process_prices(data_lines, sxrq, currency, mrhl):
filtered_lines = []
for line in reversed(data_lines):
parts = line.split()
if len(parts) < 4:
continue
if sxrq <= parts[0] and currency == parts[-1]:
parts[3] = str(float(parts[3]) * mrhl)
parts[4] = "CNY"
filtered_lines.append(" ".join(parts))
if parts[0] < sxrq:
break
return filtered_lines
def write_to_file(filepath, lines):
with open(filepath, "w") as file:
for line in lines:
file.write(line + "\n")
def main():
# Step 1: Fetch exchange rate data
exchange_rate_data = fetch_exchange_rate()
filtered_lines = []
relative_path = os.path.dirname(__file__)
# Step 2: Process each item in the exchange rate data array
for item in exchange_rate_data:
sxrq = item["sxrq"]
currency = item["yhbzl"]
mrhl = float(item["mrhl"])
# Create line in format: sxrq price currency mrhl CNY
line = f"{sxrq} price {currency} {mrhl} CNY"
filtered_lines.append(line)
print(
f"Exchange rate data processed: {sxrq}, {currency}; 买入结算汇兑比率: {mrhl}")
# Step 3: Write the filtered lines to hk2rmb.bean
hk2rmb_path = os.path.join(
relative_path, "../ledger/commodity/hk2rmb.bean")
write_to_file(hk2rmb_path, filtered_lines)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment