# JPY Rate Analyzer

> Real-time JPY monitoring platform. Parallel crawlers scrape 6 banks; Yahoo Finance fills historical data. LKG fallback ensures HA. Purchase decision engine outputs 'buy now / wait' advice.

- Result: LKG fallback + purchase decision engine (actionable insight)
- Stack: Python, Flask, SQLite, BeautifulSoup4, Pandas, Matplotlib, Yahoo Finance API

A Python platform for monitoring and analysing yen exchange rates in real time. A config-driven design brings several banks' rates together: parallel scrapers fetch the latest rates, SQLite stores them, Flask serves the interface and a REST API, and there's an item converter and a historical trend chart. Final project for the Big Data Warehousing course.

## Problem

Before exchanging yen you have to check each bank's rate one by one — and even with the numbers in front of you, you don't know whether now is a good time. This project gathers several banks' rates in one place and answers the question directly: should you exchange now?

## Key decisions

1. **Banks defined in a config file, scraped by 6 threads in parallel**: Adding a bank means editing the config; the six banks' network waits overlap instead of running one after another.
2. **Wrap SQLite in a repository pattern**: All data access sits in one layer that handles transactions and consistency, so the upper layers never touch the database directly.
3. **Return the last successful data when a scrape fails (Last Known Good)**: If one bank can't be reached for a moment, the page shows its most recent rate instead of a blank.
4. **Backfill historical rates from Yahoo Finance**: Bank pages only show today's rate; Yahoo Finance fills in the history.
5. **Turn the rate into a buying recommendation**: Target rate = budget in TWD ÷ the item's price in yen; if a bank's cash selling rate is below the target, it recommends exchanging now, otherwise waiting.

## Trade-offs

- The scraper depends on each bank's page structure, so a redesign means updating that bank's parsing config
- The history uses Yahoo Finance's market rate (JPYTWD=X daily close) for all six banks, so it is not each bank's real historical rate; differences between banks are only visible from when the scraper started recording
- A 5-minute cache: refreshing within that window shows the last scraped rates, in exchange for not hammering the bank sites

## Results

- Rates from six banks — Bank of Taiwan, First, Hua Nan, E.Sun, Cathay United and Yuanta — in one interface, with the cheapest one highlighted
- A Flask interface plus a REST API, with an item converter and a 90-day trend chart
- The converter includes 23 common items and 10 popular souvenirs (for example a PS5 disc edition at ¥66,980, a 5-pack of Ichiran ramen at ¥2,100)
- This site's project page has a live version: it fetches Bank of Taiwan and E.Sun rates and gives a recommendation with the same rules

## Architecture

```mermaid
flowchart TD
  C["Parallel scraper<br/>crawler.py"] -->|"several banks"| D[("SQLite<br/>db_manager.py")]
  Y["Yahoo Finance API"] -->|"history backfill"| D
  D --> S["rate_service.py<br/>cache + LKG fallback"]
  S --> E["Purchase decision engine"]
  E -->|"buy now / wait"| U["Flask front end<br/>app.py"]
  S --> T["trend_chart.py<br/>trend chart"]
  T --> U
```

## Architecture

- Config-driven scraper: six banks (Bank of Taiwan, First, Hua Nan, E.Sun, Cathay United, Yuanta) are defined in a separate config, so adding a source only means editing the config; 6 threads scrape in parallel
- Persistence layer: a repository pattern gives one interface for data access, with transaction management and consistency guarantees
- Service layer: a cache cuts network requests, and a Last Known Good (LKG) fallback keeps the service available
- History backfill: the Yahoo Finance API backfills historical rates automatically for long-term trends

## Crawler

- Each request waits a random 0.2–0.5 seconds and rotates the User-Agent, with a 10-second timeout; failures aren't retried but handed to LKG (the config has a retry count, but the scraper never uses it)
- Every bank's page is structured differently: which row is yen and which column is the cash selling rate are selectors in the config; E.Sun's page differs the most and got its own parser
- After parsing, pandas cleans everything in one pass: commas, spaces and dashes removed, numbers extracted with regular expressions and converted; rates outside 0.1–0.5 (TWD per yen) are dropped as parse errors, and each bank keeps one row

## Data & cache

- One SQLite rates table (bank, rate, time) indexed on (bank, time); "latest row per bank" comes from a single window-function query
- A 5-minute cache: refreshing within the window doesn't scrape again; it fetches only after expiry
- LKG works per bank: if one bank fails, its most recent valid row in the database is used while the others keep their live rates
- The trend chart plots the daily best (lowest) and average rate for the last 90 days; when data is missing it backfills from Yahoo Finance (backing off and retrying on HTTP 429)

## Purchase Decision Engine

- Target rate = budget in TWD ÷ the item's price in yen, compared with the bank's cash selling rate: at or below the target means "buy now", otherwise "wait"
- It outputs an actionable recommendation instead of handing the user a chart to interpret
- You can also add a rate markup (%); the converter prices items in TWD as best rate × (1 + markup)

## API

- GET /api/rates — latest rate for each bank (JSON, with cache status)
- GET /health — health check: how many rates there are and how long ago the cache was refreshed
- GET /export_csv — export historical rates
- GET /import_top10 — import the popular items list (also available as the flask init-data command)

> Final project for the Big Data Warehousing course.

---

Author: PINGWEI LI (李秉威, Li Ping-Wei)
Original page: https://kbs0830.com/en/projects/yen-rate-analyzer
