"""Step 6: Collect multifamily real estate with logical locations. Uses: - RentCastPropertiesClient from projects.tools.property_market.rentcast .get_properties_by_address() -- property records .get_rental_listings_by_address() -- rental listings .get_sale_listings_by_address() -- sale listings .export_records() -- CSV export - EsriAPIClient from projects.tools.property_market.esri_package.esri_package.esri .get_processed_demographic_info() -- demographics per metro Includes resume checks (skip if output CSVs exist) and retry with exponential backoff for transient RentCast API failures. Output: data/real_estate/properties.csv data/real_estate/rentals.csv data/real_estate/sales.csv data/real_estate/demographics.csv """ from __future__ import annotations import asyncio import logging import os import pandas as pd from projects.tools.property_market.rentcast import RentCastPropertiesClient from . import config logger = logging.getLogger(__name__) _MAX_RETRIES = 3 async def _retry_async(coro_factory, description: str, retries: int = _MAX_RETRIES): """Call *coro_factory()* up to *retries* times with exponential backoff.""" for attempt in range(retries): try: return await coro_factory() except Exception as exc: if attempt < retries - 1: wait = 2 ** attempt * 3 # 3s, 6s, 12s logger.warning("%s failed (attempt %d/%d), retrying in %ds: %s", description, attempt + 1, retries, wait, exc) await asyncio.sleep(wait) else: raise async def _collect_rentcast(client: RentCastPropertiesClient) -> None: """Fetch properties, rental listings, and sale listings for every metro.""" re_dir = config.REAL_ESTATE_DIR re_dir.mkdir(parents=True, exist_ok=True) # Resume check: skip if all three output CSVs already exist props_path = re_dir / "properties.csv" rentals_path = re_dir / "rentals.csv" sales_path = re_dir / "sales.csv" if props_path.exists() and rentals_path.exists() and sales_path.exists(): logger.info("RentCast data already exists (properties, rentals, sales), skipping.") return all_properties = [] all_rentals = [] all_sales = [] for metro_addr in config.METROS: logger.info("RentCast: querying %s ...", metro_addr) try: props = await _retry_async( lambda addr=metro_addr: client.get_properties_by_address( address=addr, property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type] radius=config.RENTCAST_RADIUS_MILES, auto_paginate=False, limit=config.RENTCAST_MAX_RESULTS, ), description=f"RentCast properties {metro_addr}", ) all_properties.extend(props) logger.info(" properties: %d", len(props)) except Exception as exc: logger.warning(" properties failed for %s after retries: %s", metro_addr, exc) try: rentals = await _retry_async( lambda addr=metro_addr: client.get_rental_listings_by_address( address=addr, property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type] radius=config.RENTCAST_RADIUS_MILES, auto_paginate=False, limit=config.RENTCAST_MAX_RESULTS, ), description=f"RentCast rentals {metro_addr}", ) all_rentals.extend(rentals) logger.info(" rental listings: %d", len(rentals)) except Exception as exc: logger.warning(" rentals failed for %s after retries: %s", metro_addr, exc) try: sales = await _retry_async( lambda addr=metro_addr: client.get_sale_listings_by_address( address=addr, property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type] radius=config.RENTCAST_RADIUS_MILES, auto_paginate=False, limit=config.RENTCAST_MAX_RESULTS, ), description=f"RentCast sales {metro_addr}", ) all_sales.extend(sales) logger.info(" sale listings: %d", len(sales)) except Exception as exc: logger.warning(" sales failed for %s after retries: %s", metro_addr, exc) # Brief pause between metros to be polite to the API await asyncio.sleep(0.5) # Write each file individually so partial success is preserved if all_properties: client.export_records(all_properties, props_path) logger.info("Saved %d property records.", len(all_properties)) if all_rentals: client.export_records(all_rentals, rentals_path) logger.info("Saved %d rental listings.", len(all_rentals)) if all_sales: client.export_records(all_sales, sales_path) logger.info("Saved %d sale listings.", len(all_sales)) # Write a done marker so we know all 3 were attempted done_marker = re_dir / ".rentcast_done" done_marker.write_text("done") async def _collect_demographics(client) -> None: """Fetch ESRI demographic data for each metro to make locations 'logical'.""" re_dir = config.REAL_ESTATE_DIR demo_path = re_dir / "demographics.csv" if demo_path.exists(): logger.info("Demographics file already exists, skipping.") return rows = [] for metro_addr in config.METROS: logger.info("ESRI demographics: %s ...", metro_addr) try: info = await _retry_async( lambda addr=metro_addr: client.get_processed_demographic_info(addr), description=f"ESRI demographics {metro_addr}", ) rows.append(info.model_dump()) except Exception as exc: logger.warning(" demographics failed for %s after retries: %s", metro_addr, exc) if rows: df = pd.DataFrame(rows) df.to_csv(demo_path, index=False) logger.info("Saved demographics (%d metros).", len(df)) async def run_async() -> None: """Execute Step 6 (async).""" rentcast_key = os.getenv("RENTCAST_API_KEY") if not rentcast_key: raise ValueError("Set RENTCAST_API_KEY environment variable.") rentcast_client = RentCastPropertiesClient(api_key=rentcast_key) await _collect_rentcast(rentcast_client) # Demographics via ESRI (requires arcgis package -- skip if unavailable) esri_user = os.getenv("ARCGIS_USERNAME") esri_pass = os.getenv("ARCGIS_PASSWORD") if not esri_user or not esri_pass: logger.warning("ARCGIS_USERNAME / ARCGIS_PASSWORD not set, skipping demographics.") else: try: from projects.tools.property_market.esri_package.esri_package.esri import EsriAPIClient esri_client = EsriAPIClient(username=esri_user, password=esri_pass) await _collect_demographics(esri_client) except ImportError: logger.warning("arcgis package not installed, skipping demographics collection.") logger.info("Real estate data collection complete.") def run() -> None: """Sync wrapper around the async implementation.""" asyncio.run(run_async())