stock-bot/tools/curate-etl/src/run_mongo.rs

1043 lines
38 KiB
Rust

//! Direct read-only MongoDB streaming runners for all M1 and M2 `curate-*` CLI commands.
//!
//! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`])
//! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them
//! directly into the shared `run_curate_*` reader pipelines with zero intermediate `.bson`
//! scratch files.
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit};
use crate::bson_ceo_shorts::CeoShortsFieldNames;
use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames};
use crate::bson_stream::BsonStreamOptions;
use crate::curate_adj::AdjPointInTimeFence;
use crate::ilp::IlpWriterOptions;
use crate::mongo_stream::{
MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection,
};
use crate::run_curate_adj::{
run_curate_adj_factors_with_readers, CurateAdjFactorsRunReport, RunCurateAdjError,
};
use crate::run_curate_bars::{
load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport,
RunCurateBarsError,
};
use crate::run_curate_bars_1m::{
run_curate_bars_1m_from_readers_to_dir, CurateBars1mArgs, CurateBars1mRunReport,
RunCurateBars1mError,
};
use crate::run_curate_corporate_actions::{
run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport,
RunCurateCorporateActionsError,
};
use crate::run_curate_events::{
run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError,
};
use crate::run_curate_fundamentals::{
run_curate_fundamentals_with_optional_old_readers, CurateFundamentalsArgs,
CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, RunCurateFundamentalsError,
};
use crate::run_curate_fx::{
run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE,
};
use crate::run_curate_fx_1m::{
run_curate_fx_1m_from_reader_to_dir, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError,
};
use crate::run_curate_macro::{
run_curate_macro_from_reader, CurateMacroRunReport, RunCurateMacroError,
};
use crate::run_curate_posts::{
run_curate_posts_with_reader, CuratePostsRunReport, RunCuratePostsError,
};
use crate::run_curate_qm_bars_1m::{
run_curate_qm_bars_1m_from_reader_to_dir, CurateQmBars1mArgs, CurateQmBars1mRunReport,
RunCurateQmBars1mError,
};
use crate::run_curate_shorts::{
run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError,
};
/// Error returned by direct MongoDB streaming curation commands.
#[derive(Debug)]
pub enum RunMongoCurateError {
Mongo(MongoStreamError),
Bars(RunCurateBarsError),
Adj(RunCurateAdjError),
CorporateActions(RunCurateCorporateActionsError),
Fx(RunCurateFxError),
Shorts(RunCurateShortsError),
Events(RunCurateEventsError),
Fundamentals(RunCurateFundamentalsError),
Posts(RunCuratePostsError),
Macro(RunCurateMacroError),
Bars1m(RunCurateBars1mError),
QmBars1m(RunCurateQmBars1mError),
Fx1m(RunCurateFx1mError),
}
impl fmt::Display for RunMongoCurateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Mongo(e) => write!(f, "{e}"),
Self::Bars(e) => write!(f, "{e}"),
Self::Adj(e) => write!(f, "{e}"),
Self::CorporateActions(e) => write!(f, "{e}"),
Self::Fx(e) => write!(f, "{e}"),
Self::Shorts(e) => write!(f, "{e}"),
Self::Events(e) => write!(f, "{e}"),
Self::Fundamentals(e) => write!(f, "{e}"),
Self::Posts(e) => write!(f, "{e}"),
Self::Macro(e) => write!(f, "{e}"),
Self::Bars1m(e) => write!(f, "{e}"),
Self::QmBars1m(e) => write!(f, "{e}"),
Self::Fx1m(e) => write!(f, "{e}"),
}
}
}
impl Error for RunMongoCurateError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Mongo(e) => Some(e),
Self::Bars(e) => Some(e),
Self::Adj(e) => Some(e),
Self::CorporateActions(e) => Some(e),
Self::Fx(e) => Some(e),
Self::Shorts(e) => Some(e),
Self::Events(e) => Some(e),
Self::Fundamentals(e) => Some(e),
Self::Posts(e) => Some(e),
Self::Macro(e) => Some(e),
Self::Bars1m(e) => Some(e),
Self::QmBars1m(e) => Some(e),
Self::Fx1m(e) => Some(e),
}
}
}
/// Parsed arguments for `curate-bars-1d --from-mongo`.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateBars1dMongoArgs {
pub mongo: MongoCliOptions,
pub with_qm_prices: bool,
pub provider_mapping: PathBuf,
pub listing_currencies: PathBuf,
pub out_dir: PathBuf,
pub rel_tolerance: f64,
pub threads: usize,
}
/// Parsed arguments for `curate-adj-factors --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateAdjFactorsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub bars_1d_dir: PathBuf,
pub out_dir: PathBuf,
pub fence: Option<AdjPointInTimeFence>,
}
/// Parsed arguments for `curate-corporate-actions --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateCorporateActionsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub delistings: Option<PathBuf>,
pub out_dir: PathBuf,
}
/// Parsed arguments for `curate-fx-1d --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFx1dMongoArgs {
pub mongo: MongoCliOptions,
pub te_symbol: String,
pub out_dir: PathBuf,
}
/// Parsed arguments for `curate-shorts --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateShortsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub key_field: String,
pub report_date_field: String,
pub shares_short_field: String,
pub net_change_field: Option<String>,
pub pct_float_field: Option<String>,
pub mapping_source: String,
}
/// Parsed arguments for `curate-events --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateEventsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub filings_key_field: String,
pub filings_timefiled_field: String,
pub filings_form_type_field: String,
pub filings_filing_id_field: Option<String>,
pub filings_url_field: Option<String>,
pub earnings_key_field: String,
pub earnings_report_date_field: String,
pub earnings_announce_time_field: String,
pub earnings_fiscal_period_end_field: Option<String>,
pub earnings_actual_eps_field: Option<String>,
pub earnings_revenue_field: Option<String>,
pub mapping_source: String,
}
/// Parsed arguments for `curate-fundamentals --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFundamentalsMongoArgs {
pub mongo: MongoCliOptions,
pub with_qm_financials_old: bool,
pub provider_mapping: PathBuf,
pub listing_venues: PathBuf,
pub out_dir: PathBuf,
pub financials_key_field: String,
pub financials_period_end_field: String,
pub financials_report_date_field: String,
pub financials_report_period_field: String,
pub financials_currency_field: String,
pub financials_revenue_field: Option<String>,
pub financials_net_income_field: Option<String>,
pub financials_operating_cash_flow_field: Option<String>,
pub financials_total_assets_field: Option<String>,
pub financials_total_equity_field: Option<String>,
pub financials_shares_outstanding_field: Option<String>,
pub fiscal_period: CurateFundamentalsFiscalPeriod,
pub filings_key_field: String,
pub filings_timefiled_field: String,
pub filings_form_type_field: String,
pub filings_filing_id_field: Option<String>,
pub filings_url_field: Option<String>,
pub mapping_source: String,
pub k: usize,
}
impl CurateFundamentalsMongoArgs {
pub(crate) fn to_file_args(&self) -> CurateFundamentalsArgs {
CurateFundamentalsArgs {
qm_financials: mongo_virtual_path(SourceCollection::QmFinancials),
qm_financials_old: self
.with_qm_financials_old
.then(|| mongo_virtual_path(SourceCollection::QmFinancialsOld)),
qm_filings: mongo_virtual_path(SourceCollection::QmFilings),
provider_mapping: self.provider_mapping.clone(),
listing_venues: self.listing_venues.clone(),
out_dir: self.out_dir.clone(),
financials_key_field: self.financials_key_field.clone(),
financials_period_end_field: self.financials_period_end_field.clone(),
financials_report_date_field: self.financials_report_date_field.clone(),
financials_report_period_field: self.financials_report_period_field.clone(),
financials_currency_field: self.financials_currency_field.clone(),
financials_revenue_field: self.financials_revenue_field.clone(),
financials_net_income_field: self.financials_net_income_field.clone(),
financials_operating_cash_flow_field: self
.financials_operating_cash_flow_field
.clone(),
financials_total_assets_field: self.financials_total_assets_field.clone(),
financials_total_equity_field: self.financials_total_equity_field.clone(),
financials_shares_outstanding_field: self.financials_shares_outstanding_field.clone(),
fiscal_period: self.fiscal_period.clone(),
filings_key_field: self.filings_key_field.clone(),
filings_timefiled_field: self.filings_timefiled_field.clone(),
filings_form_type_field: self.filings_form_type_field.clone(),
filings_filing_id_field: self.filings_filing_id_field.clone(),
filings_url_field: self.filings_url_field.clone(),
mapping_source: self.mapping_source.clone(),
k: self.k,
}
}
}
/// Parsed arguments for `curate-posts --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CuratePostsMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub timestamp_unit: CeoPostsTimestampUnit,
pub key_field: String,
pub spiel_id_field: String,
pub timestamp_field: String,
pub edited_field: String,
pub bot_field: String,
pub user_id_field: String,
pub text_field: String,
pub mapping_source: String,
}
/// Parsed arguments for `curate-macro --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateMacroMongoArgs {
pub mongo: MongoCliOptions,
pub series_map: PathBuf,
pub out_dir: PathBuf,
}
/// Parsed arguments for `curate-bars-1m --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateBars1mMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping_path: PathBuf,
pub out_dir: PathBuf,
pub mapping_source: String,
pub shard_count: usize,
pub known_at_micros: i64,
pub stream_options: BsonStreamOptions,
pub ilp_options: IlpWriterOptions,
}
impl CurateBars1mMongoArgs {
pub(crate) fn to_file_args(&self) -> CurateBars1mArgs {
CurateBars1mArgs {
intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M),
splits_path: mongo_virtual_path(SourceCollection::QmSplits),
provider_mapping_path: self.provider_mapping_path.clone(),
out_dir: self.out_dir.clone(),
mapping_source: self.mapping_source.clone(),
shard_count: self.shard_count,
known_at_micros: self.known_at_micros,
stream_options: self.stream_options,
ilp_options: self.ilp_options,
}
}
}
/// Parsed arguments for `curate-qm-bars-1m --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateQmBars1mMongoArgs {
pub mongo: MongoCliOptions,
pub provider_mapping_path: PathBuf,
pub out_dir: PathBuf,
pub mapping_source: String,
pub shard_count: usize,
pub known_at_micros: i64,
pub stream_options: BsonStreamOptions,
pub ilp_options: IlpWriterOptions,
}
impl CurateQmBars1mMongoArgs {
pub(crate) fn to_file_args(&self) -> CurateQmBars1mArgs {
CurateQmBars1mArgs {
intraday_path: mongo_virtual_path(SourceCollection::QmIntraday),
provider_mapping_path: self.provider_mapping_path.clone(),
out_dir: self.out_dir.clone(),
mapping_source: self.mapping_source.clone(),
shard_count: self.shard_count,
known_at_micros: self.known_at_micros,
stream_options: self.stream_options,
ilp_options: self.ilp_options,
}
}
}
/// Parsed arguments for `curate-fx-1m --from-mongo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFx1mMongoArgs {
pub mongo: MongoCliOptions,
pub out_dir: PathBuf,
pub shard_count: usize,
pub stream_options: BsonStreamOptions,
pub ilp_options: IlpWriterOptions,
}
impl CurateFx1mMongoArgs {
pub(crate) fn to_file_args(&self) -> CurateFx1mArgs {
CurateFx1mArgs {
intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M),
out_dir: self.out_dir.clone(),
shard_count: self.shard_count,
stream_options: self.stream_options,
ilp_options: self.ilp_options,
}
}
}
fn mongo_virtual_path(collection: SourceCollection) -> PathBuf {
PathBuf::from(format!("mongodb://{}", collection.as_str()))
}
fn connect_and_validate_specs(
mongo: &MongoCliOptions,
checks: &[(SourceCollection, MongoReadSpec)],
) -> Result<ReadOnlyMongoClient, RunMongoCurateError> {
for (collection, spec) in checks {
spec.validate(*collection)
.map_err(RunMongoCurateError::Mongo)?;
}
mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo)
}
fn with_mongo_client<T, F>(
mongo: &MongoCliOptions,
checks: &[(SourceCollection, MongoReadSpec)],
f: F,
) -> Result<T, RunMongoCurateError>
where
F: FnOnce(&ReadOnlyMongoClient) -> Result<T, RunMongoCurateError>,
{
let client = connect_and_validate_specs(mongo, checks)?;
let result = f(&client);
client.shutdown();
result
}
fn unique_mapping_keys_for_source(
provider_mapping_path: &Path,
source: &str,
) -> Result<Vec<String>, RunCurateBarsError> {
let rows = load_provider_mapping_tsv(provider_mapping_path)?;
let mut keys = BTreeSet::new();
for row in rows {
if row.source == source {
keys.insert(row.source_id);
}
}
Ok(keys.into_iter().collect())
}
/// Streams `qmSplits`, `eodPrices`, and optional `qmPrices` directly from read-only MongoDB into
/// `bars_1d/year=YYYY/part.parquet`.
///
/// Note: `qmSplits` is always read without a date-range filter so cumulative post-bar split
/// factors remain exact even when `--date-gte` / `--date-lt` bounds `eodPrices`.
/// When `--limit` is not set, `eodPrices` and `qmPrices` are streamed in indexed `$in` key chunks
/// from `provider_mapping.tsv` so MongoDB scans only mapped US/CA symbols sequentially.
pub fn run_curate_bars_1d_mongo(
args: &CurateBars1dMongoArgs,
) -> Result<CurateBars1dRunReport, RunMongoCurateError> {
let splits_spec = MongoReadSpec {
batch_size: args.mongo.batch_size,
..MongoReadSpec::default()
};
let eod_spec = args.mongo.to_read_spec(None, true);
let qm_spec = args.mongo.to_read_spec(None, true);
let mut checks = vec![
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::EodPrices, eod_spec.clone()),
];
if args.with_qm_prices {
checks.push((SourceCollection::QmPrices, qm_spec.clone()));
}
let client = connect_and_validate_specs(&args.mongo, &checks)?;
let use_key_chunks = args.mongo.limit.is_none();
let eod_keys = if use_key_chunks {
unique_mapping_keys_for_source(&args.provider_mapping, "eod")
.map_err(RunMongoCurateError::Bars)?
} else {
Vec::new()
};
let qm_keys = if use_key_chunks && args.with_qm_prices {
unique_mapping_keys_for_source(&args.provider_mapping, "qm")
.map_err(RunMongoCurateError::Bars)?
} else {
Vec::new()
};
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let eod_path = mongo_virtual_path(SourceCollection::EodPrices);
if use_key_chunks {
let eod_reader = client
.open_raw_cursor_for_keys(SourceCollection::EodPrices, &eod_spec, &eod_keys, 250)
.map_err(RunMongoCurateError::Mongo)?;
let qm_input = if args.with_qm_prices {
let reader = client
.open_raw_cursor_for_keys(SourceCollection::QmPrices, &qm_spec, &qm_keys, 250)
.map_err(RunMongoCurateError::Mongo)?;
Some((mongo_virtual_path(SourceCollection::QmPrices), reader))
} else {
None
};
run_curate_bars_1d_with_readers(
&args.provider_mapping,
&args.listing_currencies,
(&splits_path, splits_reader),
(&eod_path, eod_reader),
qm_input,
&args.out_dir,
args.rel_tolerance,
args.threads,
)
.map_err(RunMongoCurateError::Bars)
} else {
let eod_reader = client
.open_raw_cursor(SourceCollection::EodPrices, &eod_spec)
.map_err(RunMongoCurateError::Mongo)?;
let qm_input = if args.with_qm_prices {
let reader = client
.open_raw_cursor(SourceCollection::QmPrices, &qm_spec)
.map_err(RunMongoCurateError::Mongo)?;
Some((mongo_virtual_path(SourceCollection::QmPrices), reader))
} else {
None
};
run_curate_bars_1d_with_readers(
&args.provider_mapping,
&args.listing_currencies,
(&splits_path, splits_reader),
(&eod_path, eod_reader),
qm_input,
&args.out_dir,
args.rel_tolerance,
args.threads,
)
.map_err(RunMongoCurateError::Bars)
}
};
client.shutdown();
result
}
/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB into
/// `adj_factors/part.parquet` (retrospective or point-in-time fenced).
pub fn run_curate_adj_factors_mongo(
args: &CurateAdjFactorsMongoArgs,
) -> Result<CurateAdjFactorsRunReport, RunMongoCurateError> {
let splits_spec = args.mongo.to_read_spec(None, true);
let dividends_spec = args.mongo.to_read_spec(None, true);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::QmDividends, dividends_spec.clone()),
],
)?;
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let dividends_reader = client
.open_raw_cursor(SourceCollection::QmDividends, &dividends_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let dividends_path = mongo_virtual_path(SourceCollection::QmDividends);
run_curate_adj_factors_with_readers(
&args.provider_mapping,
&args.bars_1d_dir,
(&splits_path, splits_reader),
(&dividends_path, dividends_reader),
&args.out_dir,
args.fence,
)
.map_err(RunMongoCurateError::Adj)
};
client.shutdown();
result
}
/// Streams `qmSplits` and `qmDividends` directly from read-only MongoDB alongside optional
/// Pass 6 `delistings.tsv` into `corporate_actions/part.parquet`.
pub fn run_curate_corporate_actions_mongo(
args: &CurateCorporateActionsMongoArgs,
) -> Result<CurateCorporateActionsRunReport, RunMongoCurateError> {
let splits_spec = args.mongo.to_read_spec(None, false);
let dividends_spec = args.mongo.to_read_spec(None, false);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::QmDividends, dividends_spec.clone()),
],
)?;
let result = {
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
let dividends_reader = client
.open_raw_cursor(SourceCollection::QmDividends, &dividends_spec)
.map_err(RunMongoCurateError::Mongo)?;
let splits_path = mongo_virtual_path(SourceCollection::QmSplits);
let dividends_path = mongo_virtual_path(SourceCollection::QmDividends);
run_curate_corporate_actions_with_readers(
&args.provider_mapping,
args.delistings.as_deref(),
(&splits_path, splits_reader),
(&dividends_path, dividends_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::CorporateActions)
};
client.shutdown();
result
}
/// Streams `eodPrices` (`eodSearchCode == "CAD.FOREX"`) and `teMarketData` (`teSymbol == te_symbol`)
/// directly from read-only MongoDB into `fx_1d/part.parquet`.
pub fn run_curate_fx_1d_mongo(
args: &CurateFx1dMongoArgs,
) -> Result<CurateFx1dRunReport, RunMongoCurateError> {
let eod_spec = args
.mongo
.to_read_spec(Some(EOD_CAD_FOREX_CODE.to_owned()), false);
let te_spec = args.mongo.to_read_spec(Some(args.te_symbol.clone()), false);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::EodPrices, eod_spec.clone()),
(SourceCollection::TeMarketData, te_spec.clone()),
],
)?;
let result = {
let eod_reader = client
.open_raw_cursor(SourceCollection::EodPrices, &eod_spec)
.map_err(RunMongoCurateError::Mongo)?;
let te_reader = client
.open_raw_cursor(SourceCollection::TeMarketData, &te_spec)
.map_err(RunMongoCurateError::Mongo)?;
let eod_path = mongo_virtual_path(SourceCollection::EodPrices);
let te_path = mongo_virtual_path(SourceCollection::TeMarketData);
run_curate_fx_1d_with_readers(
(&eod_path, eod_reader),
(&te_path, te_reader),
&args.te_symbol,
&args.out_dir,
)
.map_err(RunMongoCurateError::Fx)
};
client.shutdown();
result
}
/// Streams `ceoShorts` directly from read-only MongoDB into `shorts/part.parquet`.
pub fn run_curate_shorts_mongo(
args: &CurateShortsMongoArgs,
) -> Result<CurateShortsRunReport, RunMongoCurateError> {
let shorts_spec = args.mongo.to_read_spec(None, false);
let client = connect_and_validate_specs(
&args.mongo,
&[(SourceCollection::CeoShorts, shorts_spec.clone())],
)?;
let fields = CeoShortsFieldNames {
key: args.key_field.as_str(),
report_date: args.report_date_field.as_str(),
shares_short: args.shares_short_field.as_str(),
net_change: args.net_change_field.as_deref(),
pct_float: args.pct_float_field.as_deref(),
};
let result = {
let shorts_reader = client
.open_raw_cursor(SourceCollection::CeoShorts, &shorts_spec)
.map_err(RunMongoCurateError::Mongo)?;
let shorts_path = mongo_virtual_path(SourceCollection::CeoShorts);
run_curate_shorts_with_reader(
&args.provider_mapping,
&args.mapping_source,
&fields,
(&shorts_path, shorts_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::Shorts)
};
client.shutdown();
result
}
/// Streams `qmFilings` and `qmEarnings` directly from read-only MongoDB into
/// `events/year=YYYY/part.parquet`.
pub fn run_curate_events_mongo(
args: &CurateEventsMongoArgs,
) -> Result<CurateEventsRunReport, RunMongoCurateError> {
let filings_spec = args
.mongo
.to_read_spec_for_collection(SourceCollection::QmFilings, None, true);
let earnings_spec = args
.mongo
.to_read_spec_for_collection(SourceCollection::QmEarnings, None, true);
let client = connect_and_validate_specs(
&args.mongo,
&[
(SourceCollection::QmFilings, filings_spec.clone()),
(SourceCollection::QmEarnings, earnings_spec.clone()),
],
)?;
let filings_fields = QmFilingsFieldNames {
key: args.filings_key_field.as_str(),
timefiled: args.filings_timefiled_field.as_str(),
form_type: args.filings_form_type_field.as_str(),
filing_id: args.filings_filing_id_field.as_deref(),
url: args.filings_url_field.as_deref(),
};
let earnings_fields = QmEarningsFieldNames {
key: args.earnings_key_field.as_str(),
report_date: args.earnings_report_date_field.as_str(),
announce_time: args.earnings_announce_time_field.as_str(),
fiscal_period_end: args.earnings_fiscal_period_end_field.as_deref(),
actual_eps: args.earnings_actual_eps_field.as_deref(),
revenue: args.earnings_revenue_field.as_deref(),
};
let result = {
let filings_reader = client
.open_raw_cursor(SourceCollection::QmFilings, &filings_spec)
.map_err(RunMongoCurateError::Mongo)?;
let earnings_reader = client
.open_raw_cursor(SourceCollection::QmEarnings, &earnings_spec)
.map_err(RunMongoCurateError::Mongo)?;
let filings_path = mongo_virtual_path(SourceCollection::QmFilings);
let earnings_path = mongo_virtual_path(SourceCollection::QmEarnings);
run_curate_events_with_readers(
&args.provider_mapping,
&args.mapping_source,
&filings_fields,
&earnings_fields,
(&filings_path, filings_reader),
(&earnings_path, earnings_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::Events)
};
client.shutdown();
result
}
pub(crate) fn fundamentals_read_specs(
args: &CurateFundamentalsMongoArgs,
) -> (MongoReadSpec, Option<MongoReadSpec>, MongoReadSpec) {
let fin_spec = args
.mongo
.to_read_spec_for_collection(SourceCollection::QmFinancials, None, true);
let fin_old_spec = args.with_qm_financials_old.then(|| {
args.mongo
.to_read_spec_for_collection(SourceCollection::QmFinancialsOld, None, true)
});
let filings_spec = MongoReadSpec {
batch_size: args.mongo.batch_size,
..MongoReadSpec::default()
};
(fin_spec, fin_old_spec, filings_spec)
}
pub(crate) fn run_curate_fundamentals_mongo_with_readers<RF: io::Read, RO: io::Read, RL: io::Read>(
args: &CurateFundamentalsMongoArgs,
financials_reader: RF,
financials_old_reader: Option<RO>,
filings_reader: RL,
) -> Result<CurateFundamentalsRunReport, RunMongoCurateError> {
let file_args = args.to_file_args();
run_curate_fundamentals_with_optional_old_readers(
&file_args,
financials_reader,
financials_old_reader,
filings_reader,
)
.map_err(RunMongoCurateError::Fundamentals)
}
/// Streams `qmFinancials`, optional `qmFinancials-old`, and `qmFilings` directly from read-only
/// MongoDB into `fundamentals_pit/year=YYYY/part.parquet`.
///
/// `qmFilings` is always read without date-range or `--limit` caps so retained financial
/// observations (including restatements) never lose their matching filing timestamps when
/// `--limit` samples `qmFinancials` / `qmFinancials-old`.
pub fn run_curate_fundamentals_mongo(
args: &CurateFundamentalsMongoArgs,
) -> Result<CurateFundamentalsRunReport, RunMongoCurateError> {
let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(args);
let mut checks = vec![
(SourceCollection::QmFinancials, fin_spec.clone()),
(SourceCollection::QmFilings, filings_spec.clone()),
];
if let Some(old_spec) = &fin_old_spec {
checks.push((SourceCollection::QmFinancialsOld, old_spec.clone()));
}
with_mongo_client(&args.mongo, &checks, |client| {
let fin_reader = client
.open_raw_cursor(SourceCollection::QmFinancials, &fin_spec)
.map_err(RunMongoCurateError::Mongo)?;
let fin_old_reader = if let Some(old_spec) = &fin_old_spec {
Some(
client
.open_raw_cursor(SourceCollection::QmFinancialsOld, old_spec)
.map_err(RunMongoCurateError::Mongo)?,
)
} else {
None
};
let filings_reader = client
.open_raw_cursor(SourceCollection::QmFilings, &filings_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_fundamentals_mongo_with_readers(args, fin_reader, fin_old_reader, filings_reader)
})
}
pub(crate) fn posts_read_spec(args: &CuratePostsMongoArgs) -> MongoReadSpec {
args.mongo
.to_read_spec_for_collection(SourceCollection::CeoPosts, None, true)
}
pub(crate) fn run_curate_posts_mongo_with_reader<R: io::Read>(
args: &CuratePostsMongoArgs,
posts_reader: R,
) -> Result<CuratePostsRunReport, RunMongoCurateError> {
let fields = CeoPostsFieldNames {
key: args.key_field.as_str(),
spiel_id: args.spiel_id_field.as_str(),
timestamp: args.timestamp_field.as_str(),
edited: args.edited_field.as_str(),
bot: args.bot_field.as_str(),
user_id: args.user_id_field.as_str(),
text: args.text_field.as_str(),
};
let posts_path = mongo_virtual_path(SourceCollection::CeoPosts);
run_curate_posts_with_reader(
&args.provider_mapping,
&args.mapping_source,
&fields,
args.timestamp_unit,
(&posts_path, posts_reader),
&args.out_dir,
)
.map_err(RunMongoCurateError::Posts)
}
/// Streams `ceoPosts` directly from read-only MongoDB into `events/year=YYYY/part-posts.parquet`.
pub fn run_curate_posts_mongo(
args: &CuratePostsMongoArgs,
) -> Result<CuratePostsRunReport, RunMongoCurateError> {
let posts_spec = posts_read_spec(args);
with_mongo_client(
&args.mongo,
&[(SourceCollection::CeoPosts, posts_spec.clone())],
|client| {
let posts_reader = client
.open_raw_cursor(SourceCollection::CeoPosts, &posts_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_posts_mongo_with_reader(args, posts_reader)
},
)
}
pub(crate) fn macro_read_spec(args: &CurateMacroMongoArgs) -> MongoReadSpec {
args.mongo
.to_read_spec_for_collection(SourceCollection::TeData, None, true)
}
pub(crate) fn run_curate_macro_mongo_with_reader<R: io::Read>(
args: &CurateMacroMongoArgs,
te_data_reader: R,
) -> Result<CurateMacroRunReport, RunMongoCurateError> {
let te_path = mongo_virtual_path(SourceCollection::TeData);
run_curate_macro_from_reader(&te_path, te_data_reader, &args.series_map, &args.out_dir)
.map_err(RunMongoCurateError::Macro)
}
/// Streams `teData` directly from read-only MongoDB alongside caller-owned `series_map.tsv`
/// into `macro/part.parquet`.
pub fn run_curate_macro_mongo(
args: &CurateMacroMongoArgs,
) -> Result<CurateMacroRunReport, RunMongoCurateError> {
let te_spec = macro_read_spec(args);
with_mongo_client(
&args.mongo,
&[(SourceCollection::TeData, te_spec.clone())],
|client| {
let te_reader = client
.open_raw_cursor(SourceCollection::TeData, &te_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_macro_mongo_with_reader(args, te_reader)
},
)
}
pub(crate) fn bars_1m_read_specs(args: &CurateBars1mMongoArgs) -> (MongoReadSpec, MongoReadSpec) {
let splits_spec = MongoReadSpec {
batch_size: args.mongo.batch_size,
..MongoReadSpec::default()
};
let intraday_spec =
args.mongo
.to_read_spec_for_collection(SourceCollection::EodIntraday1M, None, true);
(splits_spec, intraday_spec)
}
pub(crate) fn run_curate_bars_1m_mongo_with_readers<RI: io::Read, RS: io::Read>(
args: &CurateBars1mMongoArgs,
intraday_reader: RI,
splits_reader: RS,
) -> Result<CurateBars1mRunReport, RunMongoCurateError> {
let file_args = args.to_file_args();
run_curate_bars_1m_from_readers_to_dir(&file_args, intraday_reader, splits_reader)
.map_err(RunMongoCurateError::Bars1m)
}
/// Streams `qmSplits` and `eodIntraday1M` directly from read-only MongoDB into
/// `<out_dir>/bars_1m.shard-<NN>.ilp`.
///
/// `qmSplits` is always read without a date-range filter so post-bar cumulative split factors
/// remain exact. When `--limit` is not set, `eodIntraday1M` is streamed in indexed `$in` key
/// chunks (`250` keys/chunk) derived from `provider_mapping.tsv`.
pub fn run_curate_bars_1m_mongo(
args: &CurateBars1mMongoArgs,
) -> Result<CurateBars1mRunReport, RunMongoCurateError> {
let (splits_spec, intraday_spec) = bars_1m_read_specs(args);
with_mongo_client(
&args.mongo,
&[
(SourceCollection::QmSplits, splits_spec.clone()),
(SourceCollection::EodIntraday1M, intraday_spec.clone()),
],
|client| {
let use_key_chunks = args.mongo.limit.is_none();
let eod_keys = if use_key_chunks {
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
.map_err(|e| RunMongoCurateError::Bars1m(RunCurateBars1mError::LoadReference(e)))?
} else {
Vec::new()
};
let splits_reader = client
.open_raw_cursor(SourceCollection::QmSplits, &splits_spec)
.map_err(RunMongoCurateError::Mongo)?;
if use_key_chunks {
let intraday_reader = client
.open_raw_cursor_for_keys(
SourceCollection::EodIntraday1M,
&intraday_spec,
&eod_keys,
250,
)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
} else {
let intraday_reader = client
.open_raw_cursor(SourceCollection::EodIntraday1M, &intraday_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader)
}
},
)
}
pub(crate) fn qm_bars_1m_read_spec(args: &CurateQmBars1mMongoArgs) -> MongoReadSpec {
args.mongo
.to_read_spec_for_collection(SourceCollection::QmIntraday, None, true)
}
pub(crate) fn run_curate_qm_bars_1m_mongo_with_reader<R: io::Read>(
args: &CurateQmBars1mMongoArgs,
intraday_reader: R,
) -> Result<CurateQmBars1mRunReport, RunMongoCurateError> {
let file_args = args.to_file_args();
run_curate_qm_bars_1m_from_reader_to_dir(&file_args, intraday_reader)
.map_err(RunMongoCurateError::QmBars1m)
}
/// Streams `qmIntraday` directly from read-only MongoDB into
/// `<out_dir>/bars_1m_qm.shard-<NN>.ilp`.
///
/// When `--limit` is not set, `qmIntraday` is streamed in indexed `$in` key chunks (`250`
/// keys/chunk) derived from `provider_mapping.tsv`.
pub fn run_curate_qm_bars_1m_mongo(
args: &CurateQmBars1mMongoArgs,
) -> Result<CurateQmBars1mRunReport, RunMongoCurateError> {
let intraday_spec = qm_bars_1m_read_spec(args);
with_mongo_client(
&args.mongo,
&[(SourceCollection::QmIntraday, intraday_spec.clone())],
|client| {
let use_key_chunks = args.mongo.limit.is_none();
let qm_keys = if use_key_chunks {
unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source)
.map_err(|e| {
RunMongoCurateError::QmBars1m(RunCurateQmBars1mError::LoadReference(e))
})?
} else {
Vec::new()
};
if use_key_chunks {
let intraday_reader = client
.open_raw_cursor_for_keys(
SourceCollection::QmIntraday,
&intraday_spec,
&qm_keys,
250,
)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
} else {
let intraday_reader = client
.open_raw_cursor(SourceCollection::QmIntraday, &intraday_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader)
}
},
)
}
pub(crate) fn fx_1m_read_spec(args: &CurateFx1mMongoArgs) -> MongoReadSpec {
args.mongo.to_read_spec_for_collection(
SourceCollection::EodIntraday1M,
Some(EOD_CAD_FOREX_CODE.to_owned()),
true,
)
}
pub(crate) fn run_curate_fx_1m_mongo_with_reader<R: io::Read>(
args: &CurateFx1mMongoArgs,
intraday_reader: R,
) -> Result<CurateFx1mRunReport, RunMongoCurateError> {
let file_args = args.to_file_args();
run_curate_fx_1m_from_reader_to_dir(&file_args, intraday_reader)
.map_err(RunMongoCurateError::Fx1m)
}
/// Streams `eodIntraday1M` (`eodSearchCode == "CAD.FOREX"`) directly from read-only MongoDB into
/// `<out_dir>/fx_1m.shard-<NN>.ilp`.
pub fn run_curate_fx_1m_mongo(
args: &CurateFx1mMongoArgs,
) -> Result<CurateFx1mRunReport, RunMongoCurateError> {
let fx_spec = fx_1m_read_spec(args);
with_mongo_client(
&args.mongo,
&[(SourceCollection::EodIntraday1M, fx_spec.clone())],
|client| {
let intraday_reader = client
.open_raw_cursor(SourceCollection::EodIntraday1M, &fx_spec)
.map_err(RunMongoCurateError::Mongo)?;
run_curate_fx_1m_mongo_with_reader(args, intraday_reader)
},
)
}
/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly).
#[allow(dead_code)]
fn _assert_path_ref(path: &Path) -> &Path {
path
}
#[cfg(test)]
#[path = "run_mongo_tests.rs"]
mod tests;