October 09, 2026
Automation and Curation of Hydrometeorological Historical Series of ANA via Computational Pipeline in R Language
Automation and Curation of Hydrometeorological Historical Series from Ana Via Computational Pipeline in R Language
Marcos Aurélio Eustorgio Filho; Douglas Augusto De Paula
DOI: 10.22167/2675-6528-202603237
Article derived from a Final Course Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
The availability of consistent environmental data is fundamental for the advancement of research in climatology and water resource management. A computational algorithm in R language was developed and implemented for the automated acquisition, standardization, and organization of daily historical series of precipitation, level, and flow, from the WebService of the National Water and Basic Sanitation Agency (ANA). The method was based on a structured data pipeline, operating according to the time windows of 1961–1990, 1991–2020, and 2021–2024. The implementation used parallel processing, which ensured performance gains compared to sequential methods. As a result, the algorithm qualified the station inventory and generated structured data in Parquet format with gzip compression, ensuring high performance and volumetric economy. It was concluded that the automated solution overcame the operational limitations of manual and pre-existing tools, providing curated and high-granularity datasets, suitable for advanced applications of hydrological modeling and Machine Learning algorithms.
Keywords: Automation; Data Science; Hydrology; R Language; Time series.
1. Introduction
The availability of consistent and accessible environmental data is a fundamental element for the advancement of research in climatology, hydrology, and natural resource management. In recent decades, initiatives focused on making open data available by governmental institutions and scientific organizations have expanded access to meteorological and hydrological information on a global scale (Andrade et al., 2022; Menezes et al., 2026). This progress has contributed significantly to the development of studies aimed at understanding climate variability, hydrological modeling, and the management of risks associated with extreme events (Amorim et al., 2020; Andrade et al., 2022; Palharini et al., 2022; Pedreira Junior et al., 2021; Silva et al., 2022; Xavier et al., 2016).
Among the environmental variables observed at the Earth’s surface, precipitation stands out as one of the main components of the hydrological cycle, exerting direct influence on processes such as surface runoff, aquifer recharge, fluvial dynamics, and water availability for different uses (Amorim et al., 2020; Andrade et al., 2022; Pedreira Junior et al., 2021; Zanin and Satyamurty, 2021). Complementarily, hydrological variables such as river levels (stages) and flow rate are fundamental for understanding the dynamics of river basins, allowing for an integrated analysis of hydrological behavior at different spatial and temporal scales (Amorim et al., 2020; Marengo et al., 2024). In Brazil, the growing occurrence of extreme hydrometeorological events, such as episodes of intense precipitation resulting in floods and landslides, further highlights the importance of systematic monitoring of these variables to support scientific analyses, territorial planning, and public policy decision-making processes (Marengo, 2024; Marengo et al., 2024; Menezes et al., 2026; Moreira, 2024; Palharini et al., 2022).
Hydrometeorological monitoring networks play a strategic role by providing direct surface observations, considered essential for characterizing regional hydrological behavior and supporting robust scientific analyses. One of the main sources of hydrological and pluviometric data in Brazil is the database provided by the National Water and Basic Sanitation Agency (ANA), which compiles historical series from thousands of stations distributed across the national territory (Andrade et al., 2022; Menezes et al., 2026; Silva, 2025; Xavier et al., 2016). This information includes records of precipitation, river levels, and flow rates, constituting essential infrastructure for scientific research and operational applications in the country. However, obtaining meteorological data with adequate spatial and temporal representativeness still represents a challenge in several regions of Brazil, especially in areas where the density of monitoring stations is limited (Andrade et al., 2022; Menezes et al., 2026; Palharini et al., 2021; Xavier et al., 2016).
Despite the relevance of ANA’s database, systematic access to these historical series still presents operational challenges, especially when data for multiple stations and long time periods are desired. In general, the acquisition process requires individual queries to ANA’s WebService or the development of specific collection routines, which can result in inefficient, difficult-to-replicate, and failure-prone procedures (Chagas et al., 2020; Silva, 2025; Sousa, 2017). Although tools exist for this type of processing, such as SisCAH, SiADH, and the hydrobr package, there are still significant limitations related to the updating of these solutions, robustness against service failures, and the absence of standardization in metadata generation and data organization (Calegario et al., 2024; Lopes et al., 2013; Sousa et al., 2009). Larger-scale initiatives, such as CAMELS-BR (Chagas et al., 2020), have consolidated historical series and basin attributes from ANA data; however, these are static and pre-processed datasets, without the availability of a replicable and updatable acquisition algorithm, a gap that this work sought to fill. Additionally, observational surface data play a fundamental role in validating meteorological products derived from remote sensing and atmospheric reanalyses, making the use of observed data for evaluation and calibration indispensable (Amorim et al., 2020; Andrade et al., 2022; Pedreira Junior et al., 2021; Xavier et al., 2016).
Given this context, the need to overcome the operational limitations associated with manual data acquisition and the lack of a replicable and updatable algorithm for acquiring hydrological series from ANA justify the present research. A critical differentiator of the proposed solution is the focus on extracting raw daily data (water levels, rainfall, and flow), preserving the granularity necessary for modeling extreme events, as opposed to aggregated averages. The system’s temporal scope was structured based on periods of up to thirty years (1961-1990, 1991–2020, and 2021-2024), allowing systematic access to large-scale information. Furthermore, the study documents technical criteria for series validation, contributing to the transparency and reliability of the process. Finally, the algorithm incorporates mechanisms for operational robustness and computational efficiency through parallelized processing, accelerating database curation. Thus, this work aims to develop and implement a computational algorithm in R language for the automated acquisition, standardization, and organization of daily historical precipitation, water level, and flow series from the WebService of the National Water and Basic Sanitation Agency (ANA).
2. Material and Methods
The research was characterized as an applied study in Data Science, framed within the line of Automation and Strategic Analytics. The objective was to develop and implement a computational algorithm in R language for the automated acquisition, standardization, and organization of daily historical series of precipitation, level, and flow from the WebService of the National Water and Basic Sanitation Agency (ANA). The work was based on the construction of a structured data pipeline to overcome the operational limitations of manual acquisition and pre-existing tools.
Secondary data were obtained from the ANA HydroSerieHistorica WebService (ANA, 2024; SNIRH, 2023; Silva, 2025). The pipeline was designed to extract daily punctual records of precipitation, flow rate, or level (elevations), preserving the granularity necessary for modeling extreme events (Andrade et al., 2022; Pedreira Junior et al., 2021; Xavier et al., 2016). The temporal scope covered the periods from 1961 to 1990, 1991 to 2020 (Xavier et al., 2016), and 2021 to 2024, based on INMET climatological normals. Automatic filters were applied to process stations with at least one year of records in the selected interval (Calegario et al., 2024; Silva, 2025; Sousa, 2017).
Data collection was performed through automated consumption of the ANA WebService, using HTTP requests implemented in the R language (R Core Team, 2025) with the httr2 package (Wickham, 2025). The data, originally in XML format, underwent structured parsing processing with the xml2 package (Wickham et al., 2019), which allowed for the individualized capture of daily fields and their respective statuses and consistency levels. The series included CodEstacao (unique code, 8 digits), Data (daily observation, YYYY-MM-DD), and Chuva, Cota or Vazão (observed daily value).
The variables were expressed in millimeters (mm) for precipitation, centimeters (cm) for river levels, and cubic meters per second (m³/s) for flow rate. The Status field indicated the quality of the daily observation, with codes from 0 to 4, where 1 represented observed and 2 estimated. NivelConsistencia differentiated unreviewed records (Level 1 – Raw) from those submitted to institutional quality control (Level 2 – Consisted). DataIns recorded the date the record was inserted by ANA.
The pipeline development was entirely structured in the R language (R Core Team, 2025), using packages such as httr2 (Wickham, 2025) for HTTP communication, future (Bengtsson, 2021) for parallelization, tidyverse (Wickham et al., 2019) for data manipulation, and xml2 (Wickham et al., 2019) for XML processing. Data persistence occurred in Parquet format with gzip compression, via the arrow package (Richardson et al., 2025). The execution environment was configured with 12 workers on a multisession plan, allowing simultaneous processing of months from the same station (Bengtsson, 2021).
A resilient communication architecture was implemented, with an automatic retry mechanism via the httr2 package, allowing up to six connection attempts before aborting processing (Wickham, 2025). A timeout of 180 seconds was configured to prevent request blocking. Additionally, an exponential backoff strategy was established, with increasing intervals between successive attempts (1, 2, 4, 8, 16, and 32 seconds), limited to 90 seconds (Wickham, 2025). To mitigate overload on the remote service, load control was implemented with systematic pauses of 6 seconds between station requests and interruptions of 60 seconds for every batch of 30 processed stations. A 120-second interval was applied during the transition between Federative Units.
The curation and validation stage of the series addressed the redundancy of multiple concurrent monthly series made available by ANA’s WebService. The algorithm applied a deterministic selection model, prioritizing series whose temporal reference (DateTime) occurred on the first day of the month. In cases of ties, a tie-breaking hierarchy based on the quality and recency of information was used, prioritizing Consistency Level 2 (Consolidated) and the most recent Insertion Date. After selection, daily parsing was performed, reconstituting complete calendars and filling months without data with null values (NA).
A metadata generation system and analytical logs were incorporated for quality control, traceability, and transparency. The algorithm monitored the status of HTTP requests and the integrity of XML responses, classifying the processed stations into three categories: with valid data, without data in the period, and with technical failures. At the end of each state execution, a consolidated summary table was generated in CSV and Parquet formats with gzip compression.
3. Results and Discussion
The execution of the proposed computational pipeline resulted in the acquisition and processing of a significant volume of hydrometeorological data, encompassing 36,063 registered stations, of which 16,078 were fluviometric and 19,985 pluviometric. The collection strategy was designed to include only stations with an operational start date on or before January 1, 2024, ensuring the potential for a full year of records by the final reference date of December 31, 2024. This approach considered the latency observed in the database updates of the National Water and Basic Sanitation Agency (ANA), where more recent records were still being processed, especially for the year 2025. The segmentation of data by Federative Unit and by time periods (1961–1990, 1991–2020, and 2021–2024) was crucial to mitigate the load on the ANA WebService and circumvent operational instabilities, as observed in previous studies (Silva, 2025; Sousa, 2017).
The results of the pipeline execution were organized into three main directories, corresponding to the precipitation, river level, and flow rate variables. Each directory contained subdirectories for the three analyzed time periods, as well as summary files that consolidated information about the download process. These summaries detailed the number of eligible stations, successful processes, stations with no available data, and failures associated with server errors. Internally, the time period subdirectories were subdivided into long_data, containing files standardized by Federative Unit; nodata_gauges, with the list of stations lacking data in the period; and problem_gauges, which stored stations with failures, even after applying automatic retry mechanisms, exponential backoff, and error handling, highlighting the system’s robustness.
Overview of the obtained data
The station coverage achieved by the pipeline showed significant variations among data types and time periods. In the period from 1961 to 1990, out of 11,627 stations eligible for precipitation, 77.1% returned valid data. For level and discharge, out of 6,534 stations eligible for each type, 63.9% and 39.1% provided data, respectively. In the period from 1991 to 2020, the data availability for precipitation was 43.8% of the 19,582 eligible stations, while for level and discharge, it was 30.8% and 20.6% of the 15,149 eligible stations, respectively. In the most recent period, from 2021 to 2024, out of 19,985 eligible stations for precipitation, 22.0% contained data, and out of 16,078 eligible stations for level and discharge, 16.0% and 10.9% provided data, respectively. The reduction in the percentages of available data in the most recent periods is an expected finding, as it reflects the proximity of the collection date to the period under analysis, implying that a significant portion of the records had not yet been entered or consolidated into the ANA repository. During the collection of discharge data for 1991 to 2020, instability was identified in the ANA server, affecting states such as Pernambuco, Piauí, Paraná, Rio de Janeiro, and Rio Grande do Norte, which required a new execution of the pipeline for these locations, ensuring the integrity of the results.
Computational performance and parallelization efficiency
The evaluation of the pipeline’s computational performance revealed a substantial performance gain with the implementation of parallelized processing. When comparing sequential execution with parallelized execution, using 12 workers and the same precipitation dataset for the period from 1991 to 2020 (19,582 eligible stations), a reduction in total processing time was observed. The sequential method required approximately 4,629 minutes (77.1 hours), while the parallel execution completed the task in about 3,430 minutes (57.2 hours). This represented a performance gain of 1.35 times, or a reduction of approximately 26% in total time. This benefit was more pronounced in states with denser monitoring networks, where the scaling of monthly tasks found greater room for optimization. It is important to note that these values reflect a practical application, subject to network latencies and remote service response limitations, remaining within realistic operational levels, which validates the efficiency of the developed solution.
Quality and consistency of the extracted database
The quality of the extracted data was one of the pillars of the pipeline’s evaluation. The completeness analysis indicated that approximately 43.76% of the eligible stations resulted in valid time series, demonstrating the tool’s capability to retrieve information from ANA’s database. Most stations classified as without data were associated with the actual absence of records in the requested period, and not with technical extraction failures, which represented a reduced fraction of the total (0.27%), confirming the algorithm’s robustness in accessing the remote service. The spatial distribution of the results revealed heterogeneity among the Federative Units, with Roraima (82.81%), Ceará (74.13%), and Paraná (69.32%) showing greater data availability, in contrast to Rio Grande do Norte (21.68%), Pernambuco (22.62%), and Santa Catarina (22.64%). This variability is consistent with the differences in monitoring network density and historical record availability in Brazil, as pointed out by Chagas et al. (2020), who identified disparities in the maturity of hydrometeorological monitoring across the country’s regions.
The consistency of the monthly series was also evaluated, revealing distinct patterns among the variables. For level and flow, the percentage of consistent series (Level 2) remained high and relatively stable in the periods 1961-1990 and 1991-2020, ranging from 71.9% to 90.1%. However, there was an expressive drop in the period from 2021 to 2024, with 62.3% for level and 71.2% for flow, reflecting the still provisional and institutionally reviewed nature of the most recent data. In contrast, precipitation showed substantially lower consistency percentages in all periods, becoming practically null (0.3%) in the most recent period. This suggests a slower pace in the institutional consolidation of rainfall data compared to the other variables. This characterization of series reliability, based on official quality control indicators from ANA, aligns with methodological precedents such as CAMELS-BR (Chagas et al., 2020), which also used the percentage of data checked by the agency to qualify the reliability of the series.
Comparative between all responsible bodies and ANA’s own stations
The disaggregated analysis of station coverage and the consistency of monthly series, comparing the set of all responsible bodies with the subset of stations operated directly by ANA, revealed notable differences. Stations under ANA’s exclusive responsibility showed substantially higher coverage percentages for all data types and periods. For precipitation, ANA’s exclusive coverage reached 90.0% in the period from 1961 to 1990, 70.6% from 1991 to 2020, and 60.5% from 2021 to 2024, in contrast to 77.1%, 43.8%, and 22.0% for the set of all bodies, respectively. A similar pattern was observed for level and discharge, where ANA stations also showed higher coverage. This difference became more pronounced in the most recent period, indicating that the network operated directly by ANA is less affected by data update latency, a critical factor for the availability of timely information.
The advantage of ANA’s own stations was also reflected in the technical quality of the obtained series, especially in the consistency of Level 2 (Consisted). For fluviometric variables, ANA’s exclusive series showed consistently higher consistency percentages than the combined network. Flow reached 100.0%, 99.5%, and 77.5% in the three periods (1961-1990, 1991-2020, and 2021-2024, respectively) for ANA stations, compared to 88.9%, 90.1%, and 71.2% for all agencies. River levels followed a similar pattern, with 91.2%, 97.4%, and 74.7% for ANA, versus 71.9%, 82.0%, and 62.3% for all agencies. Precipitation, although with a more heterogeneous pattern, also showed much higher consistency in ANA stations in the older periods (89.9% vs. 26.7% in 1961-1990; 41.3% vs. 23.5% in 1991-2020), converging to percentages close to zero in the most recent period for both datasets.
The distribution of daily observation statuses, aggregated into categories such as “Observed”, “No information”, “Other classifications”, and “No record”, revealed an increasing trend in the proportion of observed days (Status 1) towards more recent periods, accompanied by a reduction in the proportion of days with no record for all data types. In the period from 2021 to 2024, precipitation showed the highest proportion of observed days (73.5%), followed by streamflow (67.1%) and water level (67.6%). In contrast, water level showed the highest proportion of days with no record in the period from 1961 to 1990 (63.4%), reflecting the lower historical density of the streamflow monitoring network during that period. The “Other classifications” category remained residual for precipitation in all periods (below 0.6%), but grew more expressively for water level and streamflow in the period from 2021 to 2024 (9.1% and 9.8%, respectively), suggesting a higher incidence of provisional or not yet fully consolidated classifications in the most recent streamflow data. When the analysis was restricted to stations under the exclusive responsibility of ANA, the proportion of days with no record significantly reduced in the period from 1991 to 2020, from 49.4% to 18.3% for precipitation and from 41.4% to 24.6% for streamflow, a pattern consistent with the comparison of station coverage.
Storage efficiency and data structuring
Storage efficiency was a fundamental criterion for the pipeline’s suitability for large-scale applications. To quantify this efficiency, the total volume occupied by precipitation files from 1991 to 2020 was compared, aggregating data from all Federative Units. Data exported in CSV format occupied 6,866 MB, while the same dataset stored in Parquet format with Gzip compression occupied only 181 MB. This difference represents a reduction of approximately 97.36% in storage volume. This volumetric saving is attributed to Parquet’s columnar storage structure, which preserves variable typing, allows for more effective compression, and enables selective column reading, unlike CSV, which stores data as plain text without explicit typing. This optimization reduces infrastructure costs and read/write time in applications that process long-term historical series, confirming the format’s suitability for the data scale generated by the pipeline for hydrological and climatological studies.
Pipeline robustness and error handling
The pipeline’s robustness was evaluated by analyzing the system’s behavior in the face of communication failures and inconsistencies in the source data, as demonstrated by the analytical logs generated during execution. These logs recorded in detail the status of requests, station processing, and events associated with data extraction, allowing for complete monitoring of the algorithm’s operational flow. This included informational messages, identification of data absence, occurrence of errors, and confirmation of successful executions. The system was able to differentiate situations of non-existent records from those where technical failures occurred, which contributed to the transparency and traceability of the process. The pipeline’s robustness became even more evident in handling communication failures, where error logs associated with the absence of data returned by the WebService occurred, triggering internal control mechanisms, such as automatic pauses implemented between requests per Federative Unit. Such programmed interruptions aimed to avoid overloading the ANA server, especially in scenarios of multiple consecutive requests, ensuring that extraction occurred stably and in accordance with the institutional repository’s capabilities. The continuity of the collection process was guaranteed by the combination of automatic retry mechanisms and exponential backoff, which allowed for the recovery of unstable requests and the circumvention of traffic limitations, such as the HTTP 429 (Too Many Requests) error, without the need for manual intervention. The system provided detailed information about each processing step, with individual monitoring of stations and explicit indication of data absence at monthly and annual levels, demonstrating the pipeline’s ability to differentiate operational scenarios.
In summary, the results demonstrate that the developed and implemented algorithm achieved the objective of automating the acquisition, standardization, and organization of daily historical series of precipitation, level, and flow from ANA. The pipeline presented high computational efficiency, especially due to parallelization and the use of the Parquet format, which optimized processing time and storage volume. The application of deterministic criteria for series selection and validation, along with resilience mechanisms, ensured the system’s robustness against network instabilities and guaranteed the integrity and temporal consistency of the extracted information. The solution provides curated, high-granularity datasets, overcoming operational limitations of pre-existing tools and offering a reproducible methodological model for large-scale environmental data curation, suitable for advanced hydrological modeling applications and Machine Learning algorithms.
4. Conclusion
The present study focused on the development and implementation of a computational algorithm in R language, aiming for the automated acquisition, standardization, and organization of daily historical series of precipitation, level, and flow, sourced from the WebService of the National Water and Basic Sanitation Agency (ANA). It was verified that the pipeline processed an expressive volume of data from 36,063 stations, segmented by Federative Unit and time periods, demonstrating its capacity to handle large scales. The results showed high computational efficiency, with parallelized processing providing a performance gain of 1.35 times compared to sequential execution. The use of the Parquet format with Gzip compression resulted in an approximate 97.36% reduction in storage volume, optimizing data management. It was identified that the availability and consistency of the data varied between variable types and periods, with stations operated directly by ANA showing greater coverage and quality. The system’s robustness was confirmed by its ability to manage communication failures and inconsistencies in the source data, through automatic retry and exponential backoff mechanisms, ensuring the integrity and continuity of the extraction process.
The main contribution of this work lies in providing a reproducible methodological model for large-scale hydrometeorological data curation, generating curated, high-granularity daily datasets. This solution overcomes the operational limitations of manual and pre-existing tools, offering a consistent and reliable database, suitable for advanced hydrological modeling applications and Machine Learning algorithms. Although some specific limitations related to official access methods to the HidroWeb system have been identified, which may condition the release of query keys, the algorithm demonstrated the strategic advantage of operating directly on the institutional WebService, expanding its immediate applicability. As a future perspective, integration with the institution’s official interfaces is suggested, which could enhance the volume of data obtained, while maintaining the already established validation and structuring protocols. In summary, the developed system constitutes a robust and efficient tool, contributing significantly to transparency and support for scientific studies and decision-making that require reliable and reproducible environmental databases.
Bibliographic References
Amorim, J.S.; Viola, M.R.; Junqueira, R.; Oliveira, V.A.; Mello, C.R. 2020. Evaluation of satellite precipitation products for hydrological modeling in the Brazilian Cerrado biome. Water 12(9): 2571.
Andrade, J.M.; Neto, A.R.; Bezerra, U.A.; Moraes, A.C.C.; Montenegro, S.M.G.L. 2022. A comprehensive assessment of precipitation products: Temporal and spatial analyses over terrestrial biomes in Northeastern Brazil. Remote Sensing Applications: Society and Environment 28(100842): 1-27.
Marengo, J.A.; Dolif, G.; Cuartas, A.; Camarinha
Menezes, P.C.M.; Souza, D.C.; Tavares, M.G.; Marques, R.A.G. 2026. Comparative analysis of the accuracy of temperature and precipitation data in Brazil. Atmosphere 1(1): 1-21.
Palharini, R.S.A.; Vila, D.A.; Araujo Palharini, R.S.; Machado, E.M.; Undurraga, E. 2022. Analysis of extreme rainfall and natural disasters events using satellite precipitation products in different regions of Brazil. Atmosphere 13(10): 1680.
Pedreira Junior, A.L.; Biudes, M.S.; Machado, N.G.; Vourilitis, G.L.; Geli, H.M.E.; Santos, L.O.F.; Querino, C.A.S.; Ivo, I.O.; Neto, N.L. 2021. Assessment of remote sensing and re-analysis estimates of regional precipitation over Mato Grosso, Brazil. Water 13(3): 333.
Silva, E.H.L.; Silva, F.D.S.; Junior, R.S.S.; Pinto, D.D.C.; Costa, R.L.; Gomes, H.B.; Júnior, J.B.C.; Freitas, I.G.F.; Herdies, D.L. 2022. Performance assessment of different precipitation databases (Gridded analyses and reanalyses) for the new Brazilian agricultural frontier: SEALBA. Water 14(9): 1473.
Xavier, A.C.; King, C.W.; Scanlon, B.R. 2016. Daily gridded meteorological variables in Brazil (1980-2013). International Journal of Climatology 36(6): 2644-2659.
Zanin, P.R.; Satyamurty, P. 2021. Interseasonal and Interbasins Hydrological Coupling in South America. Journal of Hydrometeorology 22(6): 1609-1625.
Article originating from the Final Course Work of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform