503 lines
18 KiB
Rust
503 lines
18 KiB
Rust
//! Direct read-only MongoDB streaming runners for all six M1 `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_*_with_readers` pipelines with zero intermediate `.bson`
|
|
//! scratch files.
|
|
|
|
use std::collections::BTreeSet;
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use crate::bson_ceo_shorts::CeoShortsFieldNames;
|
|
use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames};
|
|
use crate::curate_adj::AdjPointInTimeFence;
|
|
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_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_fx::{
|
|
run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE,
|
|
};
|
|
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),
|
|
}
|
|
|
|
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}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
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),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
}
|
|
|
|
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 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, ÷nds_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),
|
|
(÷nds_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, ÷nds_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),
|
|
(÷nds_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
|
|
}
|
|
|
|
/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly).
|
|
#[allow(dead_code)]
|
|
fn _assert_path_ref(path: &Path) -> &Path {
|
|
path
|
|
}
|