Real Estate Price-Drop Monitoring Tool: Building It with AI Agent Assistance
This article describes how to build a daily monitoring tool for second-hand housing listings, from requirement definition and system architecture to data collection, snapshot comparison, price-drop detection, email notifications, testing, security, and limitations. It also explains how an AI coding agent can support the development workflow while keeping human review in the loop, and why a managed web data collection service is often more practical than writing a scraper directly.
1. Requirement Background and Problem Definition
Real estate investors and homebuyers both care about one question: when do second-hand homes in a target city drop in price, and which listings are involved? Refreshing a property platform manually every day is inefficient and easy to miss listings. Assigning this task to a program creates a small data monitoring system.
The goal of the tool discussed in this article is clear:
- The user enters a city and a price range.
- The system collects eligible active listings in that city every day.
- It compares the current listings with historical snapshots to find listings whose prices have dropped.
- It outputs structured information for price-drop listings and sends it by email.
The complexity of this requirement is not in the business logic. It lies in two areas: stable access to the data source and accurate state comparison. The following sections focus on these two points.
2. System Architecture
The entire tool can be divided into four layers:
| Layer | Responsibility | Key Points |
|---|---|---|
| Configuration layer | Accept city, price range, and recipient email | Input validation; credentials stored in environment variables |
| Collection layer | Retrieve listing lists and details | Handle anti-scraping measures, proxies, and dynamic rendering |
| Storage and comparison layer | Save daily snapshots and calculate price changes | Use the listing unique identifier as the key; retain historical prices |
| Notification layer | Generate reports and send emails | Deduplication, retry on failure, templated content |
Scheduling can use the system’s built-in scheduled task and run once at a fixed time each day. When the data volume is small, SQLite or JSON files are sufficient for storage. If multiple cities need to be monitored later or long-term trends need to be retained, the storage can be migrated to a relational database.
3. Data Collection Layer: Why Not Write a Scraper Directly
Using generic HTTP requests to scrape property pages usually leads to the following problems:
- IP restrictions: Too many requests from the same source IP in a short period can result in blocking or empty pages.
- CAPTCHAs: After risk controls are triggered, the page returns a human verification challenge, and regular parsing logic stops working.
- Dynamic rendering: Listing lists are loaded by front-end scripts, and the raw HTML does not contain usable data.
- Page structure changes: After a page redesign, parsing rules based on CSS selectors become invalid.
The essence of these problems is the conflict between the access environment and anti-scraping strategies; the code logic itself is not complex. Therefore, a common practice is to use a managed web data collection service. These services generally provide the following capabilities:
- A proxy pool that automatically rotates outbound IPs.
- Headless browser rendering that returns page data after scripts are executed.
- CAPTCHA recognition and retries.
- Structured JSON returned by URL or keyword.
When selecting a service, several criteria need to be checked: coverage of the target site, whether the returned fields include key information such as price, address, and area, pricing and call quotas, and whether data usage complies with the terms of service. After choosing a service, create an API key in the provider console and store the key in environment variables or a secrets management service. Do not write it into code or logs.
4. Using an AI Agent for Development
AI coding agents differ significantly from earlier single-turn code generation tools. They can read context files, break down tasks, generate design documents, write code, and run tests. The developer’s main work shifts from line-by-line coding to defining requirements, providing reference materials, and reviewing results.
In practice, an effective workflow is as follows:
Step 1: Provide context. Organize the sample request code for the collection API, field descriptions, and the input format for the target city and price range into documents and place them in the project context directory. The more complete the context, the smaller the deviation between the generated code and the actual API.
Step 2: Define requirement boundaries. The requirement description should include input format, output fields, notification conditions, and exception handling requirements. For example, clarify whether a “price drop” means a decrease compared with the previous snapshot or a decrease compared with the first recorded price.
Step 3: Generate in stages. First ask the agent to output a design document, confirm the module breakdown and data structures, then generate the main code, and finally generate test cases. A staged approach makes it easier to find design problems early.
Step 4: Human review. Code generated by the agent needs human review for three types of issues: whether API fields match the documentation, whether exception branches are covered, and whether credentials and sensitive information have been mistakenly written into the code. Passing automatically generated tests does not mean the business logic is correct; the test cases themselves also need review.
5. Core Logic: Price-Drop Detection
The core of price-drop detection is state comparison. A listing needs a stable unique identifier, usually the listing ID provided by the platform or the detail page URL. After each collection, the current price is compared with the historical record.
The decision rules can be written as the following pseudocode:
for listing in current collection results:if listing is not within the price range:skipprevious_price = read the price of this listing from the previous snapshotif previous_price is empty:record as a new listing and do not trigger a notificationelif current_price < previous_price:add to the price-drop list and record the drop amountupdate the price of this listing in the snapshot
Three details are easy to get wrong:
- First run: When there is no historical snapshot, all listings are “new” and should not all be treated as price drops.
- Price range boundaries: Whether a listing that enters the price range after a price drop should be included in notifications must be clarified in the requirements.
- Price field format: The price returned by the API may be a string containing a currency symbol or thousands separator. It needs to be converted to a numeric value before comparison.
6. Example Code Skeleton
The following code shows the basic structure for processing collection results, detecting price drops, and sending emails. The API endpoint, field names, and authentication method must follow the actual service documentation; the code here is for illustration only.
import jsonimport osimport smtplibfrom email.mime.text import MIMETextfrom pathlib import Pathimport requestsAPI_ENDPOINT = os.environ["COLLECTOR_API_ENDPOINT"]API_KEY = os.environ["COLLECTOR_API_KEY"]SMTP_HOST = os.environ["SMTP_HOST"]SMTP_USER = os.environ["SMTP_USER"]SMTP_PASSWORD = os.environ["SMTP_PASSWORD"]SNAPSHOT_FILE = Path("snapshots.json")def fetch_listings(city: str, min_price: int, max_price: int) -> list[dict]:"""Call the collection API and return a list of listings. Field names are examples; refer to the actual documentation."""resp = requests.post(API_ENDPOINT,headers={"Authorization": f"Bearer {API_KEY}"},json={"city": city, "min_price": min_price, "max_price": max_price},timeout=60,)resp.raise_for_status()return resp.json().get("listings", [])def load_snapshot() -> dict:if SNAPSHOT_FILE.exists():return json.loads(SNAPSHOT_FILE.read_text(encoding="utf-8"))return {}def save_snapshot(data: dict) -> None:SNAPSHOT_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")def detect_price_drops(listings: list[dict], snapshot: dict) -> list[dict]:drops = []for item in listings:listing_id = str(item["id"])current = float(str(item["price"]).replace(",", "").replace("$", ""))previous = snapshot.get(listing_id)if previous is not None and current < previous:drops.append({"id": listing_id,"address": item.get("address", ""),"old_price": previous,"new_price": current,"url": item.get("url", ""),})snapshot[listing_id] = currentreturn dropsdef send_report(to_addr: str, drops: list[dict]) -> None:if not drops:returnlines = [f"{d['address']}: {d['old_price']:.0f} -> {d['new_price']:.0f} {d['url']}"for d in drops]msg = MIMEText("\n".join(lines), "plain", "utf-8")msg["Subject"] = f"Price drops today: {len(drops)} listings"msg["From"] = SMTP_USERmsg["To"] = to_addrwith smtplib.SMTP_SSL(SMTP_HOST) as server:server.login(SMTP_USER, SMTP_PASSWORD)server.send_message(msg)def run(city: str, min_price: int, max_price: int, to_addr: str) -> None:snapshot = load_snapshot()listings = fetch_listings(city, min_price, max_price)drops = detect_price_drops(listings, snapshot)save_snapshot(snapshot)send_report(to_addr, drops)print(f"Collected {len(listings)} listings, {len(drops)} price drops")if __name__ == "__main__":run("Austin", 200000, 500000, "you@example.com")
There are several design considerations in the code:
- All credentials come from environment variables, and no plaintext keys appear in the code.
- The snapshot is saved before the notification is sent. If email sending fails, the next run will not repeatedly identify the same price drop.
- Price parsing is centralized in one place, making it easier to support more formats later.
- No email is sent when there are no price drops, avoiding invalid notifications.
For a production environment, additional items include request retries and backoff, timeouts and circuit breaking, structured logging, alerts for email sending failures, and protection against concurrent writes to the snapshot file.
7. Testing and Validation
Testing should cover three levels:
- Unit tests: Verify how the price parsing function handles different formats, and verify the price-drop decision under four conditions: first run, unchanged price, increased price, and decreased price.
- Integration tests: Use fixed sample responses instead of the real API to verify the complete path from collection to notification. Samples should include boundary cases such as missing fields, abnormal prices, and duplicate listings.
- Canary run: First run the tool for one week in one city and one price range, and manually spot-check whether the notification content matches the actual prices on the platform pages.
During validation, also check collection completeness. If the number of returned listings on a given run is significantly lower than the previous day, it may be due to API rate limiting or page structure changes. An alert should be triggered instead of silently marking all listings as “disappeared.”
8. Security and Compliance
Data collection tools need to pay attention to the following items:
- Terms of service: Confirm whether the target website’s terms of use allow automated access and whether data usage is restricted.
- Access frequency: Running once per day with a single request per city is far below the level that would burden the site. Avoid high-frequency polling.
- Personal information: Listing information is mostly public data, but if it involves personal information such as landlord contact details, it should not be stored or forwarded.
- Credential management: Rotate API keys and email passwords regularly, minimize permissions, and ensure they can be revoked quickly if leaked.
- Email content: Notification content should contain only necessary fields and avoid sending the entire raw API response.
9. Limitations and Future Improvements
The current approach still has clear boundaries:
- It depends on the stability and quota of an external collection service. If the service is interrupted, the tool cannot retrieve data.
- Price-drop detection compares only the listing price. It does not distinguish the reason for the price adjustment or consider changes to the listing itself.
- It supports only a single scheduled run and has no real-time monitoring capability.
- Email notification depends on an SMTP service, so bounce handling and quota limits need to be addressed.
Future expansion can proceed in three directions: add multi-city configuration and user management; migrate snapshots to a database to support price trend queries; and introduce a message queue to decouple collection from notification, making it easier to add SMS or instant messaging channels.
Conclusion
The functionality of this tool is not complex. Its engineering value is concentrated in two points: first, delegate anti-scraping and network access problems to a professional collection service so the code can focus on business logic; second, use an AI coding agent to accelerate the process from requirements to code while retaining a human review step. For similar data monitoring requirements, this layered approach and price-drop detection method can be reused directly.
