File size: 7,496 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""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())