controller.py
1"""Research behavior over injected operations and resource factories; no Platform construction."""23from __future__ import annotations45from abc import ABC, abstractmethod6from dataclasses import asdict7from pathlib import Path8from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast910from sim_platform.domain.models import ContractError11from sim_platform.domain.json_values import copy_json12from sim_platform.market import load_news13from sim_platform.decisions.policy.contracts import make_policy14from .reports import ExportWriter, Report, run_report, export_run15from .views import SessionView, session_view16from .queries import (17 NEWS_VIEW_LIMIT,18 TRADE_VIEW_LIMIT,19 ResearchQueries,20 bar_view_limit,21 daily_closes,22 symbol_markets,23)24from sim_platform.resources import cleanup, cleanup_after_error2526if TYPE_CHECKING: # Annotation only.27 from sim_platform.decisions.agent.runner import AgentDecisionRunner28 from sim_platform.decisions.policy.live.runner import LivePolicyDecisionRunner29 from sim_platform.decisions.policy.runner import PolicyDecisionRunner30 from sim_platform.execution import ExecutionConfig31 from sim_platform.experiments.scheduling.clock import SharedExperimentClock32 from sim_platform.market.native import PathInput33 from sim_platform.market.prepared.session import PreparedSession3435 # The runner a controller owns after create_experiment/start.36 ResearchRunner = Union[PolicyDecisionRunner, LivePolicyDecisionRunner, AgentDecisionRunner]3738# Default symbol for a research load.39DEFAULT_SYMBOL = 'AAPL'40# 09:30 Eastern, the regular session open, in nanoseconds after midnight; the same41# value as market.prepared.session.REGULAR_OPEN_NS (not imported to avoid loading it).42REGULAR_OPEN_NS = 34_200_000_000_00043# Sleep between preparation steps while a synchronous caller waits.44PREPARE_POLL_SECONDS = 0.00545# Defaults kept for the prepare_tick signature; preparation runs the market's own budget.46PREPARE_TICK_EVENTS = 500047PREPARE_TICK_BUDGET_SECONDS = 0.03548# Starting cash for the demo account, in money-scale units.49DEMO_ACCOUNT_CASH = 100_000_0005051# The selected data source: 'path', 'bytes', 'mtime_ns', 'news_path',52# 'news_identity', 'allow_implicit_eof'; after preparation also 'prepared',53# 'start_origin', 'start_mode', 'start_time_ns'; at creation 'execution_mode' and,54# for Agents, 'symbol', 'source_manifest_ref', 'experiment_start_ns'.55SourceDescriptor = Dict[str, Any]56# Preparation progress: 'status' ('preparing', 'ready', 'failed' or 'cancelled'),57# 'start_mode', 'target_time_ns' and, while preparing, 'progress'.58Preparation = Dict[str, Any]59# Market position right after preparation: 'sequence' and 'time_ns'.60PreparedOrigin = Dict[str, int]616263# Backward-compatible name for existing research callers.64policy_for = make_policy656667def experiment_universe(68 path: PathInput, symbols: Sequence[str], paths: Optional[Sequence[PathInput]]69) -> List[Tuple[str, Path]]:70 """(symbol, source) pairs of an experiment on several symbols, in universe order."""71 if len(symbols) < 2 or len(set(symbols)) != len(symbols):72 raise ContractError('choose two or more different symbols')73 sources = list(paths) if paths else [path] * len(symbols)74 if len(sources) != len(symbols):75 raise ContractError('give one source per symbol, or one ITCH file for all')76 return [(s, Path(p).expanduser().resolve()) for s, p in zip(symbols, sources)]777879def check_start_date(start_date: Any, start_mode: str, time_of_day: Any) -> None:80 """A dated custom start needs 'YYYY-MM-DD' and a time of day below 24 hours."""81 from datetime import date82 from sim_platform.market.models import DAY_NS8384 if start_mode != 'custom':85 raise ContractError('a start date needs the custom start mode')86 try:87 date.fromisoformat(start_date)88 except (TypeError, ValueError) as exc:89 raise ContractError('start date must be YYYY-MM-DD') from exc90 if not 0 <= time_of_day < DAY_NS:91 raise ContractError('with a start date, the start time is a time of day')929394def dated_start(calendar: Optional[Dict[str, Any]], start_date: str, time_of_day: int) -> int:95 """Market time of a time of day on a date of a multi-day price-bar recording."""96 from datetime import date97 from sim_platform.market.models import DAY_NS9899 if not calendar or not calendar.get('start_date'):100 raise ContractError('a start date needs a price-bar recording, which has dates')101 days = (date.fromisoformat(start_date) - date.fromisoformat(calendar['start_date'])).days102 if days < 0:103 raise ContractError('start date is before the recording\'s first day')104 return days * DAY_NS + time_of_day105106107def book_matches(requested: Any, prepared: Any) -> bool:108 """Whether a prepared source already has the requested synthetic-book options."""109 from sim_platform.market.prepared.bars import book_options110111 try:112 return book_options(requested) == prepared113 except ContractError:114 return False115116117class ResearchController(ABC):118 """Shared source preparation, experiment lifecycle and report ownership.119120 Platform selects PolicyResearchController or AgentResearchController; the121 base contains no policy/agent setup or specialized action implementation.122 Platform registers the controller as a root resource. The controller owns the123 market it prepares and the runner it creates, replaces both when another source124 is loaded, and on close() closes the runner, archives and closes the market.125126 Args:127 operations: DatabaseOperations from the application package (not yet typed).128 market_factory: Creates an unloaded prepared market for a symbol and, for a129 price-bar recording, optional book options (``market_factory(symbol, book)``).130 files: DatasetFiles adapter from the persistence package (not yet typed).131 export_writer: Atomic file writer used by export().132 """133134 def __init__(135 self,136 operations: Any,137 *,138 market_factory: Callable[..., PreparedSession],139 files: Any,140 export_writer: ExportWriter,141 ) -> None:142 self.app = operations143 self._files, self._export_writer = files, export_writer144 self._queries = ResearchQueries()145 self._market_factory = market_factory146 self._market_archived = False147 self._on_close: Callable[[], None] = lambda: None148 self.market: Optional[PreparedSession] = None149 self.runner: Optional[ResearchRunner] = None150 self.profile: Optional[str] = None151 self.run_id: Optional[str] = None152 self.viewed_run: Optional[str] = None153 self.source: Optional[SourceDescriptor] = None154 self.preparation: Optional[Preparation] = None155 self._prepared_origin: Optional[PreparedOrigin] = None156 self._closed = False157 self._execution_mode: Optional[str] = None158159 # Typed views of state set by an earlier phase (load, prepare). They only cast and160 # do not check, so a call in the wrong phase fails as the plain attribute would.161 @property162 def _loaded_market(self) -> PreparedSession:163 return cast('PreparedSession', self.market)164165 @property166 def _current_preparation(self) -> Preparation:167 return cast(Preparation, self.preparation)168169 @property170 def _current_source(self) -> SourceDescriptor:171 return cast(SourceDescriptor, self.source)172173 @property174 def execution_mode(self) -> Optional[str]:175 """Selected at experiment creation; the research entry has no default mode."""176 return self._execution_mode177178 def on_close(self, callback: Callable[[], None]) -> None:179 self._on_close = callback180181 def _check_open(self) -> None:182 if self._closed:183 raise ContractError('research controller is closed')184185 def catalog(self, profile: Optional[str] = None) -> Dict[str, Any]:186 """List profiles and, for ``profile`` (default: the first), its accounts and runs."""187 self._check_open()188 profiles = self.app.profiles()189 if profile is None and profiles:190 profile = profiles[0]['id']191 return dict(192 profiles=profiles,193 profile=profile,194 accounts=self.app.accounts(profile) if profile else [],195 runs=(196 [197 {k: r[k] for k in ('id', 'account_id', 'maker_id', 'status', 'time_ns')}198 for r in self.app.runs(profile, include_records=False)199 ]200 if profile201 else []202 ),203 )204205 def create_profile(self, name: str) -> str:206 self._check_open()207 return self.app.create_profile(name)208209 def create_account(self, profile: str, name: str, cash: int) -> str:210 self._check_open()211 return self.app.create_account(profile, name, cash)212213 def _active(self) -> bool:214 return self.runner is not None and self.runner.active215216 @property217 def active(self) -> bool:218 return self._active()219220 def _news_identity(self, news: Optional[PathInput]) -> Optional[Dict[str, Any]]:221 return self._files.identity(news) if news else None222223 def view(self) -> SessionView:224 value = session_view(self._queries.capture(self))225 mode = (226 (value.get("source") or {}).get("execution_mode")227 if self.viewed_run228 else self._execution_mode229 )230 return dict(value, execution_mode=mode)231232 def _archive(self) -> None:233 """Save the market tail with the run, once after the runner has finished."""234 if (235 not self.runner236 or not self.market237 or not self.runner.archive_ready238 or self.market.status in ('failed', 'closed')239 ):240 return241 if not self.runner.active and self._market_archived:242 return243 archive = dict(244 time_ns=self.market.time_ns,245 snapshot=asdict(self.market.snapshot),246 trades=[asdict(t) for t in self.market.trades(limit=TRADE_VIEW_LIMIT)],247 bars=[asdict(b) for b in self.market.bars(limit=bar_view_limit(self.market))],248 news=[asdict(n) for n in self.market.news(limit=NEWS_VIEW_LIMIT)],249 daily_closes=daily_closes(self.market),250 )251 # Several symbols: every symbol's book, bars and daily closes, so the result page252 # can value the whole account. Absent for one symbol, whose archive is unchanged.253 markets = symbol_markets(self.market, closes=True)254 if markets:255 archive['markets'] = markets256 self.app.archive_market(self.profile, self.run_id, archive)257 if not self.runner.active:258 self._market_archived = True259260 def load(261 self,262 path: PathInput,263 symbol: str = DEFAULT_SYMBOL,264 news: Optional[PathInput] = None,265 allow_implicit_eof: bool = False,266 ) -> SessionView:267 """Synchronous research load; begin_prepare exposes cancellable progress."""268 return self._load_source(path, symbol, news, allow_implicit_eof, wait=True)269270 def _merged_market(271 self, universe: Sequence[Tuple[str, Path]], book: Optional[Dict[str, int]]272 ) -> Any:273 """One prepared market per symbol, merged; price-bar files share a first date."""274 from sim_platform.market.prepared.bars import is_bar_source, read_bars275 from sim_platform.market.prepared.merged import MergedMarket276277 bars = [is_bar_source(source) for _, source in universe]278 if any(bars) and not all(bars):279 raise ContractError('use either price-bar files or ITCH recordings for every symbol')280 origin = min(read_bars(source).start_date for _, source in universe) if all(bars) else None281 sessions = []282 try:283 for symbol, _ in universe:284 sessions.append(285 self._market_factory(symbol, book, bar_origin=origin)286 if origin287 else (288 self._market_factory(symbol, book) if book else self._market_factory(symbol)289 )290 )291 return MergedMarket(sessions)292 except Exception as exc:293 cleanup_after_error(exc, *(session.close for session in sessions))294 raise295296 def _load_source(297 self,298 path: PathInput,299 symbol: str = DEFAULT_SYMBOL,300 news: Optional[PathInput] = None,301 allow_implicit_eof: bool = False,302 *,303 wait: bool = False,304 book: Optional[Dict[str, int]] = None,305 universe: Optional[Sequence[Tuple[str, Path]]] = None,306 ) -> SessionView:307 """Load a new market, then replace (and close) the previous runner and market.308309 ``book`` chooses a price-bar recording's synthetic spread and depth310 (market.prepared.bars.book_options); it is refused for an ITCH recording.311 ``universe`` lists (symbol, source path) pairs for an experiment on several312 symbols; ``path`` and ``symbol`` are then its first pair.313 """314 self._check_open()315 if self._active():316 raise ContractError('stop the active simulation before loading another file')317 path = Path(path).expanduser().resolve()318 stat = self._files.stat(path)319 news_identity = self._news_identity(news)320 from sim_platform.market.prepared.bars import book_options, is_bar_source321322 book = book_options(book)323 if book is not None and not is_bar_source(path):324 raise ContractError('spread and depth can be chosen only for a price-bar recording')325 market: Any = (326 self._merged_market(universe, book)327 if universe328 else self._market_factory(symbol, book) if book else self._market_factory(symbol)329 )330 try:331 if universe:332 # One announcements file serves every symbol of the experiment.333 market.load(334 [source for _, source in universe],335 news=load_news(news) if news else (),336 allow_implicit_eof=allow_implicit_eof,337 )338 else:339 market.load(340 path,341 news=load_news(news) if news else (),342 allow_implicit_eof=allow_implicit_eof,343 )344 if wait:345 from time import sleep346347 while not market.prepare():348 sleep(PREPARE_POLL_SECONDS)349 except Exception as exc:350 cleanup_after_error(exc, market.close)351 raise352 try:353 if self.runner is not None:354 self.runner.close()355 self._archive()356 except Exception as exc:357 cleanup_after_error(exc, market.close)358 raise359 previous_market, previous_runner = self.market, self.runner360 self._market_archived = False361 self.runner = None362 self._execution_mode = None363 self.profile = self.run_id = self.viewed_run = None364 self.market = market365 self.preparation = self._prepared_origin = None366 self.source = dict(367 path=str(path),368 bytes=stat.st_size,369 mtime_ns=stat.st_mtime_ns,370 news_path=str(Path(news).resolve()) if news else None,371 news_identity=news_identity,372 allow_implicit_eof=allow_implicit_eof,373 )374 if book is not None:375 self.source['book'] = book376 if universe:377 self.source['universe'] = [symbol for symbol, _ in universe]378 self.source['paths'] = [str(source) for _, source in universe]379 if market.status == 'ready':380 self.preparation = dict(status='ready', start_mode='beginning', target_time_ns=0)381 self._prepared_origin = dict(sequence=market.snapshot.sequence, time_ns=market.time_ns)382 self.source.update(383 prepared=market.prepared_descriptor(),384 start_origin=copy_json(self._prepared_origin),385 start_mode='beginning',386 start_time_ns=None,387 )388 cleanup(389 *(390 resource.close391 for resource in (previous_runner, previous_market)392 if resource is not None393 )394 )395 return self.view()396397 def can_reuse_preparation(398 self,399 path: PathInput,400 symbol: str = DEFAULT_SYMBOL,401 news: Optional[PathInput] = None,402 allow_implicit_eof: bool = False,403 start_mode: str = 'first_book',404 start_time_ns: Optional[int] = None,405 book: Optional[Dict[str, int]] = None,406 start_date: Optional[str] = None,407 ) -> bool:408 """Reuse only an untouched origin with unchanged source files/settings."""409 if (410 self.runner is not None411 or self.viewed_run412 or not self.market413 or not self.source414 or (self.preparation or {}).get('status') != 'ready'415 or self.market.status not in ('ready', 'paused')416 or self._prepared_origin417 != dict(sequence=self.market.snapshot.sequence, time_ns=self.market.time_ns)418 ):419 return False420 try:421 resolved = Path(path).expanduser().resolve()422 stat = self._files.stat(resolved)423 news_identity = self._news_identity(news)424 except OSError:425 return False426 target = REGULAR_OPEN_NS if start_mode == 'regular' else start_time_ns427 return (428 str(resolved) == self.source['path']429 and stat.st_size == self.source['bytes']430 and stat.st_mtime_ns == self.source['mtime_ns']431 and news_identity == self.source.get('news_identity')432 and symbol == self.market.snapshot.symbol433 and allow_implicit_eof == self.source['allow_implicit_eof']434 and start_mode == self.source.get('start_mode')435 and target == self.source.get('start_time_ns')436 and start_date == self.source.get('start_date')437 and book_matches(book, self.source.get('book'))438 )439440 def _finish_preparation(self) -> None:441 if self._loaded_market.status == 'playing':442 self._loaded_market.pause()443 self._prepared_origin = dict(444 sequence=self._loaded_market.snapshot.sequence, time_ns=self._loaded_market.time_ns445 )446 self._current_source['start_origin'] = copy_json(self._prepared_origin)447 self._current_preparation['status'] = 'ready'448449 def begin_prepare(450 self,451 path: PathInput,452 symbol: str = DEFAULT_SYMBOL,453 news: Optional[PathInput] = None,454 allow_implicit_eof: bool = False,455 start_mode: str = 'first_book',456 start_time_ns: Optional[int] = None,457 *,458 book: Optional[Dict[str, int]] = None,459 start_date: Optional[str] = None,460 symbols: Optional[Sequence[str]] = None,461 paths: Optional[Sequence[PathInput]] = None,462 ) -> SessionView:463 """Warm the market only; no run, policy or account events exist yet.464465 ``symbols`` (two or more) prepares one experiment on several symbols: from466 ``paths``, one source per symbol (one CSV each), or from ``path`` for every467 symbol (one ITCH file).468469 A custom start is ``start_time_ns`` of market time. With ``start_date``470 ('YYYY-MM-DD', price-bar recordings only) ``start_time_ns`` is instead a time of471 day on that date. ``book`` chooses a price-bar recording's synthetic book.472 """473 if start_mode not in ('first_book', 'regular', 'custom', 'beginning'):474 raise ContractError('unknown experiment start mode')475 target = REGULAR_OPEN_NS if start_mode == 'regular' else start_time_ns476 if start_mode == 'custom':477 from sim_platform.market.models import time_ns478479 time_ns(target)480 if start_date is not None:481 check_start_date(start_date, start_mode, target)482 universe = None483 if symbols:484 universe = experiment_universe(path, symbols, paths)485 path, symbol = universe[0][1], universe[0][0]486 elif self.can_reuse_preparation(487 path, symbol, news, allow_implicit_eof, start_mode, start_time_ns, book, start_date488 ):489 return self.view()490 self._load_source(491 path, symbol, news, allow_implicit_eof, wait=False, book=book, universe=universe492 )493 self._current_source.update(start_mode=start_mode, start_time_ns=target)494 self.preparation = dict(status='preparing', start_mode=start_mode, target_time_ns=target)495 if start_date is not None:496 # Saved only when given, so earlier runs' recorded sources stay unchanged.497 self._current_source['start_date'] = self.preparation['start_date'] = start_date498 if self._loaded_market.prepare():499 self._position_prepared_source()500 return self.view()501502 def _position_prepared_source(self) -> None:503 from sim_platform.market.models import DataUnavailable504505 target = self._current_preparation['target_time_ns']506 start_date = self._current_preparation.get('start_date')507 if start_date is not None:508 target = dated_start(self._loaded_market.calendar, start_date, target)509 self._current_preparation['target_time_ns'] = target510 try:511 self._loaded_market.start_position(self._current_preparation['start_mode'], target)512 except DataUnavailable as exc:513 self._current_preparation['status'] = 'failed'514 reason = (515 'dataset ends before the requested start point; no events after it'516 if self._current_preparation['start_mode'] == 'custom'517 else 'dataset ends before the requested start point'518 )519 raise ContractError(reason + ': ' + str(exc)) from exc520 self._current_source['prepared'] = self._loaded_market.prepared_descriptor()521 self._finish_preparation()522523 def prepare_tick(524 self,525 *,526 max_events: int = PREPARE_TICK_EVENTS,527 budget_seconds: float = PREPARE_TICK_BUDGET_SECONDS,528 ) -> SessionView:529 """Advance preparation by one market step and return the view."""530 self._check_open()531 if not self.preparation or self.preparation['status'] != 'preparing':532 raise ContractError('no market preparation is active')533 try:534 if self._loaded_market.prepare():535 self._position_prepared_source()536 else:537 self._current_preparation['progress'] = self._loaded_market.preparation_progress()538 except Exception:539 self._current_preparation['status'] = 'failed'540 raise541 return self.view()542543 def wait_for_preparation(self) -> SessionView:544 """Wait for the shared preparation path; UI callers should poll prepare_tick instead."""545 from time import sleep546547 while self._current_preparation['status'] == 'preparing':548 self.prepare_tick()549 if self._current_preparation['status'] == 'preparing':550 sleep(PREPARE_POLL_SECONDS)551 return self.view()552553 def cancel_preparation(self) -> SessionView:554 self._check_open()555 if self.runner is not None:556 raise ContractError('stop the experiment instead of cancelling market preparation')557 if self.market and self.market.status == 'loading':558 self.market.close()559 elif self.market and self.market.status == 'playing':560 self.market.pause()561 self._prepared_origin = None562 self._current_preparation['status'] = 'cancelled'563 self._current_source.pop('start_origin', None)564 return self.view()565566 @property567 def policy_controls(self) -> Any:568 self._check_open()569 if self.runner is None:570 raise ContractError('no experiment is bound')571 return self.runner.policy_controls572573 @property574 def tool_controls(self) -> Any:575 self._check_open()576 if self.runner is None:577 raise ContractError('no experiment is bound')578 return self.runner.tool_controls579580 def _driver(self) -> Union[ResearchRunner, PreparedSession]:581 """The object that advances playback: the runner once bound, else the market."""582 if self.viewed_run or self.market is None:583 raise ContractError('load market data to control playback')584 return self.runner or self.market585586 def step(self) -> SessionView:587 """Advance one event; a run that this step finished saves its market data now."""588 self._check_open()589 self._driver().step()590 if self.runner is not None and not self.runner.active:591 self._archive()592 return self.view()593594 def play(self, speed: Optional[float] = None) -> SessionView:595 self._check_open()596 self._driver().play(speed)597 return self.view()598599 def pause(self) -> SessionView:600 self._check_open()601 self._driver().pause()602 return self.view()603604 def tick(605 self, *, render: bool = True, max_events: int = 1, budget_seconds: Optional[float] = None606 ) -> Optional[SessionView]:607 """Poll the driver once and archive a finished run; return the view if ``render``."""608 self._check_open()609 self._driver().poll(max_events=max_events, budget_seconds=budget_seconds)610 if self.runner is not None and not self.runner.active:611 self._archive()612 return self.view() if render else None613614 def stop(self) -> SessionView:615 self._check_open()616 if self.runner is not None:617 cleanup(self.runner.stop, self._archive)618 elif self.market and self.market.status == 'playing':619 self.market.pause()620 return self.view()621622 def _close_market(self) -> None:623 if self.runner is not None and not self.runner.closed:624 raise ContractError(625 'execution owner has not drained; retain its market for close retry'626 )627 if self.market:628 self.market.close()629630 def view_run(self, profile: str, run_id: str) -> SessionView:631 """Release any live experiment and show a saved run's report instead."""632 self._check_open()633 if self._active():634 raise ContractError('stop the active simulation before viewing a saved run')635 self.app.run(profile, run_id, include_records=False)636 if self.runner is not None:637 cleanup(self.runner.close, self._archive, self._close_market)638 else:639 self._close_market()640 self.market = self.runner = None641 self.profile, self.run_id, self.viewed_run = profile, run_id, run_id642 return self.view()643644 def recover_stop(self, profile: str, run_id: str) -> SessionView:645 """Mark an interrupted saved run stopped, then view it."""646 self._check_open()647 if self._active():648 raise ContractError('stop the live simulation first')649 self.app.abort_execution_run(profile, run_id)650 return self.view_run(profile, run_id)651652 def report(self) -> Report:653 if not self.run_id:654 raise ContractError('no simulation report; start or open a saved run')655 if self.runner is not None and not self.runner.active:656 self._archive()657 # profile is always set together with run_id.658 return run_report(self.app, cast(str, self.profile), self.run_id)659660 def export(self, path: PathInput) -> str:661 self._check_open()662 self._archive()663 # Suspected bug: unlike report(), export() does not check that a run is bound, so664 # with no run the None profile and run IDs reach the database layer.665 return export_run(666 self.app,667 self.profile, # type: ignore[arg-type]668 self.run_id, # type: ignore[arg-type]669 path,670 writer=self._export_writer,671 )672673 @property674 def closed(self) -> bool:675 return self._closed676677 def close(self) -> None:678 if self._closed:679 return680 actions: List[Callable[[], None]] = [self.runner.close] if self.runner is not None else []681 actions.extend((self._archive, self._close_market))682 try:683 cleanup(*actions)684 finally:685 if self.runner is None or self.runner.closed:686 self._closed = True687 self._on_close()688689 @abstractmethod690 def create_experiment(691 self,692 profile: str,693 account: str,694 *,695 source: PathInput,696 method: str,697 settings: Optional[Dict[str, Any]] = None,698 agent_id: Optional[str] = None,699 revision: Optional[int] = None,700 execution_config: Optional[ExecutionConfig] = None,701 log_path: Optional[PathInput] = None,702 clock: Optional[SharedExperimentClock] = None,703 execution_mode: str,704 ) -> SessionView:705 """Prepare and bind the method supported by this controller subclass."""706707708def seed_research(709 session: ResearchController,710 demo_source: Optional[Tuple[PathInput, Optional[PathInput]]] = None,711) -> None:712 """Create the demo profile/account and load demo data, or a default profile if none."""713 if demo_source:714 profile = session.create_profile('Demo researcher')715 session.create_account(profile, 'AAPL demo account', DEMO_ACCOUNT_CASH)716 session.load(demo_source[0], news=demo_source[1])717 elif not session.catalog()['profiles']:718 session.create_profile('Default researcher')