DataService API Reference
tradingbot.utils.data_service.DataService()
Service for fetching and managing market data from Yahoo Finance and database.
Caching Behavior:
- Instance-level cache: self.data and self.datasettings cache the last fetched
(interval, period) combination per DataService instance. This is useful for
repeated calls within the same instance but does not persist across instances.
- Database persistence: For cross-run data reuse (e.g., in hyperparameter tuning
or multiple backtests), set save_to_db=True when fetching data. Subsequent
calls (even from new DataService instances) will check the database first and
only fetch from yfinance if data is missing or stale (older than
FRESHNESS_TOLERANCE_MINUTES).
- Best practice: Use save_to_db=True for historical backtests and tuning to
enable efficient data reuse across multiple runs.
Initialize the data service.
Source code in tradingbot/utils/data_service.py
add_pd_df_to_db(df: pd.DataFrame, interval: str = '1d') -> None
Add DataFrame rows to database, skipping duplicates.
Only inserts rows with timestamps newer than the latest stored for this (symbol, interval).
interval is required for correctness, not bookkeeping: the high-water
mark below used to be taken across all bar sizes for the symbol. For a
symbol cached at 1m that mark is always minutes old, so every daily row
looked "not newer" and was dropped — which is why ^XAU accumulated 74k
one-minute rows and zero daily ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with columns: symbol, timestamp, open, high, low, close, volume |
required |
interval
|
str
|
Bar size these rows were fetched at (e.g. "1m", "1d") |
'1d'
|
Source code in tradingbot/utils/data_service.py
convert_to_wide_format(data_long: pd.DataFrame, value_column: str = 'close', fill_method: str = 'both') -> pd.DataFrame
Convert long-format DataFrame to wide format for portfolio optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_long
|
DataFrame
|
DataFrame in long format with columns: symbol, timestamp, open, high, low, close, volume |
required |
value_column
|
str
|
Column name to use as values (default: "close") |
'close'
|
fill_method
|
str
|
How to handle missing values - "forward", "backward", "both", or None |
'both'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with timestamp as index, symbols as columns, and specified value column as values |
Source code in tradingbot/utils/data_service.py
get_data_from_db(symbol: str, interval: str = '1d', start_date: pd.Timestamp | None = None, end_date: pd.Timestamp | None = None) -> pd.DataFrame
Load data from database for a symbol at a given bar size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol to query |
required |
interval
|
str
|
Bar size to read, e.g. "1m", "1d". Rows of other intervals are never returned — mixing them corrupts every downstream TA indicator (see HistoricData's docstring). |
'1d'
|
start_date
|
Timestamp | None
|
Optional start date (timezone-aware UTC) |
None
|
end_date
|
Timestamp | None
|
Optional end date (timezone-aware UTC) |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: symbol, interval, timestamp, open, high, low, close, volume |
DataFrame
|
Empty DataFrame if no data found |
Source code in tradingbot/utils/data_service.py
get_latest_price(symbol: str, cached_data: pd.DataFrame | None = None) -> float
Get the latest price for a symbol, using TTL cache and checking DB first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol to get price for |
required |
cached_data
|
DataFrame | None
|
Optional cached DataFrame to check first |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Latest price as float |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no price data is available |
Source code in tradingbot/utils/data_service.py
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 | |
get_latest_prices_batch(symbols: list[str]) -> dict[str, float]
Get latest prices for multiple symbols in a single DB query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
List of trading symbols to get prices for |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary mapping symbol to latest price |
Source code in tradingbot/utils/data_service.py
get_yf_data(symbol: str, interval: str = '1m', period: str = '1d', save_to_db: bool = False, use_cache: bool = True) -> pd.DataFrame
Fetch market data from Yahoo Finance, checking database first.
Data fetching strategy: 1. If use_cache=True and instance cache matches (interval, period), return cached data 2. Otherwise, check database for existing data in the requested date range 3. If DB data exists and is fresh (within FRESHNESS_TOLERANCE_MINUTES), use it 4. If DB data is missing or stale, fetch from yfinance 5. If save_to_db=True, save fetched data to database for future reuse
Note: For repeated backtests or hyperparameter tuning, set save_to_db=True on the first fetch to populate the database. Subsequent fetches (even from new DataService instances) will reuse DB data and avoid yfinance calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol |
required |
interval
|
str
|
Data interval (e.g., "1m", "5m", "1h", "1d") |
'1m'
|
period
|
str
|
Data period (e.g., "1d", "5d", "1mo", "1y") |
'1d'
|
save_to_db
|
bool
|
Whether to save fetched data to database. Set to True for historical backtests to enable data reuse across runs. |
False
|
use_cache
|
bool
|
Whether to use instance-level cached data if available. Cache is per-instance and does not persist across instances. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: symbol, timestamp, open, high, low, close, volume |
Source code in tradingbot/utils/data_service.py
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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
get_yf_data_multiple(symbols: list[str], interval: str = '1d', period: str = '3mo', save_to_db: bool = True) -> pd.DataFrame
Fetch market data for multiple symbols efficiently, checking database first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
List of trading symbols to fetch |
required |
interval
|
str
|
Data interval (e.g., "1m", "5m", "1h", "1d") |
'1d'
|
period
|
str
|
Data period (e.g., "1d", "5d", "1mo", "3mo", "1y") |
'3mo'
|
save_to_db
|
bool
|
Whether to save fetched data to database for each symbol |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: symbol, timestamp, open, high, low, close, volume |
DataFrame
|
Combined data from all symbols in long format |
Source code in tradingbot/utils/data_service.py
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |
get_yf_data_with_ta(symbol: str, interval: str = '1m', period: str = '1d', save_to_db: bool = False, features: list[str] | None = None) -> pd.DataFrame
Fetch market data with technical analysis indicators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Trading symbol |
required |
interval
|
str
|
Data interval (e.g., "1m", "5m", "1h", "1d") |
'1m'
|
period
|
str
|
Data period (e.g., "1d", "5d", "1mo", "1y") |
'1d'
|
save_to_db
|
bool
|
Whether to save fetched data to database |
False
|
features
|
list[str] | None
|
Optional list of specific TA indicator column names to keep. If provided, drops other TA columns to save memory. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with market data and technical analysis features |