crca 1.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (501) hide show
  1. .github/ISSUE_TEMPLATE/bug_report.md +65 -0
  2. .github/ISSUE_TEMPLATE/feature_request.md +41 -0
  3. .github/PULL_REQUEST_TEMPLATE.md +20 -0
  4. .github/workflows/publish-manual.yml +61 -0
  5. .github/workflows/publish.yml +64 -0
  6. .gitignore +214 -0
  7. CRCA.py +4156 -0
  8. LICENSE +201 -0
  9. MANIFEST.in +43 -0
  10. PKG-INFO +5035 -0
  11. README.md +4959 -0
  12. __init__.py +17 -0
  13. branches/CRCA-Q.py +2728 -0
  14. branches/crca_cg/corposwarm.py +9065 -0
  15. branches/crca_cg/fix_rancher_docker_creds.ps1 +155 -0
  16. branches/crca_cg/package.json +5 -0
  17. branches/crca_cg/test_bolt_integration.py +446 -0
  18. branches/crca_cg/test_corposwarm_comprehensive.py +773 -0
  19. branches/crca_cg/test_new_features.py +163 -0
  20. branches/crca_sd/__init__.py +149 -0
  21. branches/crca_sd/crca_sd_core.py +770 -0
  22. branches/crca_sd/crca_sd_governance.py +1325 -0
  23. branches/crca_sd/crca_sd_mpc.py +1130 -0
  24. branches/crca_sd/crca_sd_realtime.py +1844 -0
  25. branches/crca_sd/crca_sd_tui.py +1133 -0
  26. crca-1.4.0.dist-info/METADATA +5035 -0
  27. crca-1.4.0.dist-info/RECORD +501 -0
  28. crca-1.4.0.dist-info/WHEEL +4 -0
  29. crca-1.4.0.dist-info/licenses/LICENSE +201 -0
  30. docs/CRCA-Q.md +2333 -0
  31. examples/config.yaml.example +25 -0
  32. examples/crca_sd_example.py +513 -0
  33. examples/data_broker_example.py +294 -0
  34. examples/logistics_corporation.py +861 -0
  35. examples/palantir_example.py +299 -0
  36. examples/policy_bench.py +934 -0
  37. examples/pridnestrovia-sd.py +705 -0
  38. examples/pridnestrovia_realtime.py +1902 -0
  39. prompts/__init__.py +10 -0
  40. prompts/default_crca.py +101 -0
  41. pyproject.toml +151 -0
  42. requirements.txt +76 -0
  43. schemas/__init__.py +43 -0
  44. schemas/mcpSchemas.py +51 -0
  45. schemas/policy.py +458 -0
  46. templates/__init__.py +38 -0
  47. templates/base_specialized_agent.py +195 -0
  48. templates/drift_detection.py +325 -0
  49. templates/examples/causal_agent_template.py +309 -0
  50. templates/examples/drag_drop_example.py +213 -0
  51. templates/examples/logistics_agent_template.py +207 -0
  52. templates/examples/trading_agent_template.py +206 -0
  53. templates/feature_mixins.py +253 -0
  54. templates/graph_management.py +442 -0
  55. templates/llm_integration.py +194 -0
  56. templates/module_registry.py +276 -0
  57. templates/mpc_planner.py +280 -0
  58. templates/policy_loop.py +1168 -0
  59. templates/prediction_framework.py +448 -0
  60. templates/statistical_methods.py +778 -0
  61. tests/sanity.yml +31 -0
  62. tests/sanity_check +406 -0
  63. tests/test_core.py +47 -0
  64. tests/test_crca_excel.py +166 -0
  65. tests/test_crca_sd.py +780 -0
  66. tests/test_data_broker.py +424 -0
  67. tests/test_palantir.py +349 -0
  68. tools/__init__.py +38 -0
  69. tools/actuators.py +437 -0
  70. tools/bolt.diy/Dockerfile +103 -0
  71. tools/bolt.diy/app/components/@settings/core/AvatarDropdown.tsx +175 -0
  72. tools/bolt.diy/app/components/@settings/core/ControlPanel.tsx +345 -0
  73. tools/bolt.diy/app/components/@settings/core/constants.tsx +108 -0
  74. tools/bolt.diy/app/components/@settings/core/types.ts +114 -0
  75. tools/bolt.diy/app/components/@settings/index.ts +12 -0
  76. tools/bolt.diy/app/components/@settings/shared/components/TabTile.tsx +151 -0
  77. tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionForm.tsx +193 -0
  78. tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionTestIndicator.tsx +60 -0
  79. tools/bolt.diy/app/components/@settings/shared/service-integration/ErrorState.tsx +102 -0
  80. tools/bolt.diy/app/components/@settings/shared/service-integration/LoadingState.tsx +94 -0
  81. tools/bolt.diy/app/components/@settings/shared/service-integration/ServiceHeader.tsx +72 -0
  82. tools/bolt.diy/app/components/@settings/shared/service-integration/index.ts +6 -0
  83. tools/bolt.diy/app/components/@settings/tabs/data/DataTab.tsx +721 -0
  84. tools/bolt.diy/app/components/@settings/tabs/data/DataVisualization.tsx +384 -0
  85. tools/bolt.diy/app/components/@settings/tabs/event-logs/EventLogsTab.tsx +1013 -0
  86. tools/bolt.diy/app/components/@settings/tabs/features/FeaturesTab.tsx +295 -0
  87. tools/bolt.diy/app/components/@settings/tabs/github/GitHubTab.tsx +281 -0
  88. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubAuthDialog.tsx +173 -0
  89. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubCacheManager.tsx +367 -0
  90. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubConnection.tsx +233 -0
  91. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubErrorBoundary.tsx +105 -0
  92. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubProgressiveLoader.tsx +266 -0
  93. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositoryCard.tsx +121 -0
  94. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositorySelector.tsx +312 -0
  95. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubStats.tsx +291 -0
  96. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubUserProfile.tsx +46 -0
  97. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/GitHubStateIndicators.tsx +264 -0
  98. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/RepositoryCard.tsx +361 -0
  99. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/index.ts +11 -0
  100. tools/bolt.diy/app/components/@settings/tabs/gitlab/GitLabTab.tsx +305 -0
  101. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabAuthDialog.tsx +186 -0
  102. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabConnection.tsx +253 -0
  103. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabRepositorySelector.tsx +358 -0
  104. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryCard.tsx +79 -0
  105. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryList.tsx +142 -0
  106. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/StatsDisplay.tsx +91 -0
  107. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/index.ts +4 -0
  108. tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerList.tsx +99 -0
  109. tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerListItem.tsx +70 -0
  110. tools/bolt.diy/app/components/@settings/tabs/mcp/McpStatusBadge.tsx +37 -0
  111. tools/bolt.diy/app/components/@settings/tabs/mcp/McpTab.tsx +239 -0
  112. tools/bolt.diy/app/components/@settings/tabs/netlify/NetlifyTab.tsx +1393 -0
  113. tools/bolt.diy/app/components/@settings/tabs/netlify/components/NetlifyConnection.tsx +990 -0
  114. tools/bolt.diy/app/components/@settings/tabs/netlify/components/index.ts +1 -0
  115. tools/bolt.diy/app/components/@settings/tabs/notifications/NotificationsTab.tsx +300 -0
  116. tools/bolt.diy/app/components/@settings/tabs/profile/ProfileTab.tsx +181 -0
  117. tools/bolt.diy/app/components/@settings/tabs/providers/cloud/CloudProvidersTab.tsx +308 -0
  118. tools/bolt.diy/app/components/@settings/tabs/providers/local/ErrorBoundary.tsx +68 -0
  119. tools/bolt.diy/app/components/@settings/tabs/providers/local/HealthStatusBadge.tsx +64 -0
  120. tools/bolt.diy/app/components/@settings/tabs/providers/local/LoadingSkeleton.tsx +107 -0
  121. tools/bolt.diy/app/components/@settings/tabs/providers/local/LocalProvidersTab.tsx +556 -0
  122. tools/bolt.diy/app/components/@settings/tabs/providers/local/ModelCard.tsx +106 -0
  123. tools/bolt.diy/app/components/@settings/tabs/providers/local/ProviderCard.tsx +120 -0
  124. tools/bolt.diy/app/components/@settings/tabs/providers/local/SetupGuide.tsx +671 -0
  125. tools/bolt.diy/app/components/@settings/tabs/providers/local/StatusDashboard.tsx +91 -0
  126. tools/bolt.diy/app/components/@settings/tabs/providers/local/types.ts +44 -0
  127. tools/bolt.diy/app/components/@settings/tabs/settings/SettingsTab.tsx +215 -0
  128. tools/bolt.diy/app/components/@settings/tabs/supabase/SupabaseTab.tsx +1089 -0
  129. tools/bolt.diy/app/components/@settings/tabs/vercel/VercelTab.tsx +909 -0
  130. tools/bolt.diy/app/components/@settings/tabs/vercel/components/VercelConnection.tsx +368 -0
  131. tools/bolt.diy/app/components/@settings/tabs/vercel/components/index.ts +1 -0
  132. tools/bolt.diy/app/components/@settings/utils/tab-helpers.ts +54 -0
  133. tools/bolt.diy/app/components/chat/APIKeyManager.tsx +169 -0
  134. tools/bolt.diy/app/components/chat/Artifact.tsx +296 -0
  135. tools/bolt.diy/app/components/chat/AssistantMessage.tsx +192 -0
  136. tools/bolt.diy/app/components/chat/BaseChat.module.scss +47 -0
  137. tools/bolt.diy/app/components/chat/BaseChat.tsx +522 -0
  138. tools/bolt.diy/app/components/chat/Chat.client.tsx +670 -0
  139. tools/bolt.diy/app/components/chat/ChatAlert.tsx +108 -0
  140. tools/bolt.diy/app/components/chat/ChatBox.tsx +334 -0
  141. tools/bolt.diy/app/components/chat/CodeBlock.module.scss +10 -0
  142. tools/bolt.diy/app/components/chat/CodeBlock.tsx +85 -0
  143. tools/bolt.diy/app/components/chat/DicussMode.tsx +17 -0
  144. tools/bolt.diy/app/components/chat/ExamplePrompts.tsx +37 -0
  145. tools/bolt.diy/app/components/chat/FilePreview.tsx +38 -0
  146. tools/bolt.diy/app/components/chat/GitCloneButton.tsx +327 -0
  147. tools/bolt.diy/app/components/chat/ImportFolderButton.tsx +141 -0
  148. tools/bolt.diy/app/components/chat/LLMApiAlert.tsx +109 -0
  149. tools/bolt.diy/app/components/chat/MCPTools.tsx +129 -0
  150. tools/bolt.diy/app/components/chat/Markdown.module.scss +171 -0
  151. tools/bolt.diy/app/components/chat/Markdown.spec.ts +48 -0
  152. tools/bolt.diy/app/components/chat/Markdown.tsx +252 -0
  153. tools/bolt.diy/app/components/chat/Messages.client.tsx +102 -0
  154. tools/bolt.diy/app/components/chat/ModelSelector.tsx +797 -0
  155. tools/bolt.diy/app/components/chat/NetlifyDeploymentLink.client.tsx +51 -0
  156. tools/bolt.diy/app/components/chat/ProgressCompilation.tsx +110 -0
  157. tools/bolt.diy/app/components/chat/ScreenshotStateManager.tsx +33 -0
  158. tools/bolt.diy/app/components/chat/SendButton.client.tsx +39 -0
  159. tools/bolt.diy/app/components/chat/SpeechRecognition.tsx +28 -0
  160. tools/bolt.diy/app/components/chat/StarterTemplates.tsx +38 -0
  161. tools/bolt.diy/app/components/chat/SupabaseAlert.tsx +199 -0
  162. tools/bolt.diy/app/components/chat/SupabaseConnection.tsx +339 -0
  163. tools/bolt.diy/app/components/chat/ThoughtBox.tsx +43 -0
  164. tools/bolt.diy/app/components/chat/ToolInvocations.tsx +409 -0
  165. tools/bolt.diy/app/components/chat/UserMessage.tsx +101 -0
  166. tools/bolt.diy/app/components/chat/VercelDeploymentLink.client.tsx +158 -0
  167. tools/bolt.diy/app/components/chat/chatExportAndImport/ExportChatButton.tsx +49 -0
  168. tools/bolt.diy/app/components/chat/chatExportAndImport/ImportButtons.tsx +96 -0
  169. tools/bolt.diy/app/components/deploy/DeployAlert.tsx +197 -0
  170. tools/bolt.diy/app/components/deploy/DeployButton.tsx +277 -0
  171. tools/bolt.diy/app/components/deploy/GitHubDeploy.client.tsx +171 -0
  172. tools/bolt.diy/app/components/deploy/GitHubDeploymentDialog.tsx +1041 -0
  173. tools/bolt.diy/app/components/deploy/GitLabDeploy.client.tsx +171 -0
  174. tools/bolt.diy/app/components/deploy/GitLabDeploymentDialog.tsx +764 -0
  175. tools/bolt.diy/app/components/deploy/NetlifyDeploy.client.tsx +246 -0
  176. tools/bolt.diy/app/components/deploy/VercelDeploy.client.tsx +235 -0
  177. tools/bolt.diy/app/components/editor/codemirror/BinaryContent.tsx +7 -0
  178. tools/bolt.diy/app/components/editor/codemirror/CodeMirrorEditor.tsx +555 -0
  179. tools/bolt.diy/app/components/editor/codemirror/EnvMasking.ts +80 -0
  180. tools/bolt.diy/app/components/editor/codemirror/cm-theme.ts +192 -0
  181. tools/bolt.diy/app/components/editor/codemirror/indent.ts +68 -0
  182. tools/bolt.diy/app/components/editor/codemirror/languages.ts +112 -0
  183. tools/bolt.diy/app/components/git/GitUrlImport.client.tsx +147 -0
  184. tools/bolt.diy/app/components/header/Header.tsx +42 -0
  185. tools/bolt.diy/app/components/header/HeaderActionButtons.client.tsx +54 -0
  186. tools/bolt.diy/app/components/mandate/MandateSubmission.tsx +167 -0
  187. tools/bolt.diy/app/components/observability/DeploymentStatus.tsx +168 -0
  188. tools/bolt.diy/app/components/observability/EventTimeline.tsx +119 -0
  189. tools/bolt.diy/app/components/observability/FileDiffViewer.tsx +121 -0
  190. tools/bolt.diy/app/components/observability/GovernanceStatus.tsx +197 -0
  191. tools/bolt.diy/app/components/observability/GovernorMetrics.tsx +246 -0
  192. tools/bolt.diy/app/components/observability/LogStream.tsx +244 -0
  193. tools/bolt.diy/app/components/observability/MandateDetails.tsx +201 -0
  194. tools/bolt.diy/app/components/observability/ObservabilityDashboard.tsx +200 -0
  195. tools/bolt.diy/app/components/sidebar/HistoryItem.tsx +187 -0
  196. tools/bolt.diy/app/components/sidebar/Menu.client.tsx +536 -0
  197. tools/bolt.diy/app/components/sidebar/date-binning.ts +59 -0
  198. tools/bolt.diy/app/components/txt +1 -0
  199. tools/bolt.diy/app/components/ui/BackgroundRays/index.tsx +18 -0
  200. tools/bolt.diy/app/components/ui/BackgroundRays/styles.module.scss +246 -0
  201. tools/bolt.diy/app/components/ui/Badge.tsx +53 -0
  202. tools/bolt.diy/app/components/ui/BranchSelector.tsx +270 -0
  203. tools/bolt.diy/app/components/ui/Breadcrumbs.tsx +101 -0
  204. tools/bolt.diy/app/components/ui/Button.tsx +46 -0
  205. tools/bolt.diy/app/components/ui/Card.tsx +55 -0
  206. tools/bolt.diy/app/components/ui/Checkbox.tsx +32 -0
  207. tools/bolt.diy/app/components/ui/CloseButton.tsx +49 -0
  208. tools/bolt.diy/app/components/ui/CodeBlock.tsx +103 -0
  209. tools/bolt.diy/app/components/ui/Collapsible.tsx +9 -0
  210. tools/bolt.diy/app/components/ui/ColorSchemeDialog.tsx +378 -0
  211. tools/bolt.diy/app/components/ui/Dialog.tsx +449 -0
  212. tools/bolt.diy/app/components/ui/Dropdown.tsx +63 -0
  213. tools/bolt.diy/app/components/ui/EmptyState.tsx +154 -0
  214. tools/bolt.diy/app/components/ui/FileIcon.tsx +346 -0
  215. tools/bolt.diy/app/components/ui/FilterChip.tsx +92 -0
  216. tools/bolt.diy/app/components/ui/GlowingEffect.tsx +192 -0
  217. tools/bolt.diy/app/components/ui/GradientCard.tsx +100 -0
  218. tools/bolt.diy/app/components/ui/IconButton.tsx +84 -0
  219. tools/bolt.diy/app/components/ui/Input.tsx +22 -0
  220. tools/bolt.diy/app/components/ui/Label.tsx +20 -0
  221. tools/bolt.diy/app/components/ui/LoadingDots.tsx +27 -0
  222. tools/bolt.diy/app/components/ui/LoadingOverlay.tsx +32 -0
  223. tools/bolt.diy/app/components/ui/PanelHeader.tsx +20 -0
  224. tools/bolt.diy/app/components/ui/PanelHeaderButton.tsx +36 -0
  225. tools/bolt.diy/app/components/ui/Popover.tsx +29 -0
  226. tools/bolt.diy/app/components/ui/Progress.tsx +22 -0
  227. tools/bolt.diy/app/components/ui/RepositoryStats.tsx +87 -0
  228. tools/bolt.diy/app/components/ui/ScrollArea.tsx +41 -0
  229. tools/bolt.diy/app/components/ui/SearchInput.tsx +80 -0
  230. tools/bolt.diy/app/components/ui/SearchResultItem.tsx +134 -0
  231. tools/bolt.diy/app/components/ui/Separator.tsx +22 -0
  232. tools/bolt.diy/app/components/ui/SettingsButton.tsx +35 -0
  233. tools/bolt.diy/app/components/ui/Slider.tsx +73 -0
  234. tools/bolt.diy/app/components/ui/StatusIndicator.tsx +90 -0
  235. tools/bolt.diy/app/components/ui/Switch.tsx +37 -0
  236. tools/bolt.diy/app/components/ui/Tabs.tsx +52 -0
  237. tools/bolt.diy/app/components/ui/TabsWithSlider.tsx +112 -0
  238. tools/bolt.diy/app/components/ui/ThemeSwitch.tsx +29 -0
  239. tools/bolt.diy/app/components/ui/Tooltip.tsx +122 -0
  240. tools/bolt.diy/app/components/ui/index.ts +38 -0
  241. tools/bolt.diy/app/components/ui/use-toast.ts +66 -0
  242. tools/bolt.diy/app/components/workbench/DiffView.tsx +796 -0
  243. tools/bolt.diy/app/components/workbench/EditorPanel.tsx +174 -0
  244. tools/bolt.diy/app/components/workbench/ExpoQrModal.tsx +55 -0
  245. tools/bolt.diy/app/components/workbench/FileBreadcrumb.tsx +150 -0
  246. tools/bolt.diy/app/components/workbench/FileTree.tsx +565 -0
  247. tools/bolt.diy/app/components/workbench/Inspector.tsx +126 -0
  248. tools/bolt.diy/app/components/workbench/InspectorPanel.tsx +146 -0
  249. tools/bolt.diy/app/components/workbench/LockManager.tsx +262 -0
  250. tools/bolt.diy/app/components/workbench/PortDropdown.tsx +91 -0
  251. tools/bolt.diy/app/components/workbench/Preview.tsx +1049 -0
  252. tools/bolt.diy/app/components/workbench/ScreenshotSelector.tsx +293 -0
  253. tools/bolt.diy/app/components/workbench/Search.tsx +257 -0
  254. tools/bolt.diy/app/components/workbench/Workbench.client.tsx +506 -0
  255. tools/bolt.diy/app/components/workbench/terminal/Terminal.tsx +131 -0
  256. tools/bolt.diy/app/components/workbench/terminal/TerminalManager.tsx +68 -0
  257. tools/bolt.diy/app/components/workbench/terminal/TerminalTabs.tsx +277 -0
  258. tools/bolt.diy/app/components/workbench/terminal/theme.ts +36 -0
  259. tools/bolt.diy/app/components/workflow/WorkflowPhase.tsx +109 -0
  260. tools/bolt.diy/app/components/workflow/WorkflowStatus.tsx +60 -0
  261. tools/bolt.diy/app/components/workflow/WorkflowTimeline.tsx +150 -0
  262. tools/bolt.diy/app/entry.client.tsx +7 -0
  263. tools/bolt.diy/app/entry.server.tsx +80 -0
  264. tools/bolt.diy/app/root.tsx +156 -0
  265. tools/bolt.diy/app/routes/_index.tsx +175 -0
  266. tools/bolt.diy/app/routes/api.bug-report.ts +254 -0
  267. tools/bolt.diy/app/routes/api.chat.ts +463 -0
  268. tools/bolt.diy/app/routes/api.check-env-key.ts +41 -0
  269. tools/bolt.diy/app/routes/api.configured-providers.ts +110 -0
  270. tools/bolt.diy/app/routes/api.corporate-swarm-status.ts +55 -0
  271. tools/bolt.diy/app/routes/api.enhancer.ts +137 -0
  272. tools/bolt.diy/app/routes/api.export-api-keys.ts +44 -0
  273. tools/bolt.diy/app/routes/api.git-info.ts +69 -0
  274. tools/bolt.diy/app/routes/api.git-proxy.$.ts +178 -0
  275. tools/bolt.diy/app/routes/api.github-branches.ts +166 -0
  276. tools/bolt.diy/app/routes/api.github-deploy.ts +67 -0
  277. tools/bolt.diy/app/routes/api.github-stats.ts +198 -0
  278. tools/bolt.diy/app/routes/api.github-template.ts +242 -0
  279. tools/bolt.diy/app/routes/api.github-user.ts +287 -0
  280. tools/bolt.diy/app/routes/api.gitlab-branches.ts +143 -0
  281. tools/bolt.diy/app/routes/api.gitlab-deploy.ts +67 -0
  282. tools/bolt.diy/app/routes/api.gitlab-projects.ts +105 -0
  283. tools/bolt.diy/app/routes/api.health.ts +8 -0
  284. tools/bolt.diy/app/routes/api.llmcall.ts +298 -0
  285. tools/bolt.diy/app/routes/api.mandate.ts +351 -0
  286. tools/bolt.diy/app/routes/api.mcp-check.ts +16 -0
  287. tools/bolt.diy/app/routes/api.mcp-update-config.ts +23 -0
  288. tools/bolt.diy/app/routes/api.models.$provider.ts +2 -0
  289. tools/bolt.diy/app/routes/api.models.ts +90 -0
  290. tools/bolt.diy/app/routes/api.netlify-deploy.ts +240 -0
  291. tools/bolt.diy/app/routes/api.netlify-user.ts +142 -0
  292. tools/bolt.diy/app/routes/api.supabase-user.ts +199 -0
  293. tools/bolt.diy/app/routes/api.supabase.query.ts +92 -0
  294. tools/bolt.diy/app/routes/api.supabase.ts +56 -0
  295. tools/bolt.diy/app/routes/api.supabase.variables.ts +32 -0
  296. tools/bolt.diy/app/routes/api.system.diagnostics.ts +142 -0
  297. tools/bolt.diy/app/routes/api.system.disk-info.ts +311 -0
  298. tools/bolt.diy/app/routes/api.system.git-info.ts +332 -0
  299. tools/bolt.diy/app/routes/api.update.ts +21 -0
  300. tools/bolt.diy/app/routes/api.vercel-deploy.ts +497 -0
  301. tools/bolt.diy/app/routes/api.vercel-user.ts +161 -0
  302. tools/bolt.diy/app/routes/api.workflow-status.$proposalId.ts +309 -0
  303. tools/bolt.diy/app/routes/chat.$id.tsx +8 -0
  304. tools/bolt.diy/app/routes/execute.$mandateId.tsx +432 -0
  305. tools/bolt.diy/app/routes/git.tsx +25 -0
  306. tools/bolt.diy/app/routes/observability.$mandateId.tsx +50 -0
  307. tools/bolt.diy/app/routes/webcontainer.connect.$id.tsx +32 -0
  308. tools/bolt.diy/app/routes/webcontainer.preview.$id.tsx +97 -0
  309. tools/bolt.diy/app/routes/workflow.$proposalId.tsx +170 -0
  310. tools/bolt.diy/app/styles/animations.scss +49 -0
  311. tools/bolt.diy/app/styles/components/code.scss +9 -0
  312. tools/bolt.diy/app/styles/components/editor.scss +135 -0
  313. tools/bolt.diy/app/styles/components/resize-handle.scss +30 -0
  314. tools/bolt.diy/app/styles/components/terminal.scss +3 -0
  315. tools/bolt.diy/app/styles/components/toast.scss +23 -0
  316. tools/bolt.diy/app/styles/diff-view.css +72 -0
  317. tools/bolt.diy/app/styles/index.scss +73 -0
  318. tools/bolt.diy/app/styles/variables.scss +255 -0
  319. tools/bolt.diy/app/styles/z-index.scss +37 -0
  320. tools/bolt.diy/app/types/GitHub.ts +182 -0
  321. tools/bolt.diy/app/types/GitLab.ts +103 -0
  322. tools/bolt.diy/app/types/actions.ts +85 -0
  323. tools/bolt.diy/app/types/artifact.ts +5 -0
  324. tools/bolt.diy/app/types/context.ts +26 -0
  325. tools/bolt.diy/app/types/design-scheme.ts +93 -0
  326. tools/bolt.diy/app/types/global.d.ts +13 -0
  327. tools/bolt.diy/app/types/mandate.ts +333 -0
  328. tools/bolt.diy/app/types/model.ts +25 -0
  329. tools/bolt.diy/app/types/netlify.ts +94 -0
  330. tools/bolt.diy/app/types/supabase.ts +54 -0
  331. tools/bolt.diy/app/types/template.ts +8 -0
  332. tools/bolt.diy/app/types/terminal.ts +9 -0
  333. tools/bolt.diy/app/types/theme.ts +1 -0
  334. tools/bolt.diy/app/types/vercel.ts +67 -0
  335. tools/bolt.diy/app/utils/buffer.ts +29 -0
  336. tools/bolt.diy/app/utils/classNames.ts +65 -0
  337. tools/bolt.diy/app/utils/constants.ts +147 -0
  338. tools/bolt.diy/app/utils/debounce.ts +13 -0
  339. tools/bolt.diy/app/utils/debugLogger.ts +1284 -0
  340. tools/bolt.diy/app/utils/diff.spec.ts +11 -0
  341. tools/bolt.diy/app/utils/diff.ts +117 -0
  342. tools/bolt.diy/app/utils/easings.ts +3 -0
  343. tools/bolt.diy/app/utils/fileLocks.ts +96 -0
  344. tools/bolt.diy/app/utils/fileUtils.ts +121 -0
  345. tools/bolt.diy/app/utils/folderImport.ts +73 -0
  346. tools/bolt.diy/app/utils/formatSize.ts +12 -0
  347. tools/bolt.diy/app/utils/getLanguageFromExtension.ts +24 -0
  348. tools/bolt.diy/app/utils/githubStats.ts +9 -0
  349. tools/bolt.diy/app/utils/gitlabStats.ts +54 -0
  350. tools/bolt.diy/app/utils/logger.ts +162 -0
  351. tools/bolt.diy/app/utils/markdown.ts +155 -0
  352. tools/bolt.diy/app/utils/mobile.ts +4 -0
  353. tools/bolt.diy/app/utils/os.ts +4 -0
  354. tools/bolt.diy/app/utils/path.ts +19 -0
  355. tools/bolt.diy/app/utils/projectCommands.ts +197 -0
  356. tools/bolt.diy/app/utils/promises.ts +19 -0
  357. tools/bolt.diy/app/utils/react.ts +6 -0
  358. tools/bolt.diy/app/utils/sampler.ts +49 -0
  359. tools/bolt.diy/app/utils/selectStarterTemplate.ts +255 -0
  360. tools/bolt.diy/app/utils/shell.ts +384 -0
  361. tools/bolt.diy/app/utils/stacktrace.ts +27 -0
  362. tools/bolt.diy/app/utils/stripIndent.ts +23 -0
  363. tools/bolt.diy/app/utils/terminal.ts +11 -0
  364. tools/bolt.diy/app/utils/unreachable.ts +3 -0
  365. tools/bolt.diy/app/vite-env.d.ts +2 -0
  366. tools/bolt.diy/assets/entitlements.mac.plist +25 -0
  367. tools/bolt.diy/assets/icons/icon.icns +0 -0
  368. tools/bolt.diy/assets/icons/icon.ico +0 -0
  369. tools/bolt.diy/assets/icons/icon.png +0 -0
  370. tools/bolt.diy/bindings.js +78 -0
  371. tools/bolt.diy/bindings.sh +33 -0
  372. tools/bolt.diy/docker-compose.yaml +145 -0
  373. tools/bolt.diy/electron/main/index.ts +201 -0
  374. tools/bolt.diy/electron/main/tsconfig.json +30 -0
  375. tools/bolt.diy/electron/main/ui/menu.ts +29 -0
  376. tools/bolt.diy/electron/main/ui/window.ts +54 -0
  377. tools/bolt.diy/electron/main/utils/auto-update.ts +110 -0
  378. tools/bolt.diy/electron/main/utils/constants.ts +4 -0
  379. tools/bolt.diy/electron/main/utils/cookie.ts +40 -0
  380. tools/bolt.diy/electron/main/utils/reload.ts +35 -0
  381. tools/bolt.diy/electron/main/utils/serve.ts +71 -0
  382. tools/bolt.diy/electron/main/utils/store.ts +3 -0
  383. tools/bolt.diy/electron/main/utils/vite-server.ts +44 -0
  384. tools/bolt.diy/electron/main/vite.config.ts +44 -0
  385. tools/bolt.diy/electron/preload/index.ts +22 -0
  386. tools/bolt.diy/electron/preload/tsconfig.json +7 -0
  387. tools/bolt.diy/electron/preload/vite.config.ts +31 -0
  388. tools/bolt.diy/electron-builder.yml +64 -0
  389. tools/bolt.diy/electron-update.yml +4 -0
  390. tools/bolt.diy/eslint.config.mjs +57 -0
  391. tools/bolt.diy/functions/[[path]].ts +12 -0
  392. tools/bolt.diy/icons/angular.svg +1 -0
  393. tools/bolt.diy/icons/astro.svg +8 -0
  394. tools/bolt.diy/icons/chat.svg +1 -0
  395. tools/bolt.diy/icons/expo-brand.svg +1 -0
  396. tools/bolt.diy/icons/expo.svg +4 -0
  397. tools/bolt.diy/icons/logo-text.svg +1 -0
  398. tools/bolt.diy/icons/logo.svg +4 -0
  399. tools/bolt.diy/icons/mcp.svg +1 -0
  400. tools/bolt.diy/icons/nativescript.svg +1 -0
  401. tools/bolt.diy/icons/netlify.svg +10 -0
  402. tools/bolt.diy/icons/nextjs.svg +1 -0
  403. tools/bolt.diy/icons/nuxt.svg +1 -0
  404. tools/bolt.diy/icons/qwik.svg +1 -0
  405. tools/bolt.diy/icons/react.svg +1 -0
  406. tools/bolt.diy/icons/remix.svg +24 -0
  407. tools/bolt.diy/icons/remotion.svg +1 -0
  408. tools/bolt.diy/icons/shadcn.svg +21 -0
  409. tools/bolt.diy/icons/slidev.svg +60 -0
  410. tools/bolt.diy/icons/solidjs.svg +1 -0
  411. tools/bolt.diy/icons/stars.svg +1 -0
  412. tools/bolt.diy/icons/svelte.svg +1 -0
  413. tools/bolt.diy/icons/typescript.svg +1 -0
  414. tools/bolt.diy/icons/vite.svg +1 -0
  415. tools/bolt.diy/icons/vue.svg +1 -0
  416. tools/bolt.diy/load-context.ts +9 -0
  417. tools/bolt.diy/notarize.cjs +31 -0
  418. tools/bolt.diy/package.json +218 -0
  419. tools/bolt.diy/playwright.config.preview.ts +35 -0
  420. tools/bolt.diy/pre-start.cjs +26 -0
  421. tools/bolt.diy/public/apple-touch-icon-precomposed.png +0 -0
  422. tools/bolt.diy/public/apple-touch-icon.png +0 -0
  423. tools/bolt.diy/public/favicon.ico +0 -0
  424. tools/bolt.diy/public/favicon.svg +4 -0
  425. tools/bolt.diy/public/icons/AmazonBedrock.svg +1 -0
  426. tools/bolt.diy/public/icons/Anthropic.svg +4 -0
  427. tools/bolt.diy/public/icons/Cohere.svg +4 -0
  428. tools/bolt.diy/public/icons/Deepseek.svg +5 -0
  429. tools/bolt.diy/public/icons/Default.svg +4 -0
  430. tools/bolt.diy/public/icons/Google.svg +4 -0
  431. tools/bolt.diy/public/icons/Groq.svg +4 -0
  432. tools/bolt.diy/public/icons/HuggingFace.svg +4 -0
  433. tools/bolt.diy/public/icons/Hyperbolic.svg +3 -0
  434. tools/bolt.diy/public/icons/LMStudio.svg +5 -0
  435. tools/bolt.diy/public/icons/Mistral.svg +4 -0
  436. tools/bolt.diy/public/icons/Ollama.svg +4 -0
  437. tools/bolt.diy/public/icons/OpenAI.svg +4 -0
  438. tools/bolt.diy/public/icons/OpenAILike.svg +4 -0
  439. tools/bolt.diy/public/icons/OpenRouter.svg +4 -0
  440. tools/bolt.diy/public/icons/Perplexity.svg +4 -0
  441. tools/bolt.diy/public/icons/Together.svg +4 -0
  442. tools/bolt.diy/public/icons/xAI.svg +5 -0
  443. tools/bolt.diy/public/inspector-script.js +292 -0
  444. tools/bolt.diy/public/logo-dark-styled.png +0 -0
  445. tools/bolt.diy/public/logo-dark.png +0 -0
  446. tools/bolt.diy/public/logo-light-styled.png +0 -0
  447. tools/bolt.diy/public/logo-light.png +0 -0
  448. tools/bolt.diy/public/logo.svg +15 -0
  449. tools/bolt.diy/public/social_preview_index.jpg +0 -0
  450. tools/bolt.diy/scripts/clean.js +45 -0
  451. tools/bolt.diy/scripts/electron-dev.mjs +181 -0
  452. tools/bolt.diy/scripts/setup-env.sh +41 -0
  453. tools/bolt.diy/scripts/update-imports.sh +7 -0
  454. tools/bolt.diy/scripts/update.sh +52 -0
  455. tools/bolt.diy/services/execution-governor/Dockerfile +41 -0
  456. tools/bolt.diy/services/execution-governor/config.ts +42 -0
  457. tools/bolt.diy/services/execution-governor/index.ts +683 -0
  458. tools/bolt.diy/services/execution-governor/metrics.ts +141 -0
  459. tools/bolt.diy/services/execution-governor/package.json +31 -0
  460. tools/bolt.diy/services/execution-governor/priority-queue.ts +139 -0
  461. tools/bolt.diy/services/execution-governor/tsconfig.json +21 -0
  462. tools/bolt.diy/services/execution-governor/types.ts +145 -0
  463. tools/bolt.diy/services/headless-executor/Dockerfile +43 -0
  464. tools/bolt.diy/services/headless-executor/executor.ts +210 -0
  465. tools/bolt.diy/services/headless-executor/index.ts +323 -0
  466. tools/bolt.diy/services/headless-executor/package.json +27 -0
  467. tools/bolt.diy/services/headless-executor/tsconfig.json +21 -0
  468. tools/bolt.diy/services/headless-executor/types.ts +38 -0
  469. tools/bolt.diy/test-workflows.sh +240 -0
  470. tools/bolt.diy/tests/integration/corporate-swarm.test.ts +208 -0
  471. tools/bolt.diy/tests/mandates/budget-limited.json +34 -0
  472. tools/bolt.diy/tests/mandates/complex.json +53 -0
  473. tools/bolt.diy/tests/mandates/constraint-enforced.json +36 -0
  474. tools/bolt.diy/tests/mandates/simple.json +35 -0
  475. tools/bolt.diy/tsconfig.json +37 -0
  476. tools/bolt.diy/types/istextorbinary.d.ts +15 -0
  477. tools/bolt.diy/uno.config.ts +279 -0
  478. tools/bolt.diy/vite-electron.config.ts +76 -0
  479. tools/bolt.diy/vite.config.ts +112 -0
  480. tools/bolt.diy/worker-configuration.d.ts +22 -0
  481. tools/bolt.diy/wrangler.toml +6 -0
  482. tools/code_generator.py +461 -0
  483. tools/file_operations.py +465 -0
  484. tools/mandate_generator.py +337 -0
  485. tools/mcpClientUtils.py +1216 -0
  486. tools/sensors.py +285 -0
  487. utils/Agent_types.py +15 -0
  488. utils/AnyToStr.py +0 -0
  489. utils/HHCS.py +277 -0
  490. utils/__init__.py +30 -0
  491. utils/agent.py +3627 -0
  492. utils/aop.py +2948 -0
  493. utils/canonical.py +143 -0
  494. utils/conversation.py +1195 -0
  495. utils/doctrine_versioning +230 -0
  496. utils/formatter.py +474 -0
  497. utils/ledger.py +311 -0
  498. utils/out_types.py +16 -0
  499. utils/rollback.py +339 -0
  500. utils/router.py +929 -0
  501. utils/tui.py +1908 -0
docs/CRCA-Q.md ADDED
@@ -0,0 +1,2333 @@
1
+ # CRCA-Q: Causal Reasoning for Quantitative Trading
2
+
3
+ ## Executive Summary
4
+
5
+ CRCA-Q is a single-file quantitative trading system that integrates **causal reasoning** (based on Judea Pearl's Structural Causal Models and the CRCA framework) with traditional quantitative finance techniques. Unlike correlation-based systems, CRCA-Q uses **causal inference** to understand *why* market movements occur, enabling more robust predictions that remain valid across different market regimes.
6
+
7
+ This document provides a comprehensive technical deep-dive into the system's architecture, theoretical foundations, and practical implementation.
8
+
9
+ ---
10
+
11
+ ## Table of Contents
12
+
13
+ 1. [Philosophical Foundation: Causal vs. Correlational Trading](#philosophical-foundation)
14
+ 2. [System Architecture Overview](#system-architecture)
15
+ 3. [Core Components Deep Dive](#core-components)
16
+ 4. [Causal Reasoning Engine](#causal-reasoning-engine)
17
+ 5. [Signal Generation and Validation](#signal-generation)
18
+ 6. [Portfolio Optimization](#portfolio-optimization)
19
+ 7. [Risk Management Framework](#risk-management)
20
+ 8. [Execution and Backtesting](#execution-backtesting)
21
+ 9. [Comparison with Renaissance Technologies](#renaissance-comparison)
22
+ 10. [Quick Setup Guide](#quick-setup)
23
+ 11. [Advanced Configuration](#advanced-configuration)
24
+
25
+ ---
26
+
27
+ ## Philosophical Foundation: Causal vs. Correlational Trading {#philosophical-foundation}
28
+
29
+ ### The Fundamental Problem
30
+
31
+ Traditional quantitative trading systems (including many used by hedge funds) rely heavily on **correlational patterns**: "When X happens, Y tends to follow." This approach has critical limitations:
32
+
33
+ 1. **Regime Dependency**: Correlations break down when market regimes change (e.g., bull vs. bear markets)
34
+ 2. **Spurious Relationships**: Many correlations are coincidental, not causal
35
+ 3. **Lack of Interpretability**: It's unclear *why* a signal works, making it hard to adapt when conditions change
36
+ 4. **Overfitting Risk**: Complex models can memorize historical patterns without understanding underlying mechanisms
37
+
38
+ ### The Causal Solution
39
+
40
+ CRCA-Q addresses these issues by implementing **causal reasoning** based on Judea Pearl's framework:
41
+
42
+ - **Structural Causal Models (SCMs)**: Represent market variables as nodes in a directed acyclic graph (DAG), where edges represent causal relationships
43
+ - **Do-Calculus**: Uses Pearl's do-operator to reason about interventions ("What happens if we *force* sentiment to increase?")
44
+ - **Counterfactual Reasoning**: Answers "What would have happened if..." questions, enabling robust scenario analysis
45
+ - **Confounder Identification**: Distinguishes between direct causal effects and spurious correlations
46
+
47
+ ### Why This Matters
48
+
49
+ Consider a simple example: **Volume → Price Movement**
50
+
51
+ - **Correlational view**: "High volume correlates with price increases"
52
+ - **Causal view**: "High volume *causes* increased liquidity, which *causes* reduced price impact, which *causes* more efficient price discovery"
53
+
54
+ The causal view is more robust because:
55
+ - It explains *why* the relationship exists
56
+ - It can predict behavior under interventions (e.g., "What if we artificially increase volume?")
57
+ - It remains valid across different market regimes
58
+
59
+ ---
60
+
61
+ ## System Architecture Overview {#system-architecture}
62
+
63
+ CRCA-Q is organized into **five major subsystems**, each with specific responsibilities:
64
+
65
+ ```mermaid
66
+ flowchart TD
67
+ Start([Start: QuantTradingAgent.run]) --> InitCheck{System State Check}
68
+ InitCheck -->|COOLDOWN| CooldownTick[Cooldown Tick]
69
+ InitCheck -->|ACTIVE| UpdatePnL[Update Session PnL]
70
+ CooldownTick --> CheckCircuit[Check Circuit Breaker]
71
+ UpdatePnL --> CheckCircuit
72
+ CheckCircuit --> CheckIncremental{Incremental Update?}
73
+
74
+ CheckIncremental -->|Yes & Cached| ReturnCached[Return Cached Result]
75
+ CheckIncremental -->|No| CheckMultiAsset{Multi-Asset Mode?}
76
+
77
+ CheckMultiAsset -->|Yes| MultiAssetFlow[Multi-Asset Workflow]
78
+ CheckMultiAsset -->|No| SingleAssetFlow[Single-Asset Workflow]
79
+
80
+ %% Single Asset Flow
81
+ SingleAssetFlow --> FetchData1[Fetch Market Data]
82
+ FetchData1 --> FetchAltData1[Fetch Alternative Data]
83
+ FetchAltData1 --> ComputeSignals1[Compute Signals]
84
+ ComputeSignals1 --> ValidateSignals1[Validate Signals with CRCA]
85
+ ValidateSignals1 --> BuildCausalGraph[Build Causal Graph]
86
+ BuildCausalGraph --> FitSCM[Fit SCM from Data]
87
+ FitSCM --> GeneratePredictions1[Generate Predictions]
88
+ GeneratePredictions1 --> OptimizePortfolio1[Optimize Portfolio]
89
+ OptimizePortfolio1 --> CalculateTargets1[Calculate Price Targets]
90
+ CalculateTargets1 --> MakeDecision1[Make Trading Decision]
91
+
92
+ %% Multi-Asset Flow
93
+ MultiAssetFlow --> FetchData2[Fetch Multi-Asset Data]
94
+ FetchData2 --> ProcessAssets[Process Each Asset]
95
+ ProcessAssets --> ComputeSignals2[Compute Signals per Asset]
96
+ ComputeSignals2 --> ValidateSignals2[Validate Signals per Asset]
97
+ ValidateSignals2 --> GenerateMultiPredictions[Generate Multi-Asset Predictions]
98
+ GenerateMultiPredictions --> AssetRotation{Asset Rotation Enabled?}
99
+ AssetRotation -->|Yes| EvaluateRotation[Evaluate Asset Rotation]
100
+ AssetRotation -->|No| BatchProcessing[Batch Processing]
101
+ EvaluateRotation --> ExecuteRotationTrades[Execute Rotation Trades]
102
+ ExecuteRotationTrades --> BatchProcessing
103
+ BatchProcessing --> OptimizePortfolio2[Optimize Portfolio per Batch]
104
+ OptimizePortfolio2 --> MakeMultiDecisions[Make Multi-Asset Decisions]
105
+
106
+ %% Decision Making Process
107
+ MakeDecision1 --> EvaluateCausalStability[Evaluate Causal Stability]
108
+ MakeMultiDecisions --> EvaluateCausalStability
109
+ EvaluateCausalStability --> CausalBlock{Causal Block?}
110
+ CausalBlock -->|Yes| HoldSignal1[Signal: HOLD]
111
+ CausalBlock -->|No| ComputeConfidence[Compute Confidence]
112
+
113
+ ComputeConfidence --> ComputeSignalStrength[Compute Signal Strength]
114
+ ComputeSignalStrength --> CheckThresholds{Meets Thresholds?}
115
+ CheckThresholds -->|No| HoldSignal2[Signal: HOLD]
116
+ CheckThresholds -->|Yes| DetermineSignal{Signal Direction?}
117
+
118
+ DetermineSignal -->|Positive| BuySignal[Signal: BUY]
119
+ DetermineSignal -->|Negative| SellSignal[Signal: SELL]
120
+ DetermineSignal -->|Neutral| HoldSignal3[Signal: HOLD]
121
+
122
+ BuySignal --> PositionSizing[Position Sizing Calculation]
123
+ SellSignal --> PositionSizing
124
+ HoldSignal1 --> RiskCheck
125
+ HoldSignal2 --> RiskCheck
126
+ HoldSignal3 --> RiskCheck
127
+
128
+ PositionSizing --> KellyCriterion{Kelly Criterion}
129
+ KellyCriterion --> RiskParity{Risk Parity}
130
+ RiskParity --> TargetVol[Target Volatility]
131
+ TargetVol --> AdjustForUncertainty[Adjust for Uncertainty]
132
+ AdjustForUncertainty --> AdjustForConfidence[Adjust for Confidence]
133
+ AdjustForConfidence --> RiskCheck[Risk Pre-Trade Check]
134
+
135
+ RiskCheck --> CheckPositionSize{Position Size OK?}
136
+ CheckPositionSize -->|No| AdjustSize[Adjust Position Size]
137
+ CheckPositionSize -->|Yes| CheckCircuitBreaker[Check Circuit Breaker]
138
+ AdjustSize --> CheckCircuitBreaker
139
+
140
+ CheckCircuitBreaker --> CircuitOK{Circuit OK?}
141
+ CircuitOK -->|No| BlockTrade[Block Trade - HOLD]
142
+ CircuitOK -->|Yes| CheckSystemState{System State?}
143
+
144
+ CheckSystemState -->|COOLDOWN/EXIT| SetCooldownSignal[Set COOLDOWN/EXIT Signal]
145
+ CheckSystemState -->|ACTIVE| CheckLiveMode{Live Trading Mode?}
146
+ SetCooldownSignal --> RecordDecision
147
+
148
+ CheckLiveMode -->|Yes| ExecuteTrade[Execute Trade via ExecutionEngine]
149
+ CheckLiveMode -->|No| LogDemoTrade[Log Demo Trade]
150
+
151
+ ExecuteTrade --> TradeSuccess{Trade Success?}
152
+ TradeSuccess -->|Yes| RecordFill[Record Live Fill]
153
+ TradeSuccess -->|No| LogError[Log Trade Error]
154
+ RecordFill --> UpdatePositions[Update Positions]
155
+ LogDemoTrade --> UpdatePositions
156
+ LogError --> UpdatePositions
157
+
158
+ UpdatePositions --> UpdatePortfolioMetrics[Update Portfolio Metrics]
159
+ UpdatePortfolioMetrics --> CheckPromotion{Promotion Threshold?}
160
+ CheckPromotion -->|Yes| PromoteBaseline[Promote Baseline]
161
+ CheckPromotion -->|No| CheckCooldownTrigger
162
+ PromoteBaseline --> CheckCooldownTrigger{Should Enter Cooldown?}
163
+
164
+ CheckCooldownTrigger -->|Yes| EnterCooldown[Enter Cooldown State]
165
+ CheckCooldownTrigger -->|No| MonitorSignals[Monitor Signal Health]
166
+ EnterCooldown --> MonitorSignals
167
+
168
+ MonitorSignals --> TrackPnL[Track PnL]
169
+ TrackPnL --> UpdateCRCADiagnostics[Update CRCA Diagnostics]
170
+ UpdateCRCADiagnostics --> CalculateAttribution[Calculate Performance Attribution]
171
+ CalculateAttribution --> RecordDecision[Record Decision & Results]
172
+
173
+ BlockTrade --> RecordDecision
174
+ ReturnCached --> End
175
+
176
+ RecordDecision --> BuildResult[Build Result Dictionary]
177
+ BuildResult --> CacheResult[Cache Result]
178
+ CacheResult --> End([End: Return Result])
179
+
180
+ %% Styling
181
+ classDef startEnd fill:#90EE90,stroke:#006400,stroke-width:3px
182
+ classDef process fill:#87CEEB,stroke:#4682B4,stroke-width:2px
183
+ classDef decision fill:#FFD700,stroke:#FF8C00,stroke-width:2px
184
+ classDef risk fill:#FF6B6B,stroke:#8B0000,stroke-width:2px
185
+ classDef execution fill:#9370DB,stroke:#4B0082,stroke-width:2px
186
+
187
+ class Start,End startEnd
188
+ class FetchData1,FetchData2,FetchAltData1,ComputeSignals1,ComputeSignals2,ValidateSignals1,ValidateSignals2,GeneratePredictions1,GenerateMultiPredictions,OptimizePortfolio1,OptimizePortfolio2,MakeDecision1,MakeMultiDecisions,PositionSizing,UpdatePositions,UpdatePortfolioMetrics,MonitorSignals,TrackPnL process
189
+ class InitCheck,CheckIncremental,CheckMultiAsset,AssetRotation,CausalBlock,CheckThresholds,DetermineSignal,CheckPositionSize,CircuitOK,CheckSystemState,CheckLiveMode,TradeSuccess,CheckPromotion,CheckCooldownTrigger decision
190
+ class RiskCheck,CheckCircuitBreaker,BlockTrade risk
191
+ class ExecuteTrade,RecordFill,LogDemoTrade execution
192
+ ```
193
+
194
+ ### Data Flow
195
+
196
+ 1. **Data Acquisition**: MarketDataClient fetches historical prices; AltDataClient gathers alternative data (social sentiment, on-chain metrics, news)
197
+ 2. **Signal Generation**: Multiple signal classes compute technical indicators, alternative data signals, and cross-asset relationships
198
+ 3. **Causal Validation**: CausalEngine builds an SCM and validates signals using causal reasoning
199
+ 4. **Prediction**: Ensemble of models (linear, tree-based, neural) generates forward-looking predictions
200
+ 5. **Portfolio Optimization**: PortfolioOptimizer allocates capital based on expected returns, covariance, and risk constraints
201
+ 6. **Risk Management**: RiskMonitor and CircuitBreaker enforce position limits and stop losses
202
+ 7. **Execution**: ExecutionEngine places trades (in live mode) or simulates them (in demo mode)
203
+
204
+ ---
205
+
206
+ ## Core Components Deep Dive {#core-components}
207
+
208
+ ### 1. MarketDataClient
209
+
210
+ **Purpose**: Fetches and normalizes market data from multiple sources.
211
+
212
+ **Key Methods**:
213
+ - `fetch_price_data()`: Retrieves historical OHLCV data for a single asset
214
+ - `fetch_multiple_assets()`: Batch fetches data for multiple assets with alignment
215
+ - `validate_unified_schema()`: Ensures all assets have consistent date ranges and column structures
216
+ - `compute_multi_asset_covariance()`: Calculates covariance matrices using EWMA (Exponentially Weighted Moving Average)
217
+
218
+ **Data Sources**:
219
+ - **Crypto**: CoinGecko API (free tier), with fallback to demo data
220
+ - **Stocks**: Yahoo Finance (via `yfinance`)
221
+ - **FX/Futures**: Yahoo Finance with symbol transformations
222
+
223
+ **Unified Schema**:
224
+ All data is normalized to:
225
+ ```python
226
+ {
227
+ 'date': pd.Timestamp,
228
+ 'price': float, # Close price
229
+ 'volume': float, # Trading volume
230
+ 'market_cap': float, # Market capitalization (0 for non-crypto)
231
+ 'returns': float # Computed as price.pct_change()
232
+ }
233
+ ```
234
+
235
+ **Why This Matters**: Consistent data schema enables multi-asset portfolio optimization and cross-asset signal generation.
236
+
237
+ ---
238
+
239
+ ### 2. AltDataClient (Alternative Data Connector)
240
+
241
+ **Purpose**: Aggregates non-price data sources that provide leading indicators of market movements.
242
+
243
+ **Data Sources**:
244
+
245
+ 1. **On-Chain Metrics** (Ethereum/blockchain):
246
+ - Active addresses growth
247
+ - Transaction volume trends
248
+ - Network growth rate
249
+ - Gas efficiency metrics
250
+ - Sources: The Graph, Etherscan API, direct RPC calls
251
+
252
+ 2. **Social Sentiment**:
253
+ - Twitter sentiment (via Twitter API v2)
254
+ - Reddit sentiment (via Reddit API)
255
+ - Social volume metrics
256
+ - Sources: Twitter Bearer Token, Reddit API
257
+
258
+ 3. **News Sentiment**:
259
+ - NewsAPI sentiment scores
260
+ - Headline sentiment analysis
261
+ - News volume spikes
262
+ - Source: NewsAPI
263
+
264
+ 4. **GitHub Activity**:
265
+ - Repository commit frequency
266
+ - Developer activity momentum
267
+ - Community health metrics
268
+ - Source: GitHub API
269
+
270
+ 5. **Exchange Metrics**:
271
+ - Funding rates (perpetual futures)
272
+ - Open interest
273
+ - Long/short ratios
274
+ - Source: Exchange APIs (Binance, Bybit)
275
+
276
+ **Caching Strategy**:
277
+ - **Redis** (preferred): Fast in-memory caching with TTL
278
+ - **File-based**: Fallback using `.cache/alternative_data/`
279
+ - **TTL by source**: On-chain (2h), social (30m), news (1h), GitHub (2h), exchange (30m)
280
+
281
+ **Confidence Weights**:
282
+ Each data source is weighted by:
283
+ - **Freshness** (40%): How recent is the data?
284
+ - **Reliability** (40%): Is the source available and consistent?
285
+ - **Stability** (20%): How stable is the signal over time?
286
+
287
+ ---
288
+
289
+ ### 3. Signal Generation Classes
290
+
291
+ CRCA-Q generates **hundreds of signals** across multiple categories:
292
+
293
+ #### TimeSeriesSignals
294
+
295
+ **Purpose**: Technical indicators based on price/volume history.
296
+
297
+ **Key Signals**:
298
+ - `momentum()`: Log price difference over lookback period (trend following)
299
+ - `short_term_reversal()`: Negative of recent returns (mean reversion)
300
+ - `sma_distance()`: Distance from price to moving average (normalized)
301
+ - `ema_trend()`: Exponential moving average trend
302
+ - `ma_crossover()`: Fast MA - Slow MA (normalized)
303
+ - `volatility_breakout()`: True Range breakout signal
304
+ - `price_level()`: Log price z-score (relative positioning)
305
+
306
+ **Theoretical Basis**: Based on academic literature (Jegadeesh & Titman 1993, Moskowitz et al. 2012) showing that momentum and reversal effects are persistent across markets.
307
+
308
+ #### VolatilitySignals
309
+
310
+ **Purpose**: Measure and predict volatility, a key risk factor.
311
+
312
+ **Key Signals**:
313
+ - `realized_variance()`: Rolling variance of returns
314
+ - `realized_volatility()`: Square root of variance (annualized)
315
+ - `garch_volatility()`: GARCH(1,1) model for volatility clustering
316
+ - `vol_of_vol()`: Volatility of volatility (uncertainty measure)
317
+ - `skewness()`: Third moment of returns (tail risk)
318
+ - `kurtosis()`: Fourth moment (fat tails)
319
+ - `volatility_clustering()`: Autocorrelation of absolute returns
320
+
321
+ **Why Volatility Matters**: Volatility is a **latent causal variable** in the SCM. High volatility can cause:
322
+ - Reduced liquidity (market makers widen spreads)
323
+ - Increased risk aversion (investors reduce positions)
324
+ - Feedback loops (volatility → price → volatility)
325
+
326
+ #### LiquiditySignals
327
+
328
+ **Purpose**: Measure market depth and trading costs.
329
+
330
+ **Key Signals**:
331
+ - `turnover()`: Volume / Market Cap (liquidity ratio)
332
+ - `volume_zscore()`: Standardized volume (unusual activity)
333
+ - `amihud_illiquidity()`: Price impact per unit volume (Amihud 2002)
334
+ - `bid_ask_spread()`: Spread / Mid price (transaction cost)
335
+ - `order_book_imbalance()`: (Bid volume - Ask volume) / Total volume
336
+ - `depth_slope()`: Order book depth asymmetry
337
+ - `trade_imbalance()`: Signed volume (buyer vs. seller pressure)
338
+ - `vpin()`: Volume-synchronized probability of informed trading
339
+
340
+ **Causal Role**: Liquidity is a **mediating variable**:
341
+ ```
342
+ Sentiment → Volume → Liquidity → Price Impact → Returns
343
+ ```
344
+
345
+ #### CrossSectionalSignals
346
+
347
+ **Purpose**: Compare assets relative to each other (multi-asset mode).
348
+
349
+ **Key Signals**:
350
+ - `size()`: Log market cap (size effect)
351
+ - `beta()`: Correlation with market returns (systematic risk)
352
+ - `residual_volatility()`: Idiosyncratic risk (after removing market factor)
353
+ - `low_volatility()`: Negative of volatility (low-vol anomaly)
354
+ - `cross_sectional_momentum()`: Relative momentum vs. other assets
355
+
356
+ **Academic Basis**: Fama-French factors, low-volatility anomaly (Ang et al. 2006).
357
+
358
+ #### RelativeValueSignals
359
+
360
+ **Purpose**: Identify mispricings between related assets.
361
+
362
+ **Key Signals**:
363
+ - `pair_spread()`: Price difference between two assets (pairs trading)
364
+ - `cointegration_residual()`: Deviation from long-run equilibrium
365
+ - `futures_basis()`: (Futures price - Spot price) / Spot price
366
+ - `cross_asset_correlation()`: Rolling correlation between assets
367
+ - `relative_strength()`: Performance relative to benchmark
368
+ - `btc_eth_correlation()`: Crypto-specific correlation signal
369
+
370
+ **Trading Strategy**: When spread deviates from historical mean, expect mean reversion.
371
+
372
+ #### RegimeSignals
373
+
374
+ **Purpose**: Detect market regimes (calm, volatile, trending, mean-reverting).
375
+
376
+ **Key Signals**:
377
+ - `volatility_regime()`: Classifies volatility into low/medium/high regimes
378
+ - `liquidity_regime()`: Classifies liquidity into normal/tight/loose regimes
379
+ - `post_event_drift()`: Price drift after earnings/news events
380
+
381
+ **Why Regimes Matter**: Different signals work in different regimes. Causal relationships may change:
382
+ - **Calm regime**: Momentum signals stronger
383
+ - **Volatile regime**: Mean reversion signals stronger
384
+ - **Liquidity crisis**: All signals weaken (market dysfunction)
385
+
386
+ #### MetaSignals
387
+
388
+ **Purpose**: Measure signal quality and stability.
389
+
390
+ **Key Signals**:
391
+ - `signal_crowding()`: Correlation of signal with market returns (overcrowding)
392
+ - `signal_instability()`: T-statistic of signal mean (statistical significance)
393
+
394
+ **Causal Interpretation**: If a signal is "crowded" (many traders use it), its predictive power may decay due to:
395
+ - **Reflexivity**: Traders' actions affect the market, breaking the causal chain
396
+ - **Arbitrage**: Other traders exploit the pattern, eliminating the edge
397
+
398
+ ---
399
+
400
+ ## Causal Reasoning Engine {#causal-reasoning-engine}
401
+
402
+ ### Theoretical Foundation
403
+
404
+ CRCA-Q implements **Structural Causal Models (SCMs)** as defined by Judea Pearl:
405
+
406
+ **Definition**: An SCM is a triple `(U, V, F)` where:
407
+ - `U`: Exogenous (unobserved) variables (e.g., market shocks)
408
+ - `V`: Endogenous (observed) variables (e.g., price, volume, sentiment)
409
+ - `F`: Structural equations that define causal relationships
410
+
411
+ **Example SCM** (simplified):
412
+ ```
413
+ M_t = f_M(U_M, Vol_{t-1}) # Momentum depends on volatility
414
+ Vol_t = f_Vol(U_Vol, L_t) # Volatility depends on liquidity
415
+ L_t = f_L(U_L, Volume_t) # Liquidity depends on volume
416
+ Price_t = f_Price(U_Price, M_t, Vol_t, L_t) # Price depends on momentum, vol, liquidity
417
+ ```
418
+
419
+ ### CausalEngine Implementation
420
+
421
+ **Class**: `CausalEngine`
422
+
423
+ **Core Components**:
424
+
425
+ 1. **CRCAAgent Integration**:
426
+ ```python
427
+ self.crca = CRCAAgent(
428
+ agent_name='crca-quant-trading',
429
+ model_name='gpt-4o-mini', # LLM for causal reasoning
430
+ max_loops=2 # (5 in longterm_mode)
431
+ )
432
+ ```
433
+
434
+ 2. **Latent Variables**:
435
+ - `M_t`: Momentum (trend strength)
436
+ - `Vol_t`: Volatility (uncertainty)
437
+ - `L_t`: Liquidity (market depth)
438
+ - `OF_t`: Order flow (buyer/seller imbalance)
439
+ - `R_i,t`: Return of asset i at time t
440
+ - `F_i,t`: Fundamental value of asset i at time t
441
+
442
+ 3. **SCM Building**:
443
+ ```python
444
+ def build_scm(self, variables: List[str], edges: List[Tuple[str, str]]):
445
+ # Adds causal edges to the graph
446
+ for parent, child in edges:
447
+ self.crca.add_causal_relationship(parent, child, strength=0.0)
448
+ ```
449
+
450
+ 4. **Fitting from Data**:
451
+ ```python
452
+ def fit_from_data(self, df: pd.DataFrame, variables: List[str], window: int = 30):
453
+ # Estimates edge strengths using least squares regression
454
+ # Applies exponential decay (alpha=0.9) for time-varying relationships
455
+ ```
456
+
457
+ ### Signal Validation via Causal Reasoning
458
+
459
+ **Class**: `SignalValidator`
460
+
461
+ **Validation Process**:
462
+
463
+ 1. **Mutual Information** (40% weight):
464
+ - Measures information-theoretic relationship between signal and target
465
+ - Uses correlation as proxy: `min(1.0, abs(correlation) * 2)`
466
+
467
+ 2. **Regime Invariance** (40% weight):
468
+ - Tests if signal-target relationship is stable across regimes
469
+ - Computes correlation in each regime, penalizes high variance
470
+ - **Causal signals should be regime-invariant** (Pearl's stability requirement)
471
+
472
+ 3. **Structural Consistency** (20% weight):
473
+ - Checks if signal maps to known latent variables in the SCM
474
+ - Example: Volatility signals should map to `Vol_t` node
475
+ - Graph boost: +0.15 if signal matches SCM structure
476
+
477
+ **Example Validation**:
478
+ ```python
479
+ signal_scores = {
480
+ 'signal_momentum': {
481
+ 'score': 0.85, # High score: strong causal relationship
482
+ 'relevance': 0.90, # High mutual information
483
+ 'stability': 0.80, # Stable across regimes
484
+ 'causal_role': 0.85 # Maps to M_t in SCM
485
+ },
486
+ 'signal_spurious': {
487
+ 'score': 0.35, # Low score: weak causal relationship
488
+ 'relevance': 0.40, # Low mutual information
489
+ 'stability': 0.20, # Unstable across regimes
490
+ 'causal_role': 0.45 # No clear SCM mapping
491
+ }
492
+ }
493
+ ```
494
+
495
+ ### Causal Stability Evaluation
496
+
497
+ **Method**: `_evaluate_causal_stability()`
498
+
499
+ **Process**:
500
+
501
+ 1. **Build SCM Dataset**:
502
+ - Extracts variables: `sentiment`, `liquidity`, `volume`, `momentum`, `trend`, `reversion_pressure`, `short_vol`, `future_return`
503
+ - Shifts all variables by 1 period (to ensure causality, not correlation)
504
+
505
+ 2. **Fit Causal Graph**:
506
+ ```python
507
+ edges = {
508
+ 'volume': ['sentiment', 'liquidity'],
509
+ 'momentum': ['sentiment', 'liquidity', 'volume'],
510
+ 'short_vol': ['regime_vol'],
511
+ 'future_return': ['momentum', 'trend', 'reversion_pressure', 'short_vol']
512
+ }
513
+ ```
514
+ - Uses least squares to estimate edge strengths (coefficients)
515
+
516
+ 3. **Monte Carlo Intervention Simulation**:
517
+ - For each parent variable, perturbs it by ±ε
518
+ - Propagates effect through causal chain
519
+ - Measures impact on `future_return`
520
+ - **Score**: Average magnitude of causal effects
521
+
522
+ 4. **Structural Score**:
523
+ - Normalizes edge coefficients by target standard deviation
524
+ - Measures strength of direct and indirect paths
525
+ - Example: `volume → momentum → future_return` (chain score)
526
+
527
+ 5. **Blocking Decision**:
528
+ - If causal score < threshold (0.35 default, 0.45 conservative), **block trading**
529
+ - Rationale: Unstable causal structure indicates regime change or model misspecification
530
+
531
+ **Why This Matters**: Unlike correlation-based systems, CRCA-Q can **detect when its model is wrong** and automatically reduce risk.
532
+
533
+ ---
534
+
535
+ ## Signal Generation and Validation {#signal-generation}
536
+
537
+ ### Signal Computation Pipeline
538
+
539
+ **Method**: `compute_signals()`
540
+
541
+ **Steps**:
542
+
543
+ 1. **Data Preparation**:
544
+ - Ensures `price` and `returns` columns exist
545
+ - Handles single-asset vs. multi-asset mode
546
+ - Caches signals in Redis (if available)
547
+
548
+ 2. **Time-Series Signals**:
549
+ ```python
550
+ signals['momentum'] = TimeSeriesSignals.momentum(data, lookback=12)
551
+ signals['sma_distance'] = TimeSeriesSignals.sma_distance(data, window=20)
552
+ signals['volatility'] = VolatilitySignals.realized_volatility(data, window=1)
553
+ ```
554
+
555
+ 3. **Alternative Data Signals**:
556
+ ```python
557
+ if 'onchain' in alternative_data_cache:
558
+ signals['active_addresses'] = OnChainSignals.active_addresses_growth(onchain_data)
559
+ if 'social' in alternative_data_cache:
560
+ signals['twitter_sentiment'] = SocialSentimentSignals.twitter_sentiment(social_data)
561
+ ```
562
+
563
+ 4. **Cross-Asset Signals** (multi-asset mode):
564
+ ```python
565
+ signals['btc_correlation'] = RelativeValueSignals.btc_eth_correlation(eth_data, btc_data)
566
+ signals['relative_strength'] = RelativeValueSignals.relative_strength(asset_data, market_data)
567
+ ```
568
+
569
+ 5. **Regime Detection**:
570
+ ```python
571
+ signals['volatility_regime'] = RegimeSignals.volatility_regime(data, window=20)
572
+ signals['liquidity_regime'] = RegimeSignals.liquidity_regime(data, window=20)
573
+ ```
574
+
575
+ 6. **Meta-Signals**:
576
+ ```python
577
+ signals['signal_crowding'] = MetaSignals.signal_crowding(data, 'momentum', market_returns)
578
+ ```
579
+
580
+ **Output**: DataFrame with columns for each signal, indexed by date.
581
+
582
+ ### Signal Validation
583
+
584
+ **Method**: `validate_signals()`
585
+
586
+ **Process**:
587
+
588
+ 1. **Causal Scoring** (for each signal):
589
+ ```python
590
+ causal_score = signal_validator.compute_causal_score(
591
+ signal_name='signal_momentum',
592
+ signal_values=signals_df['momentum'],
593
+ target=signals_df['returns'].shift(-1), # Future returns
594
+ regimes=signals_df['volatility_regime']
595
+ )
596
+ ```
597
+
598
+ 2. **Signal Filtering**:
599
+ - Removes signals with score < 0.3
600
+ - Removes signals with excessive NaN values
601
+ - Removes signals with zero variance
602
+
603
+ 3. **Signal Weighting**:
604
+ - Weights by causal score
605
+ - Applies decay factor (0.95) for recent performance
606
+ - Meta-learner optimizes weights based on historical performance
607
+
608
+ **Output**: Dictionary mapping signal names to scores:
609
+ ```python
610
+ {
611
+ 'signal_momentum': {'score': 0.85, 'relevance': 0.90, 'stability': 0.80, 'causal_role': 0.85},
612
+ 'signal_volatility': {'score': 0.72, 'relevance': 0.75, 'stability': 0.70, 'causal_role': 0.71},
613
+ ...
614
+ }
615
+ ```
616
+
617
+ ---
618
+
619
+ ## Portfolio Optimization {#portfolio-optimization}
620
+
621
+ ### Theoretical Foundation
622
+
623
+ CRCA-Q uses **Conditional Value at Risk (CVaR)** optimization, which is superior to mean-variance optimization because:
624
+
625
+ 1. **Tail Risk Focus**: CVaR measures expected loss in worst-case scenarios (e.g., worst 5% of outcomes)
626
+ 2. **Non-Normal Returns**: Works with fat-tailed distributions (common in crypto)
627
+ 3. **Regime Awareness**: Can incorporate regime-dependent constraints
628
+
629
+ ### PortfolioOptimizer Implementation
630
+
631
+ **Class**: `PortfolioOptimizer`
632
+
633
+ **Optimization Problem**:
634
+
635
+ ```
636
+ Maximize: μ'w - λ * w'Σw
637
+ Subject to:
638
+ - Σ|w_i| ≤ max_leverage
639
+ - w_i ≥ -max_leverage (no shorting beyond leverage limit)
640
+ - w_i ≤ max_leverage
641
+ - Σ|w_i|_type ≤ max_exposure_per_type (e.g., crypto ≤ 60%)
642
+ ```
643
+
644
+ Where:
645
+ - `μ`: Expected returns vector
646
+ - `Σ`: Covariance matrix (EWMA with λ=0.94)
647
+ - `w`: Portfolio weights
648
+ - `λ`: Risk aversion parameter (default: 1.0)
649
+
650
+ **Solver**:
651
+ - **CVXPY** (if available): Convex optimization solver (ECOS)
652
+ - **Fallback**: Analytical solution using inverse covariance matrix
653
+
654
+ **Multi-Asset Constraints**:
655
+ ```python
656
+ cross_asset_constraints = {
657
+ 'crypto': 0.6, # Max 60% in crypto
658
+ 'stock': 0.4, # Max 40% in stocks
659
+ 'fx': 0.2, # Max 20% in FX
660
+ }
661
+ ```
662
+
663
+ ### Covariance Estimation
664
+
665
+ **Class**: `CovarianceEstimator`
666
+
667
+ **Methods**:
668
+
669
+ 1. **EWMA Covariance**:
670
+ ```python
671
+ Σ_t = (1-α) * Σ_{t-1} + α * r_t * r_t'
672
+ ```
673
+ - `α = 0.06` (decay factor, equivalent to λ=0.94)
674
+ - Gives more weight to recent observations
675
+ - **Why**: Market relationships change over time
676
+
677
+ 2. **Shrinkage Estimator**:
678
+ ```python
679
+ Σ_shrink = shrinkage * (trace(Σ)/n * I) + (1-shrinkage) * Σ_sample
680
+ ```
681
+ - Shrinks sample covariance toward identity matrix
682
+ - Reduces estimation error when n_assets > n_observations
683
+ - **Why**: Prevents overfitting in high-dimensional settings
684
+
685
+ **Positive Semi-Definite Enforcement**:
686
+ - Adds small epsilon to diagonal: `Σ + εI`
687
+ - Eigendecomposition: `Σ = QΛQ'`, then `Λ = max(Λ, ε)`
688
+ - Reconstructs: `Σ_psd = Q * diag(Λ) * Q'`
689
+
690
+ ---
691
+
692
+ ## Risk Management Framework {#risk-management}
693
+
694
+ ### RiskMonitor
695
+
696
+ **Class**: `RiskMonitor`
697
+
698
+ **Constraints**:
699
+
700
+ 1. **Position Size Limits**:
701
+ - `max_position_size`: Max fraction per asset (default: 20%)
702
+ - `max_exposure_per_asset`: Hard cap (default: 15%)
703
+ - `max_exposure_per_type`: Max exposure per asset class
704
+
705
+ 2. **Leverage Limits**:
706
+ - `max_leverage`: Total leverage (default: 1.0 = no leverage)
707
+ - Checks: `Σ|w_i| ≤ max_leverage`
708
+
709
+ 3. **Correlation Limits**:
710
+ - `max_correlation`: Max pairwise correlation (default: 0.8)
711
+ - Prevents over-concentration in correlated assets
712
+
713
+ 4. **Volatility Limits**:
714
+ - `max_portfolio_volatility`: Max portfolio volatility (default: 20%)
715
+ - Adjusts position sizes if asset volatility exceeds limit
716
+
717
+ 5. **Drawdown Limits**:
718
+ - `max_drawdown`: Max allowed drawdown (default: 15%)
719
+ - Tracks peak portfolio value, blocks trades if drawdown exceeded
720
+
721
+ 6. **Dollar Risk**:
722
+ - `max_dollar_risk_per_trade`: Max dollar loss per trade
723
+ - Calculates: `position_size * stop_loss_distance * portfolio_value`
724
+
725
+ **Pre-Trade Checks**:
726
+ ```python
727
+ is_valid, reason, adjusted_size = risk_monitor.pre_trade_check(
728
+ signal='BUY',
729
+ position_size=0.15, # 15% of portfolio
730
+ current_positions={'BTC': 0.10, 'ETH': 0.05},
731
+ portfolio_value=10000,
732
+ stop_loss_distance=0.02, # 2% stop loss
733
+ asset_volatility=0.35, # 35% annualized vol
734
+ asset_type='crypto'
735
+ )
736
+ ```
737
+
738
+ **Output**: `(False, "Position size exceeds max_exposure_per_asset", 0.15)` → Adjusted to 15% cap.
739
+
740
+ ### CircuitBreaker
741
+
742
+ **Class**: `CircuitBreaker`
743
+
744
+ **Protection Mechanisms**:
745
+
746
+ 1. **Daily Loss Limit**:
747
+ - `max_daily_loss`: Max daily loss (default: 5%)
748
+ - Tracks cumulative PnL, trips if exceeded
749
+
750
+ 2. **Trade Frequency Limit**:
751
+ - `max_trades_per_day`: Max trades per day (default: 50)
752
+ - Prevents overtrading and API rate limit issues
753
+
754
+ 3. **Kill Switch**:
755
+ - `kill_switch_file`: File path (default: 'kill_switch.txt')
756
+ - If file exists, immediately stops all trading
757
+ - **Use case**: Manual emergency stop
758
+
759
+ **Integration**:
760
+ ```python
761
+ circuit_ok, reason = circuit_breaker.check_circuit()
762
+ if not circuit_ok:
763
+ logger.error(f"Circuit breaker tripped: {reason}")
764
+ return {'signal': 'HOLD', 'reason': reason}
765
+ ```
766
+
767
+ ### Position Sizing
768
+
769
+ **Class**: `PositionSizer`
770
+
771
+ **Methods**:
772
+
773
+ 1. **Kelly Criterion** (default):
774
+ ```
775
+ f* = (expected_return) / (volatility²)
776
+ ```
777
+ - Optimal bet size for long-term growth
778
+ - **Conservative adjustment**: Uses 25% of Kelly (`f* * 0.25`)
779
+
780
+ 2. **Risk Parity**:
781
+ ```
782
+ f* = target_vol / volatility
783
+ ```
784
+ - Equalizes risk contribution across assets
785
+ - Target volatility: 10-15% annualized
786
+
787
+ 3. **Target Volatility**:
788
+ ```
789
+ f* = target_vol / realized_vol
790
+ ```
791
+ - Maintains constant portfolio volatility
792
+ - Adjusts positions as volatility changes
793
+
794
+ **Uncertainty Penalty**:
795
+ ```python
796
+ adjusted_size = base_size * (1 - 0.5 * uncertainty_penalty)
797
+ ```
798
+ - Reduces position size when prediction uncertainty is high
799
+ - Uncertainty penalty: `min(uncertainty_ratio, 2.0)`
800
+
801
+ **Confidence Adjustment**:
802
+ ```python
803
+ final_size = adjusted_size * confidence
804
+ ```
805
+ - Scales position by prediction confidence (0-1)
806
+
807
+ ---
808
+
809
+ ## Execution and Backtesting {#execution-backtesting}
810
+
811
+ ### ExecutionEngine
812
+
813
+ **Class**: `ExecutionEngine`
814
+
815
+ **Supported Exchanges**:
816
+ - **Kraken**: Native REST API (KrakenRestClient)
817
+ - **Binance**: Via CCXT library
818
+ - **Coinbase**: Via CCXT library
819
+
820
+ **Trade Execution Flow**:
821
+
822
+ 1. **Symbol Derivation**:
823
+ ```python
824
+ symbol = execution_engine._derive_symbol('ETH')
825
+ # Returns: 'ETH/USD' (Kraken), 'ETH/USDT' (Binance), etc.
826
+ ```
827
+
828
+ 2. **Market Metadata**:
829
+ - Fetches min order size, price precision, lot size
830
+ - Validates trade size meets exchange requirements
831
+
832
+ 3. **Order Placement**:
833
+ ```python
834
+ trade_result = execution_engine.execute_trade(
835
+ signal='BUY',
836
+ size_fraction=0.1, # 10% of portfolio
837
+ base_symbol='ETH',
838
+ expected_return_pct=0.05, # 5% expected return
839
+ leverage=None # No leverage
840
+ )
841
+ ```
842
+
843
+ 4. **Transaction Cost Estimation**:
844
+ - **Spread**: Bid-ask spread (default: 5 bps)
845
+ - **Slippage**: Market impact (default: 10 bps)
846
+ - **Market Impact**: `0.5 * sqrt(trade_value / daily_volume)`
847
+ - **Fees**: Maker (0.1%) or Taker (0.2%)
848
+
849
+ 5. **Fill Recording**:
850
+ - Records: `symbol`, `side`, `amount`, `price`, `timestamp`
851
+ - Updates portfolio state
852
+
853
+ **Dry Run Mode**:
854
+ - If `dry_run=True`, simulates execution without placing orders
855
+ - Logs what *would* have been executed
856
+
857
+ ### BacktestEngine
858
+
859
+ **Class**: `BacktestEngine`
860
+
861
+ **Backtesting Methodology**:
862
+
863
+ 1. **Rolling Window**:
864
+ - **Train window**: 60 days (configurable)
865
+ - **Test window**: 7 days (configurable)
866
+ - **Step size**: 7 days (non-overlapping)
867
+
868
+ 2. **Walk-Forward Analysis**:
869
+ ```
870
+ Fold 1: Train [T-60:T], Test [T:T+7]
871
+ Fold 2: Train [T-53:T+7], Test [T+7:T+14]
872
+ Fold 3: Train [T-46:T+14], Test [T+14:T+21]
873
+ ...
874
+ ```
875
+
876
+ 3. **Trade Simulation**:
877
+ ```python
878
+ def _simulate_trade(self, signal, weight, price, capital, position, entry_price):
879
+ if signal == 'BUY':
880
+ execution_price = price * (1 + slippage_rate) # 0.05% slippage
881
+ commission = trade_cost * commission_rate # 0.1% commission
882
+ capital -= (trade_cost + commission)
883
+ position += trade_size
884
+ ```
885
+
886
+ 4. **Performance Metrics**:
887
+ - **Total Return**: `(final_capital - initial_capital) / initial_capital`
888
+ - **Annualized Return**: `(1 + total_return)^(252/days) - 1`
889
+ - **Volatility**: `std(daily_returns) * sqrt(252)`
890
+ - **Sharpe Ratio**: `annualized_return / volatility`
891
+ - **Sortino Ratio**: `annualized_return / downside_std` (only negative returns)
892
+ - **Max Drawdown**: `max((peak - equity) / peak)`
893
+ - **Calmar Ratio**: `annualized_return / max_drawdown`
894
+ - **Win Rate**: `wins / total_trades`
895
+
896
+ **Report Example**:
897
+ ```
898
+ ================================================================================
899
+ BACKTEST REPORT
900
+ ================================================================================
901
+
902
+ Initial Capital: $100,000.00
903
+ Final Capital: $115,000.00
904
+ Total Return: 15.00%
905
+
906
+ Performance Metrics:
907
+ Annualized Return: 18.50%
908
+ Volatility: 12.30%
909
+ Sharpe Ratio: 1.50
910
+ Sortino Ratio: 2.10
911
+ Max Drawdown: 8.20%
912
+ Calmar Ratio: 2.26
913
+ Win Rate: 55.00%
914
+ Total Trades: 120
915
+ ================================================================================
916
+ ```
917
+
918
+ ---
919
+
920
+ ## Comparison with Renaissance Technologies {#renaissance-comparison}
921
+
922
+ ### Renaissance Technologies Approach
923
+
924
+ Renaissance Technologies (Medallion Fund) is known for:
925
+
926
+ 1. **Statistical Arbitrage**: Exploiting short-term price discrepancies
927
+ 2. **Machine Learning**: Complex neural networks and ensemble methods
928
+ 3. **Data Mining**: Massive datasets, alternative data sources
929
+ 4. **High-Frequency Trading**: Microsecond execution, co-location
930
+ 5. **Secrecy**: Proprietary algorithms, limited disclosure
931
+
932
+ ### CRCA-Q Advantages
933
+
934
+ #### 1. **Causal Reasoning**
935
+
936
+ **Renaissance**: Relies on statistical patterns (correlations, cointegrations)
937
+
938
+ **CRCA-Q**: Uses causal models to understand *why* patterns exist
939
+
940
+ **Example**:
941
+ - **Renaissance**: "BTC and ETH prices move together (correlation = 0.85)"
942
+ - **CRCA-Q**: "BTC price → market sentiment → ETH price (causal chain), with strength β=0.72"
943
+
944
+ **Benefit**: Causal models are more robust to regime changes. If the correlation breaks, Renaissance may not know why. CRCA-Q can detect regime shifts via causal stability checks.
945
+
946
+ #### 2. **Interpretability**
947
+
948
+ **Renaissance**: "Black box" models (neural networks with thousands of parameters)
949
+
950
+ **CRCA-Q**: Interpretable causal graphs showing:
951
+ - Which variables cause which
952
+ - Strength of causal relationships
953
+ - Mediating pathways (e.g., sentiment → volume → price)
954
+
955
+ **Benefit**: Easier to debug, adapt, and explain to stakeholders.
956
+
957
+ #### 3. **Regime Adaptation**
958
+
959
+ **Renaissance**: May require retraining when regimes change
960
+
961
+ **CRCA-Q**: Automatically detects regime changes via:
962
+ - Causal stability evaluation
963
+ - Regime detection signals
964
+ - Signal validation (regime invariance)
965
+
966
+ **Benefit**: Faster adaptation to new market conditions.
967
+
968
+ #### 4. **Alternative Data Integration**
969
+
970
+ **Renaissance**: Uses proprietary data sources (satellite imagery, credit card transactions, etc.)
971
+
972
+ **CRCA-Q**: Integrates:
973
+ - On-chain blockchain data (unique to crypto)
974
+ - Social sentiment (Twitter, Reddit)
975
+ - GitHub activity (developer momentum)
976
+ - News sentiment
977
+ - Exchange metrics (funding rates, open interest)
978
+
979
+ **Benefit**: More comprehensive view of market drivers, especially in crypto.
980
+
981
+ #### 5. **Risk Management**
982
+
983
+ **Renaissance**: Sophisticated risk models (likely CVaR, stress testing)
984
+
985
+ **CRCA-Q**: Implements:
986
+ - CVaR optimization
987
+ - Causal stability blocking (unique feature)
988
+ - Multi-layer risk checks (position size, leverage, correlation, drawdown)
989
+ - Circuit breakers
990
+
991
+ **Benefit**: Similar risk management, but with causal validation layer.
992
+
993
+ ### CRCA-Q Limitations vs. Renaissance
994
+
995
+ 1. **Scale**: Renaissance trades billions; CRCA-Q is designed for smaller accounts
996
+ 2. **Speed**: Renaissance uses HFT infrastructure; CRCA-Q is not optimized for microsecond execution
997
+ 3. **Data**: Renaissance has proprietary datasets; CRCA-Q uses public APIs
998
+ 4. **Complexity**: Renaissance likely uses more sophisticated ML models (deep learning, reinforcement learning)
999
+
1000
+ ### When CRCA-Q Excels
1001
+
1002
+ 1. **Crypto Markets**: On-chain data provides unique alpha
1003
+ 2. **Regime Changes**: Causal models adapt faster than correlation-based systems
1004
+ 3. **Interpretability**: Useful for research, education, and regulatory compliance
1005
+ 4. **Small-Medium Accounts**: Designed for accounts $1K-$100K (Renaissance focuses on institutional scale)
1006
+
1007
+ ---
1008
+
1009
+ ## Quick Setup Guide {#quick-setup}
1010
+
1011
+ ### Installation
1012
+
1013
+ ```bash
1014
+ # Clone repository
1015
+ git clone <repo-url>
1016
+ cd swarms
1017
+
1018
+ # Install dependencies
1019
+ pip install pandas numpy requests loguru python-dotenv
1020
+ pip install ccxt websockets # For live trading
1021
+ pip install rich # For UI (optional)
1022
+
1023
+ # Optional (for advanced features):
1024
+ pip install torch xgboost lightgbm cvxpy optuna # ML and optimization
1025
+ pip install redis # For caching
1026
+ pip install yfinance # For stock data
1027
+ ```
1028
+
1029
+ ### Environment Variables
1030
+
1031
+ Create `.env` file:
1032
+
1033
+ ```bash
1034
+ # For live trading (Kraken example)
1035
+ KRAKEN_API_KEY=your_api_key
1036
+ KRAKEN_API_SECRET=your_api_secret
1037
+ KRAKEN_API_PASSPHRASE=your_passphrase # Optional for Kraken
1038
+
1039
+ # For alternative data (optional)
1040
+ TWITTER_BEARER_TOKEN=your_twitter_token
1041
+ NEWSAPI_KEY=your_newsapi_key
1042
+ ETHERSCAN_API_KEY=your_etherscan_key
1043
+ THEGRAPH_API_KEY=your_thegraph_key
1044
+ ```
1045
+
1046
+ ## Advanced Configuration {#advanced-configuration}
1047
+
1048
+ ### Trading Configuration
1049
+
1050
+ Edit `TRADING_CONFIG` in the file:
1051
+
1052
+ ```python
1053
+ TRADING_CONFIG = {
1054
+ 'account_size': 10000, # Account size in USD
1055
+ 'max_position_size': 0.3, # Max 30% per position
1056
+ 'max_position_hard_cap': 0.3, # Hard limit
1057
+ 'min_trade_value': 5.0, # Minimum $5 per trade
1058
+ 'position_size_multiplier': 1.0, # Scale all positions
1059
+ 'conservative_mode': True, # Tighter risk controls
1060
+ 'aggressive_mode': False, # More aggressive sizing
1061
+ 'cooldown_enabled': False, # Enable cooldown periods
1062
+ 'stop_loss_pct': -10.0, # -10% stop loss
1063
+ 'stop_gain_pct': 20.0, # +20% take profit
1064
+ 'promotion_threshold_pct': 0.1, # 10% gain triggers baseline promotion
1065
+ }
1066
+ ```
1067
+
1068
+ ### Longterm Mode Configuration
1069
+
1070
+ ```python
1071
+ LONGTERM_MODE_CONFIG = {
1072
+ 'prediction_horizon_days': 7, # 7-day predictions
1073
+ 'position_evaluation_interval_hours': 1, # Check every hour
1074
+ 'max_position_size': 0.005, # 0.5% max position
1075
+ 'min_confidence_threshold': 0.85, # 85% confidence required
1076
+ 'crca_max_loops': 5, # More thorough causal analysis
1077
+ 'use_crca_agent_heavily': True, # Heavy use of CRCA validation
1078
+ }
1079
+ ```
1080
+
1081
+ ### Alternative Data Configuration
1082
+
1083
+ ```python
1084
+ ALTERNATIVE_DATA_CONFIG = {
1085
+ 'use_real_apis': True, # Use real APIs (vs mock data)
1086
+ 'cache_type': 'redis', # 'redis' or 'file'
1087
+ 'window_size_days': 7, # 7-day lookback
1088
+ 'enabled_sources': {
1089
+ 'onchain': True,
1090
+ 'social': True,
1091
+ 'news': True,
1092
+ 'github': True,
1093
+ 'exchange': True,
1094
+ },
1095
+ 'cache_ttl': {
1096
+ 'onchain': 7200, # 2 hours
1097
+ 'social': 1800, # 30 minutes
1098
+ 'news': 3600, # 1 hour
1099
+ 'github': 7200, # 2 hours
1100
+ 'exchange': 1800, # 30 minutes
1101
+ },
1102
+ }
1103
+ ```
1104
+
1105
+ ### Signal Priority Weights
1106
+
1107
+ ```python
1108
+ PRIORITY_WEIGHTS = {
1109
+ 'predicted_return': 0.45, # 45% weight on predictions
1110
+ 'volume': 0.15, # 15% on volume
1111
+ 'volatility': 0.15, # 15% on volatility
1112
+ 'trend_strength': 0.10, # 10% on trend
1113
+ 'signal_quality': 0.10, # 10% on signal quality
1114
+ 'market_cap': 0.05, # 5% on market cap
1115
+ }
1116
+ ```
1117
+
1118
+ ---
1119
+
1120
+ ## Conclusion
1121
+
1122
+ CRCA-Q represents a novel approach to quantitative trading by integrating **causal reasoning** with traditional quantitative finance techniques. Unlike correlation-based systems, CRCA-Q:
1123
+
1124
+ 1. **Understands why** market movements occur (via SCMs)
1125
+ 2. **Adapts to regime changes** (via causal stability checks)
1126
+ 3. **Validates signals** using causal criteria (regime invariance, structural consistency)
1127
+ 4. **Provides interpretability** (causal graphs, not black boxes)
1128
+
1129
+ While not a replacement for institutional-grade systems like Renaissance Technologies, CRCA-Q offers unique advantages for:
1130
+ - **Crypto markets** (on-chain data integration)
1131
+ - **Research and education** (interpretable models)
1132
+ - **Small-medium accounts** ($1K-$100K)
1133
+ - **Regime-adaptive trading** (causal reasoning)
1134
+
1135
+ **Key Takeaway**: CRCA-Q is not just another ML trading system—it's a **causal reasoning system** that happens to trade. This fundamental difference makes it more robust, interpretable, and adaptable than traditional correlation-based approaches.# CRCA-Q: Causal Reasoning for Quantitative Trading
1136
+
1137
+ ## Executive Summary
1138
+
1139
+ CRCA-Q is a single-file quantitative trading system that integrates **causal reasoning** (based on Judea Pearl's Structural Causal Models and the CRCA framework) with traditional quantitative finance techniques. Unlike correlation-based systems, CRCA-Q uses **causal inference** to understand *why* market movements occur, enabling more robust predictions that remain valid across different market regimes.
1140
+
1141
+ This document provides a comprehensive technical deep-dive into the system's architecture, theoretical foundations, and practical implementation.
1142
+
1143
+ ---
1144
+
1145
+ ## Table of Contents
1146
+
1147
+ 1. [Philosophical Foundation: Causal vs. Correlational Trading](#philosophical-foundation)
1148
+ 2. [System Architecture Overview](#system-architecture)
1149
+ 3. [Core Components Deep Dive](#core-components)
1150
+ 4. [Causal Reasoning Engine](#causal-reasoning-engine)
1151
+ 5. [Signal Generation and Validation](#signal-generation)
1152
+ 6. [Portfolio Optimization](#portfolio-optimization)
1153
+ 7. [Risk Management Framework](#risk-management)
1154
+ 8. [Execution and Backtesting](#execution-backtesting)
1155
+ 9. [Comparison with Renaissance Technologies](#renaissance-comparison)
1156
+ 10. [Quick Setup Guide](#quick-setup)
1157
+ 11. [Advanced Configuration](#advanced-configuration)
1158
+
1159
+ ---
1160
+
1161
+ ## Philosophical Foundation: Causal vs. Correlational Trading {#philosophical-foundation}
1162
+
1163
+ ### The Fundamental Problem
1164
+
1165
+ Traditional quantitative trading systems (including many used by hedge funds) rely heavily on **correlational patterns**: "When X happens, Y tends to follow." This approach has critical limitations:
1166
+
1167
+ 1. **Regime Dependency**: Correlations break down when market regimes change (e.g., bull vs. bear markets)
1168
+ 2. **Spurious Relationships**: Many correlations are coincidental, not causal
1169
+ 3. **Lack of Interpretability**: It's unclear *why* a signal works, making it hard to adapt when conditions change
1170
+ 4. **Overfitting Risk**: Complex models can memorize historical patterns without understanding underlying mechanisms
1171
+
1172
+ ### The Causal Solution
1173
+
1174
+ CRCA-Q addresses these issues by implementing **causal reasoning** based on Judea Pearl's framework:
1175
+
1176
+ - **Structural Causal Models (SCMs)**: Represent market variables as nodes in a directed acyclic graph (DAG), where edges represent causal relationships
1177
+ - **Do-Calculus**: Uses Pearl's do-operator to reason about interventions ("What happens if we *force* sentiment to increase?")
1178
+ - **Counterfactual Reasoning**: Answers "What would have happened if..." questions, enabling robust scenario analysis
1179
+ - **Confounder Identification**: Distinguishes between direct causal effects and spurious correlations
1180
+
1181
+ ### Why This Matters
1182
+
1183
+ Consider a simple example: **Volume → Price Movement**
1184
+
1185
+ - **Correlational view**: "High volume correlates with price increases"
1186
+ - **Causal view**: "High volume *causes* increased liquidity, which *causes* reduced price impact, which *causes* more efficient price discovery"
1187
+
1188
+ The causal view is more robust because:
1189
+ - It explains *why* the relationship exists
1190
+ - It can predict behavior under interventions (e.g., "What if we artificially increase volume?")
1191
+ - It remains valid across different market regimes
1192
+
1193
+ ---
1194
+
1195
+ ## System Architecture Overview {#system-architecture}
1196
+
1197
+ CRCA-Q is organized into **five major subsystems**, each with specific responsibilities:
1198
+
1199
+ ```mermaid
1200
+ graph TB
1201
+ subgraph "Orchestration Layer"
1202
+ QTA[QuantTradingAgent<br/>Main Orchestrator]
1203
+ end
1204
+
1205
+ subgraph "Data Layer"
1206
+ MDC[MarketDataClient<br/>Price Data Fetching]
1207
+ ADC[AltDataClient<br/>Alternative Data]
1208
+ ESM[ExchangeSocketManager<br/>WebSocket Connections]
1209
+ OBT[OrderBookTracker<br/>Order Book Processing]
1210
+ end
1211
+
1212
+ subgraph "Signal Generation Layer"
1213
+ TSS[TimeSeriesSignals<br/>Momentum, Reversal, MA]
1214
+ VS[VolatilitySignals<br/>Realized Vol, GARCH]
1215
+ LS[LiquiditySignals<br/>Amihud, VPIN, Turnover]
1216
+ CSS[CrossSectionalSignals<br/>Size, Beta, Low Vol]
1217
+ RVS[RelativeValueSignals<br/>Pairs, Cointegration]
1218
+ RS[RegimeSignals<br/>Volatility/Liquidity Regimes]
1219
+ MS[MetaSignals<br/>Crowding, Instability]
1220
+ ASS[Alternative Signals<br/>On-chain, Social, News]
1221
+ end
1222
+
1223
+ subgraph "Causal Reasoning Layer"
1224
+ CE[CausalEngine<br/>SCM Builder]
1225
+ CRCA[CRCAAgent<br/>Causal Analysis]
1226
+ SV[SignalValidator<br/>Causal Validation]
1227
+ RD[RegimeDetector<br/>Regime Classification]
1228
+ CML[CausalMLModels<br/>Causal Forests/Transformers]
1229
+ JTE[JointTrainingEngine<br/>Joint Causal-ML Training]
1230
+ end
1231
+
1232
+ subgraph "Model & Prediction Layer"
1233
+ EP[EnsemblePredictor<br/>Multi-Model Ensemble]
1234
+ MF[ModelFactory<br/>Model Creation]
1235
+ TG[TargetGenerator<br/>Forward Returns]
1236
+ ML[MetaLearner<br/>Signal Weight Optimization]
1237
+ SWO[SignalWeightOptimizer<br/>Performance-Based Weights]
1238
+ MSel[ModelSelector<br/>Regime-Based Selection]
1239
+ end
1240
+
1241
+ subgraph "Portfolio Optimization Layer"
1242
+ PO[PortfolioOptimizer<br/>CVaR Optimization]
1243
+ CE2[CovarianceEstimator<br/>EWMA, Shrinkage]
1244
+ RM[RiskManager<br/>CVaR, Stress Testing]
1245
+ end
1246
+
1247
+ subgraph "Risk Management Layer"
1248
+ RMon[RiskMonitor<br/>Position Limits, Drawdown]
1249
+ CB[CircuitBreaker<br/>Daily Limits, Kill Switch]
1250
+ PS[PositionSizer<br/>Kelly, Risk Parity]
1251
+ TCM[TransactionCostModel<br/>Spread, Slippage, Impact]
1252
+ end
1253
+
1254
+ subgraph "Execution Layer"
1255
+ EE[ExecutionEngine<br/>Trade Execution]
1256
+ KRC[KrakenRestClient<br/>Kraken API]
1257
+ CCXT[CCXT Exchange<br/>Binance, Coinbase]
1258
+ TWAP[TWAPExecutor<br/>Time-Weighted Execution]
1259
+ VWAP[VWAPExecutor<br/>Volume-Weighted Execution]
1260
+ SR[SmartRouter<br/>Multi-Exchange Routing]
1261
+ ISO[ImplementationShortfallOptimizer<br/>Optimal Order Splitting]
1262
+ end
1263
+
1264
+ subgraph "Monitoring & Calibration Layer"
1265
+ MonSys[MonitoringSystem<br/>PnL Tracking, Diagnostics]
1266
+ CC[ConfidenceCalibrator<br/>Isotonic Calibration]
1267
+ BE[BacktestEngine<br/>Walk-Forward Analysis]
1268
+ end
1269
+
1270
+ subgraph "Asset Management Layer"
1271
+ AD[AssetDiscovery<br/>Asset Selection]
1272
+ ARM[AssetRotationManager<br/>Portfolio Rotation]
1273
+ EAC[ExchangeAssetCatalog<br/>Exchange Assets]
1274
+ end
1275
+
1276
+ subgraph "Caching & Storage"
1277
+ Redis[(Redis Cache<br/>Signals, Alternative Data)]
1278
+ FileCache[(File Cache<br/>Fallback Storage)]
1279
+ end
1280
+
1281
+ %% Orchestration connections
1282
+ QTA --> MDC
1283
+ QTA --> ADC
1284
+ QTA --> ESM
1285
+ QTA --> TSS
1286
+ QTA --> VS
1287
+ QTA --> LS
1288
+ QTA --> CSS
1289
+ QTA --> RVS
1290
+ QTA --> RS
1291
+ QTA --> MS
1292
+ QTA --> CE
1293
+ QTA --> SV
1294
+ QTA --> EP
1295
+ QTA --> PO
1296
+ QTA --> RMon
1297
+ QTA --> CB
1298
+ QTA --> EE
1299
+ QTA --> MonSys
1300
+ QTA --> AD
1301
+ QTA --> ARM
1302
+
1303
+ %% Data flow
1304
+ MDC --> Redis
1305
+ ADC --> Redis
1306
+ ADC --> FileCache
1307
+ ESM --> OBT
1308
+
1309
+ %% Signal flow
1310
+ TSS --> SV
1311
+ VS --> SV
1312
+ LS --> SV
1313
+ CSS --> SV
1314
+ RVS --> SV
1315
+ RS --> SV
1316
+ MS --> SV
1317
+ ASS --> SV
1318
+
1319
+ %% Causal flow
1320
+ SV --> CE
1321
+ CE --> CRCA
1322
+ CE --> CML
1323
+ CML --> JTE
1324
+ RD --> CE
1325
+
1326
+ %% Prediction flow
1327
+ SV --> EP
1328
+ EP --> MF
1329
+ TG --> EP
1330
+ ML --> EP
1331
+ SWO --> ML
1332
+ MSel --> ML
1333
+
1334
+ %% Portfolio flow
1335
+ EP --> PO
1336
+ CE2 --> PO
1337
+ RM --> PO
1338
+ PO --> PS
1339
+
1340
+ %% Risk flow
1341
+ PS --> RMon
1342
+ RMon --> CB
1343
+ TCM --> PS
1344
+ RMon --> EE
1345
+
1346
+ %% Execution flow
1347
+ EE --> KRC
1348
+ EE --> CCXT
1349
+ EE --> TWAP
1350
+ EE --> VWAP
1351
+ EE --> SR
1352
+ EE --> ISO
1353
+
1354
+ %% Monitoring flow
1355
+ EE --> MonSys
1356
+ EP --> CC
1357
+ CC --> MonSys
1358
+ QTA --> BE
1359
+
1360
+ %% Asset management flow
1361
+ AD --> EAC
1362
+ ARM --> AD
1363
+ ARM --> EE
1364
+
1365
+ %% Styling
1366
+ classDef orchestration fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#fff
1367
+ classDef data fill:#50C878,stroke:#2D7A4E,stroke-width:2px,color:#fff
1368
+ classDef signal fill:#FFB347,stroke:#CC8A2E,stroke-width:2px
1369
+ classDef causal fill:#9B59B6,stroke:#6B3A7A,stroke-width:2px,color:#fff
1370
+ classDef model fill:#E74C3C,stroke:#A93226,stroke-width:2px,color:#fff
1371
+ classDef portfolio fill:#3498DB,stroke:#2471A3,stroke-width:2px,color:#fff
1372
+ classDef risk fill:#E67E22,stroke:#A04000,stroke-width:2px,color:#fff
1373
+ classDef execution fill:#16A085,stroke:#0E6655,stroke-width:2px,color:#fff
1374
+ classDef monitoring fill:#95A5A6,stroke:#5D6D7E,stroke-width:2px,color:#fff
1375
+ classDef asset fill:#F39C12,stroke:#B9770E,stroke-width:2px
1376
+ classDef cache fill:#34495E,stroke:#1B2631,stroke-width:2px,color:#fff
1377
+
1378
+ class QTA orchestration
1379
+ class MDC,ADC,ESM,OBT data
1380
+ class TSS,VS,LS,CSS,RVS,RS,MS,ASS signal
1381
+ class CE,CRCA,SV,RD,CML,JTE causal
1382
+ class EP,MF,TG,ML,SWO,MSel model
1383
+ class PO,CE2,RM portfolio
1384
+ class RMon,CB,PS,TCM risk
1385
+ class EE,KRC,CCXT,TWAP,VWAP,SR,ISO execution
1386
+ class MonSys,CC,BE monitoring
1387
+ class AD,ARM,EAC asset
1388
+ class Redis,FileCache cache
1389
+ ```
1390
+
1391
+ ### Data Flow
1392
+
1393
+ 1. **Data Acquisition**: MarketDataClient fetches historical prices; AltDataClient gathers alternative data (social sentiment, on-chain metrics, news)
1394
+ 2. **Signal Generation**: Multiple signal classes compute technical indicators, alternative data signals, and cross-asset relationships
1395
+ 3. **Causal Validation**: CausalEngine builds an SCM and validates signals using causal reasoning
1396
+ 4. **Prediction**: Ensemble of models (linear, tree-based, neural) generates forward-looking predictions
1397
+ 5. **Portfolio Optimization**: PortfolioOptimizer allocates capital based on expected returns, covariance, and risk constraints
1398
+ 6. **Risk Management**: RiskMonitor and CircuitBreaker enforce position limits and stop losses
1399
+ 7. **Execution**: ExecutionEngine places trades (in live mode) or simulates them (in demo mode)
1400
+
1401
+ ---
1402
+
1403
+ ## Core Components Deep Dive {#core-components}
1404
+
1405
+ ### 1. MarketDataClient
1406
+
1407
+ **Purpose**: Fetches and normalizes market data from multiple sources.
1408
+
1409
+ **Key Methods**:
1410
+ - `fetch_price_data()`: Retrieves historical OHLCV data for a single asset
1411
+ - `fetch_multiple_assets()`: Batch fetches data for multiple assets with alignment
1412
+ - `validate_unified_schema()`: Ensures all assets have consistent date ranges and column structures
1413
+ - `compute_multi_asset_covariance()`: Calculates covariance matrices using EWMA (Exponentially Weighted Moving Average)
1414
+
1415
+ **Data Sources**:
1416
+ - **Crypto**: CoinGecko API (free tier), with fallback to demo data
1417
+ - **Stocks**: Yahoo Finance (via `yfinance`)
1418
+ - **FX/Futures**: Yahoo Finance with symbol transformations
1419
+
1420
+ **Unified Schema**:
1421
+ All data is normalized to:
1422
+ ```python
1423
+ {
1424
+ 'date': pd.Timestamp,
1425
+ 'price': float, # Close price
1426
+ 'volume': float, # Trading volume
1427
+ 'market_cap': float, # Market capitalization (0 for non-crypto)
1428
+ 'returns': float # Computed as price.pct_change()
1429
+ }
1430
+ ```
1431
+
1432
+ **Why This Matters**: Consistent data schema enables multi-asset portfolio optimization and cross-asset signal generation.
1433
+
1434
+ ---
1435
+
1436
+ ### 2. AltDataClient (Alternative Data Connector)
1437
+
1438
+ **Purpose**: Aggregates non-price data sources that provide leading indicators of market movements.
1439
+
1440
+ **Data Sources**:
1441
+
1442
+ 1. **On-Chain Metrics** (Ethereum/blockchain):
1443
+ - Active addresses growth
1444
+ - Transaction volume trends
1445
+ - Network growth rate
1446
+ - Gas efficiency metrics
1447
+ - Sources: The Graph, Etherscan API, direct RPC calls
1448
+
1449
+ 2. **Social Sentiment**:
1450
+ - Twitter sentiment (via Twitter API v2)
1451
+ - Reddit sentiment (via Reddit API)
1452
+ - Social volume metrics
1453
+ - Sources: Twitter Bearer Token, Reddit API
1454
+
1455
+ 3. **News Sentiment**:
1456
+ - NewsAPI sentiment scores
1457
+ - Headline sentiment analysis
1458
+ - News volume spikes
1459
+ - Source: NewsAPI
1460
+
1461
+ 4. **GitHub Activity**:
1462
+ - Repository commit frequency
1463
+ - Developer activity momentum
1464
+ - Community health metrics
1465
+ - Source: GitHub API
1466
+
1467
+ 5. **Exchange Metrics**:
1468
+ - Funding rates (perpetual futures)
1469
+ - Open interest
1470
+ - Long/short ratios
1471
+ - Source: Exchange APIs (Binance, Bybit)
1472
+
1473
+ **Caching Strategy**:
1474
+ - **Redis** (preferred): Fast in-memory caching with TTL
1475
+ - **File-based**: Fallback using `.cache/alternative_data/`
1476
+ - **TTL by source**: On-chain (2h), social (30m), news (1h), GitHub (2h), exchange (30m)
1477
+
1478
+ **Confidence Weights**:
1479
+ Each data source is weighted by:
1480
+ - **Freshness** (40%): How recent is the data?
1481
+ - **Reliability** (40%): Is the source available and consistent?
1482
+ - **Stability** (20%): How stable is the signal over time?
1483
+
1484
+ ---
1485
+
1486
+ ### 3. Signal Generation Classes
1487
+
1488
+ CRCA-Q generates **hundreds of signals** across multiple categories:
1489
+
1490
+ #### TimeSeriesSignals
1491
+
1492
+ **Purpose**: Technical indicators based on price/volume history.
1493
+
1494
+ **Key Signals**:
1495
+ - `momentum()`: Log price difference over lookback period (trend following)
1496
+ - `short_term_reversal()`: Negative of recent returns (mean reversion)
1497
+ - `sma_distance()`: Distance from price to moving average (normalized)
1498
+ - `ema_trend()`: Exponential moving average trend
1499
+ - `ma_crossover()`: Fast MA - Slow MA (normalized)
1500
+ - `volatility_breakout()`: True Range breakout signal
1501
+ - `price_level()`: Log price z-score (relative positioning)
1502
+
1503
+ **Theoretical Basis**: Based on academic literature (Jegadeesh & Titman 1993, Moskowitz et al. 2012) showing that momentum and reversal effects are persistent across markets.
1504
+
1505
+ #### VolatilitySignals
1506
+
1507
+ **Purpose**: Measure and predict volatility, a key risk factor.
1508
+
1509
+ **Key Signals**:
1510
+ - `realized_variance()`: Rolling variance of returns
1511
+ - `realized_volatility()`: Square root of variance (annualized)
1512
+ - `garch_volatility()`: GARCH(1,1) model for volatility clustering
1513
+ - `vol_of_vol()`: Volatility of volatility (uncertainty measure)
1514
+ - `skewness()`: Third moment of returns (tail risk)
1515
+ - `kurtosis()`: Fourth moment (fat tails)
1516
+ - `volatility_clustering()`: Autocorrelation of absolute returns
1517
+
1518
+ **Why Volatility Matters**: Volatility is a **latent causal variable** in the SCM. High volatility can cause:
1519
+ - Reduced liquidity (market makers widen spreads)
1520
+ - Increased risk aversion (investors reduce positions)
1521
+ - Feedback loops (volatility → price → volatility)
1522
+
1523
+ #### LiquiditySignals
1524
+
1525
+ **Purpose**: Measure market depth and trading costs.
1526
+
1527
+ **Key Signals**:
1528
+ - `turnover()`: Volume / Market Cap (liquidity ratio)
1529
+ - `volume_zscore()`: Standardized volume (unusual activity)
1530
+ - `amihud_illiquidity()`: Price impact per unit volume (Amihud 2002)
1531
+ - `bid_ask_spread()`: Spread / Mid price (transaction cost)
1532
+ - `order_book_imbalance()`: (Bid volume - Ask volume) / Total volume
1533
+ - `depth_slope()`: Order book depth asymmetry
1534
+ - `trade_imbalance()`: Signed volume (buyer vs. seller pressure)
1535
+ - `vpin()`: Volume-synchronized probability of informed trading
1536
+
1537
+ **Causal Role**: Liquidity is a **mediating variable**:
1538
+ ```
1539
+ Sentiment → Volume → Liquidity → Price Impact → Returns
1540
+ ```
1541
+
1542
+ #### CrossSectionalSignals
1543
+
1544
+ **Purpose**: Compare assets relative to each other (multi-asset mode).
1545
+
1546
+ **Key Signals**:
1547
+ - `size()`: Log market cap (size effect)
1548
+ - `beta()`: Correlation with market returns (systematic risk)
1549
+ - `residual_volatility()`: Idiosyncratic risk (after removing market factor)
1550
+ - `low_volatility()`: Negative of volatility (low-vol anomaly)
1551
+ - `cross_sectional_momentum()`: Relative momentum vs. other assets
1552
+
1553
+ **Academic Basis**: Fama-French factors, low-volatility anomaly (Ang et al. 2006).
1554
+
1555
+ #### RelativeValueSignals
1556
+
1557
+ **Purpose**: Identify mispricings between related assets.
1558
+
1559
+ **Key Signals**:
1560
+ - `pair_spread()`: Price difference between two assets (pairs trading)
1561
+ - `cointegration_residual()`: Deviation from long-run equilibrium
1562
+ - `futures_basis()`: (Futures price - Spot price) / Spot price
1563
+ - `cross_asset_correlation()`: Rolling correlation between assets
1564
+ - `relative_strength()`: Performance relative to benchmark
1565
+ - `btc_eth_correlation()`: Crypto-specific correlation signal
1566
+
1567
+ **Trading Strategy**: When spread deviates from historical mean, expect mean reversion.
1568
+
1569
+ #### RegimeSignals
1570
+
1571
+ **Purpose**: Detect market regimes (calm, volatile, trending, mean-reverting).
1572
+
1573
+ **Key Signals**:
1574
+ - `volatility_regime()`: Classifies volatility into low/medium/high regimes
1575
+ - `liquidity_regime()`: Classifies liquidity into normal/tight/loose regimes
1576
+ - `post_event_drift()`: Price drift after earnings/news events
1577
+
1578
+ **Why Regimes Matter**: Different signals work in different regimes. Causal relationships may change:
1579
+ - **Calm regime**: Momentum signals stronger
1580
+ - **Volatile regime**: Mean reversion signals stronger
1581
+ - **Liquidity crisis**: All signals weaken (market dysfunction)
1582
+
1583
+ #### MetaSignals
1584
+
1585
+ **Purpose**: Measure signal quality and stability.
1586
+
1587
+ **Key Signals**:
1588
+ - `signal_crowding()`: Correlation of signal with market returns (overcrowding)
1589
+ - `signal_instability()`: T-statistic of signal mean (statistical significance)
1590
+
1591
+ **Causal Interpretation**: If a signal is "crowded" (many traders use it), its predictive power may decay due to:
1592
+ - **Reflexivity**: Traders' actions affect the market, breaking the causal chain
1593
+ - **Arbitrage**: Other traders exploit the pattern, eliminating the edge
1594
+
1595
+ ---
1596
+
1597
+ ## Causal Reasoning Engine {#causal-reasoning-engine}
1598
+
1599
+ ### Theoretical Foundation
1600
+
1601
+ CRCA-Q implements **Structural Causal Models (SCMs)** as defined by Judea Pearl:
1602
+
1603
+ **Definition**: An SCM is a triple `(U, V, F)` where:
1604
+ - `U`: Exogenous (unobserved) variables (e.g., market shocks)
1605
+ - `V`: Endogenous (observed) variables (e.g., price, volume, sentiment)
1606
+ - `F`: Structural equations that define causal relationships
1607
+
1608
+ **Example SCM** (simplified):
1609
+ ```
1610
+ M_t = f_M(U_M, Vol_{t-1}) # Momentum depends on volatility
1611
+ Vol_t = f_Vol(U_Vol, L_t) # Volatility depends on liquidity
1612
+ L_t = f_L(U_L, Volume_t) # Liquidity depends on volume
1613
+ Price_t = f_Price(U_Price, M_t, Vol_t, L_t) # Price depends on momentum, vol, liquidity
1614
+ ```
1615
+
1616
+ ### CausalEngine Implementation
1617
+
1618
+ **Class**: `CausalEngine`
1619
+
1620
+ **Core Components**:
1621
+
1622
+ 1. **CRCAAgent Integration**:
1623
+ ```python
1624
+ self.crca = CRCAAgent(
1625
+ agent_name='crca-quant-trading',
1626
+ model_name='gpt-4o-mini', # LLM for causal reasoning
1627
+ max_loops=2 # (5 in longterm_mode)
1628
+ )
1629
+ ```
1630
+
1631
+ 2. **Latent Variables**:
1632
+ - `M_t`: Momentum (trend strength)
1633
+ - `Vol_t`: Volatility (uncertainty)
1634
+ - `L_t`: Liquidity (market depth)
1635
+ - `OF_t`: Order flow (buyer/seller imbalance)
1636
+ - `R_i,t`: Return of asset i at time t
1637
+ - `F_i,t`: Fundamental value of asset i at time t
1638
+
1639
+ 3. **SCM Building**:
1640
+ ```python
1641
+ def build_scm(self, variables: List[str], edges: List[Tuple[str, str]]):
1642
+ # Adds causal edges to the graph
1643
+ for parent, child in edges:
1644
+ self.crca.add_causal_relationship(parent, child, strength=0.0)
1645
+ ```
1646
+
1647
+ 4. **Fitting from Data**:
1648
+ ```python
1649
+ def fit_from_data(self, df: pd.DataFrame, variables: List[str], window: int = 30):
1650
+ # Estimates edge strengths using least squares regression
1651
+ # Applies exponential decay (alpha=0.9) for time-varying relationships
1652
+ ```
1653
+
1654
+ ### Signal Validation via Causal Reasoning
1655
+
1656
+ **Class**: `SignalValidator`
1657
+
1658
+ **Validation Process**:
1659
+
1660
+ 1. **Mutual Information** (40% weight):
1661
+ - Measures information-theoretic relationship between signal and target
1662
+ - Uses correlation as proxy: `min(1.0, abs(correlation) * 2)`
1663
+
1664
+ 2. **Regime Invariance** (40% weight):
1665
+ - Tests if signal-target relationship is stable across regimes
1666
+ - Computes correlation in each regime, penalizes high variance
1667
+ - **Causal signals should be regime-invariant** (Pearl's stability requirement)
1668
+
1669
+ 3. **Structural Consistency** (20% weight):
1670
+ - Checks if signal maps to known latent variables in the SCM
1671
+ - Example: Volatility signals should map to `Vol_t` node
1672
+ - Graph boost: +0.15 if signal matches SCM structure
1673
+
1674
+ **Example Validation**:
1675
+ ```python
1676
+ signal_scores = {
1677
+ 'signal_momentum': {
1678
+ 'score': 0.85, # High score: strong causal relationship
1679
+ 'relevance': 0.90, # High mutual information
1680
+ 'stability': 0.80, # Stable across regimes
1681
+ 'causal_role': 0.85 # Maps to M_t in SCM
1682
+ },
1683
+ 'signal_spurious': {
1684
+ 'score': 0.35, # Low score: weak causal relationship
1685
+ 'relevance': 0.40, # Low mutual information
1686
+ 'stability': 0.20, # Unstable across regimes
1687
+ 'causal_role': 0.45 # No clear SCM mapping
1688
+ }
1689
+ }
1690
+ ```
1691
+
1692
+ ### Causal Stability Evaluation
1693
+
1694
+ **Method**: `_evaluate_causal_stability()`
1695
+
1696
+ **Process**:
1697
+
1698
+ 1. **Build SCM Dataset**:
1699
+ - Extracts variables: `sentiment`, `liquidity`, `volume`, `momentum`, `trend`, `reversion_pressure`, `short_vol`, `future_return`
1700
+ - Shifts all variables by 1 period (to ensure causality, not correlation)
1701
+
1702
+ 2. **Fit Causal Graph**:
1703
+ ```python
1704
+ edges = {
1705
+ 'volume': ['sentiment', 'liquidity'],
1706
+ 'momentum': ['sentiment', 'liquidity', 'volume'],
1707
+ 'short_vol': ['regime_vol'],
1708
+ 'future_return': ['momentum', 'trend', 'reversion_pressure', 'short_vol']
1709
+ }
1710
+ ```
1711
+ - Uses least squares to estimate edge strengths (coefficients)
1712
+
1713
+ 3. **Monte Carlo Intervention Simulation**:
1714
+ - For each parent variable, perturbs it by ±ε
1715
+ - Propagates effect through causal chain
1716
+ - Measures impact on `future_return`
1717
+ - **Score**: Average magnitude of causal effects
1718
+
1719
+ 4. **Structural Score**:
1720
+ - Normalizes edge coefficients by target standard deviation
1721
+ - Measures strength of direct and indirect paths
1722
+ - Example: `volume → momentum → future_return` (chain score)
1723
+
1724
+ 5. **Blocking Decision**:
1725
+ - If causal score < threshold (0.35 default, 0.45 conservative), **block trading**
1726
+ - Rationale: Unstable causal structure indicates regime change or model misspecification
1727
+
1728
+ **Why This Matters**: Unlike correlation-based systems, CRCA-Q can **detect when its model is wrong** and automatically reduce risk.
1729
+
1730
+ ---
1731
+
1732
+ ## Signal Generation and Validation {#signal-generation}
1733
+
1734
+ ### Signal Computation Pipeline
1735
+
1736
+ **Method**: `compute_signals()`
1737
+
1738
+ **Steps**:
1739
+
1740
+ 1. **Data Preparation**:
1741
+ - Ensures `price` and `returns` columns exist
1742
+ - Handles single-asset vs. multi-asset mode
1743
+ - Caches signals in Redis (if available)
1744
+
1745
+ 2. **Time-Series Signals**:
1746
+ ```python
1747
+ signals['momentum'] = TimeSeriesSignals.momentum(data, lookback=12)
1748
+ signals['sma_distance'] = TimeSeriesSignals.sma_distance(data, window=20)
1749
+ signals['volatility'] = VolatilitySignals.realized_volatility(data, window=1)
1750
+ ```
1751
+
1752
+ 3. **Alternative Data Signals**:
1753
+ ```python
1754
+ if 'onchain' in alternative_data_cache:
1755
+ signals['active_addresses'] = OnChainSignals.active_addresses_growth(onchain_data)
1756
+ if 'social' in alternative_data_cache:
1757
+ signals['twitter_sentiment'] = SocialSentimentSignals.twitter_sentiment(social_data)
1758
+ ```
1759
+
1760
+ 4. **Cross-Asset Signals** (multi-asset mode):
1761
+ ```python
1762
+ signals['btc_correlation'] = RelativeValueSignals.btc_eth_correlation(eth_data, btc_data)
1763
+ signals['relative_strength'] = RelativeValueSignals.relative_strength(asset_data, market_data)
1764
+ ```
1765
+
1766
+ 5. **Regime Detection**:
1767
+ ```python
1768
+ signals['volatility_regime'] = RegimeSignals.volatility_regime(data, window=20)
1769
+ signals['liquidity_regime'] = RegimeSignals.liquidity_regime(data, window=20)
1770
+ ```
1771
+
1772
+ 6. **Meta-Signals**:
1773
+ ```python
1774
+ signals['signal_crowding'] = MetaSignals.signal_crowding(data, 'momentum', market_returns)
1775
+ ```
1776
+
1777
+ **Output**: DataFrame with columns for each signal, indexed by date.
1778
+
1779
+ ### Signal Validation
1780
+
1781
+ **Method**: `validate_signals()`
1782
+
1783
+ **Process**:
1784
+
1785
+ 1. **Causal Scoring** (for each signal):
1786
+ ```python
1787
+ causal_score = signal_validator.compute_causal_score(
1788
+ signal_name='signal_momentum',
1789
+ signal_values=signals_df['momentum'],
1790
+ target=signals_df['returns'].shift(-1), # Future returns
1791
+ regimes=signals_df['volatility_regime']
1792
+ )
1793
+ ```
1794
+
1795
+ 2. **Signal Filtering**:
1796
+ - Removes signals with score < 0.3
1797
+ - Removes signals with excessive NaN values
1798
+ - Removes signals with zero variance
1799
+
1800
+ 3. **Signal Weighting**:
1801
+ - Weights by causal score
1802
+ - Applies decay factor (0.95) for recent performance
1803
+ - Meta-learner optimizes weights based on historical performance
1804
+
1805
+ **Output**: Dictionary mapping signal names to scores:
1806
+ ```python
1807
+ {
1808
+ 'signal_momentum': {'score': 0.85, 'relevance': 0.90, 'stability': 0.80, 'causal_role': 0.85},
1809
+ 'signal_volatility': {'score': 0.72, 'relevance': 0.75, 'stability': 0.70, 'causal_role': 0.71},
1810
+ ...
1811
+ }
1812
+ ```
1813
+
1814
+ ---
1815
+
1816
+ ## Portfolio Optimization {#portfolio-optimization}
1817
+
1818
+ ### Theoretical Foundation
1819
+
1820
+ CRCA-Q uses **Conditional Value at Risk (CVaR)** optimization, which is superior to mean-variance optimization because:
1821
+
1822
+ 1. **Tail Risk Focus**: CVaR measures expected loss in worst-case scenarios (e.g., worst 5% of outcomes)
1823
+ 2. **Non-Normal Returns**: Works with fat-tailed distributions (common in crypto)
1824
+ 3. **Regime Awareness**: Can incorporate regime-dependent constraints
1825
+
1826
+ ### PortfolioOptimizer Implementation
1827
+
1828
+ **Class**: `PortfolioOptimizer`
1829
+
1830
+ **Optimization Problem**:
1831
+
1832
+ ```
1833
+ Maximize: μ'w - λ * w'Σw
1834
+ Subject to:
1835
+ - Σ|w_i| ≤ max_leverage
1836
+ - w_i ≥ -max_leverage (no shorting beyond leverage limit)
1837
+ - w_i ≤ max_leverage
1838
+ - Σ|w_i|_type ≤ max_exposure_per_type (e.g., crypto ≤ 60%)
1839
+ ```
1840
+
1841
+ Where:
1842
+ - `μ`: Expected returns vector
1843
+ - `Σ`: Covariance matrix (EWMA with λ=0.94)
1844
+ - `w`: Portfolio weights
1845
+ - `λ`: Risk aversion parameter (default: 1.0)
1846
+
1847
+ **Solver**:
1848
+ - **CVXPY** (if available): Convex optimization solver (ECOS)
1849
+ - **Fallback**: Analytical solution using inverse covariance matrix
1850
+
1851
+ **Multi-Asset Constraints**:
1852
+ ```python
1853
+ cross_asset_constraints = {
1854
+ 'crypto': 0.6, # Max 60% in crypto
1855
+ 'stock': 0.4, # Max 40% in stocks
1856
+ 'fx': 0.2, # Max 20% in FX
1857
+ }
1858
+ ```
1859
+
1860
+ ### Covariance Estimation
1861
+
1862
+ **Class**: `CovarianceEstimator`
1863
+
1864
+ **Methods**:
1865
+
1866
+ 1. **EWMA Covariance**:
1867
+ ```python
1868
+ Σ_t = (1-α) * Σ_{t-1} + α * r_t * r_t'
1869
+ ```
1870
+ - `α = 0.06` (decay factor, equivalent to λ=0.94)
1871
+ - Gives more weight to recent observations
1872
+ - **Why**: Market relationships change over time
1873
+
1874
+ 2. **Shrinkage Estimator**:
1875
+ ```python
1876
+ Σ_shrink = shrinkage * (trace(Σ)/n * I) + (1-shrinkage) * Σ_sample
1877
+ ```
1878
+ - Shrinks sample covariance toward identity matrix
1879
+ - Reduces estimation error when n_assets > n_observations
1880
+ - **Why**: Prevents overfitting in high-dimensional settings
1881
+
1882
+ **Positive Semi-Definite Enforcement**:
1883
+ - Adds small epsilon to diagonal: `Σ + εI`
1884
+ - Eigendecomposition: `Σ = QΛQ'`, then `Λ = max(Λ, ε)`
1885
+ - Reconstructs: `Σ_psd = Q * diag(Λ) * Q'`
1886
+
1887
+ ---
1888
+
1889
+ ## Risk Management Framework {#risk-management}
1890
+
1891
+ ### RiskMonitor
1892
+
1893
+ **Class**: `RiskMonitor`
1894
+
1895
+ **Constraints**:
1896
+
1897
+ 1. **Position Size Limits**:
1898
+ - `max_position_size`: Max fraction per asset (default: 20%)
1899
+ - `max_exposure_per_asset`: Hard cap (default: 15%)
1900
+ - `max_exposure_per_type`: Max exposure per asset class
1901
+
1902
+ 2. **Leverage Limits**:
1903
+ - `max_leverage`: Total leverage (default: 1.0 = no leverage)
1904
+ - Checks: `Σ|w_i| ≤ max_leverage`
1905
+
1906
+ 3. **Correlation Limits**:
1907
+ - `max_correlation`: Max pairwise correlation (default: 0.8)
1908
+ - Prevents over-concentration in correlated assets
1909
+
1910
+ 4. **Volatility Limits**:
1911
+ - `max_portfolio_volatility`: Max portfolio volatility (default: 20%)
1912
+ - Adjusts position sizes if asset volatility exceeds limit
1913
+
1914
+ 5. **Drawdown Limits**:
1915
+ - `max_drawdown`: Max allowed drawdown (default: 15%)
1916
+ - Tracks peak portfolio value, blocks trades if drawdown exceeded
1917
+
1918
+ 6. **Dollar Risk**:
1919
+ - `max_dollar_risk_per_trade`: Max dollar loss per trade
1920
+ - Calculates: `position_size * stop_loss_distance * portfolio_value`
1921
+
1922
+ **Pre-Trade Checks**:
1923
+ ```python
1924
+ is_valid, reason, adjusted_size = risk_monitor.pre_trade_check(
1925
+ signal='BUY',
1926
+ position_size=0.15, # 15% of portfolio
1927
+ current_positions={'BTC': 0.10, 'ETH': 0.05},
1928
+ portfolio_value=10000,
1929
+ stop_loss_distance=0.02, # 2% stop loss
1930
+ asset_volatility=0.35, # 35% annualized vol
1931
+ asset_type='crypto'
1932
+ )
1933
+ ```
1934
+
1935
+ **Output**: `(False, "Position size exceeds max_exposure_per_asset", 0.15)` → Adjusted to 15% cap.
1936
+
1937
+ ### CircuitBreaker
1938
+
1939
+ **Class**: `CircuitBreaker`
1940
+
1941
+ **Protection Mechanisms**:
1942
+
1943
+ 1. **Daily Loss Limit**:
1944
+ - `max_daily_loss`: Max daily loss (default: 5%)
1945
+ - Tracks cumulative PnL, trips if exceeded
1946
+
1947
+ 2. **Trade Frequency Limit**:
1948
+ - `max_trades_per_day`: Max trades per day (default: 50)
1949
+ - Prevents overtrading and API rate limit issues
1950
+
1951
+ 3. **Kill Switch**:
1952
+ - `kill_switch_file`: File path (default: 'kill_switch.txt')
1953
+ - If file exists, immediately stops all trading
1954
+ - **Use case**: Manual emergency stop
1955
+
1956
+ **Integration**:
1957
+ ```python
1958
+ circuit_ok, reason = circuit_breaker.check_circuit()
1959
+ if not circuit_ok:
1960
+ logger.error(f"Circuit breaker tripped: {reason}")
1961
+ return {'signal': 'HOLD', 'reason': reason}
1962
+ ```
1963
+
1964
+ ### Position Sizing
1965
+
1966
+ **Class**: `PositionSizer`
1967
+
1968
+ **Methods**:
1969
+
1970
+ 1. **Kelly Criterion** (default):
1971
+ ```
1972
+ f* = (expected_return) / (volatility²)
1973
+ ```
1974
+ - Optimal bet size for long-term growth
1975
+ - **Conservative adjustment**: Uses 25% of Kelly (`f* * 0.25`)
1976
+
1977
+ 2. **Risk Parity**:
1978
+ ```
1979
+ f* = target_vol / volatility
1980
+ ```
1981
+ - Equalizes risk contribution across assets
1982
+ - Target volatility: 10-15% annualized
1983
+
1984
+ 3. **Target Volatility**:
1985
+ ```
1986
+ f* = target_vol / realized_vol
1987
+ ```
1988
+ - Maintains constant portfolio volatility
1989
+ - Adjusts positions as volatility changes
1990
+
1991
+ **Uncertainty Penalty**:
1992
+ ```python
1993
+ adjusted_size = base_size * (1 - 0.5 * uncertainty_penalty)
1994
+ ```
1995
+ - Reduces position size when prediction uncertainty is high
1996
+ - Uncertainty penalty: `min(uncertainty_ratio, 2.0)`
1997
+
1998
+ **Confidence Adjustment**:
1999
+ ```python
2000
+ final_size = adjusted_size * confidence
2001
+ ```
2002
+ - Scales position by prediction confidence (0-1)
2003
+
2004
+ ---
2005
+
2006
+ ## Execution and Backtesting {#execution-backtesting}
2007
+
2008
+ ### ExecutionEngine
2009
+
2010
+ **Class**: `ExecutionEngine`
2011
+
2012
+ **Supported Exchanges**:
2013
+ - **Kraken**: Native REST API (KrakenRestClient)
2014
+ - **Binance**: Via CCXT library
2015
+ - **Coinbase**: Via CCXT library
2016
+
2017
+ **Trade Execution Flow**:
2018
+
2019
+ 1. **Symbol Derivation**:
2020
+ ```python
2021
+ symbol = execution_engine._derive_symbol('ETH')
2022
+ # Returns: 'ETH/USD' (Kraken), 'ETH/USDT' (Binance), etc.
2023
+ ```
2024
+
2025
+ 2. **Market Metadata**:
2026
+ - Fetches min order size, price precision, lot size
2027
+ - Validates trade size meets exchange requirements
2028
+
2029
+ 3. **Order Placement**:
2030
+ ```python
2031
+ trade_result = execution_engine.execute_trade(
2032
+ signal='BUY',
2033
+ size_fraction=0.1, # 10% of portfolio
2034
+ base_symbol='ETH',
2035
+ expected_return_pct=0.05, # 5% expected return
2036
+ leverage=None # No leverage
2037
+ )
2038
+ ```
2039
+
2040
+ 4. **Transaction Cost Estimation**:
2041
+ - **Spread**: Bid-ask spread (default: 5 bps)
2042
+ - **Slippage**: Market impact (default: 10 bps)
2043
+ - **Market Impact**: `0.5 * sqrt(trade_value / daily_volume)`
2044
+ - **Fees**: Maker (0.1%) or Taker (0.2%)
2045
+
2046
+ 5. **Fill Recording**:
2047
+ - Records: `symbol`, `side`, `amount`, `price`, `timestamp`
2048
+ - Updates portfolio state
2049
+
2050
+ **Dry Run Mode**:
2051
+ - If `dry_run=True`, simulates execution without placing orders
2052
+ - Logs what *would* have been executed
2053
+
2054
+ ### BacktestEngine
2055
+
2056
+ **Class**: `BacktestEngine`
2057
+
2058
+ **Backtesting Methodology**:
2059
+
2060
+ 1. **Rolling Window**:
2061
+ - **Train window**: 60 days (configurable)
2062
+ - **Test window**: 7 days (configurable)
2063
+ - **Step size**: 7 days (non-overlapping)
2064
+
2065
+ 2. **Walk-Forward Analysis**:
2066
+ ```
2067
+ Fold 1: Train [T-60:T], Test [T:T+7]
2068
+ Fold 2: Train [T-53:T+7], Test [T+7:T+14]
2069
+ Fold 3: Train [T-46:T+14], Test [T+14:T+21]
2070
+ ...
2071
+ ```
2072
+
2073
+ 3. **Trade Simulation**:
2074
+ ```python
2075
+ def _simulate_trade(self, signal, weight, price, capital, position, entry_price):
2076
+ if signal == 'BUY':
2077
+ execution_price = price * (1 + slippage_rate) # 0.05% slippage
2078
+ commission = trade_cost * commission_rate # 0.1% commission
2079
+ capital -= (trade_cost + commission)
2080
+ position += trade_size
2081
+ ```
2082
+
2083
+ 4. **Performance Metrics**:
2084
+ - **Total Return**: `(final_capital - initial_capital) / initial_capital`
2085
+ - **Annualized Return**: `(1 + total_return)^(252/days) - 1`
2086
+ - **Volatility**: `std(daily_returns) * sqrt(252)`
2087
+ - **Sharpe Ratio**: `annualized_return / volatility`
2088
+ - **Sortino Ratio**: `annualized_return / downside_std` (only negative returns)
2089
+ - **Max Drawdown**: `max((peak - equity) / peak)`
2090
+ - **Calmar Ratio**: `annualized_return / max_drawdown`
2091
+ - **Win Rate**: `wins / total_trades`
2092
+
2093
+ **Report Example**:
2094
+ ```
2095
+ ================================================================================
2096
+ BACKTEST REPORT
2097
+ ================================================================================
2098
+
2099
+ Initial Capital: $100,000.00
2100
+ Final Capital: $115,000.00
2101
+ Total Return: 15.00%
2102
+
2103
+ Performance Metrics:
2104
+ Annualized Return: 18.50%
2105
+ Volatility: 12.30%
2106
+ Sharpe Ratio: 1.50
2107
+ Sortino Ratio: 2.10
2108
+ Max Drawdown: 8.20%
2109
+ Calmar Ratio: 2.26
2110
+ Win Rate: 55.00%
2111
+ Total Trades: 120
2112
+ ================================================================================
2113
+ ```
2114
+
2115
+ ---
2116
+
2117
+ ## Comparison with Renaissance Technologies {#renaissance-comparison}
2118
+
2119
+ ### Renaissance Technologies Approach
2120
+
2121
+ Renaissance Technologies (Medallion Fund) is known for:
2122
+
2123
+ 1. **Statistical Arbitrage**: Exploiting short-term price discrepancies
2124
+ 2. **Machine Learning**: Complex neural networks and ensemble methods
2125
+ 3. **Data Mining**: Massive datasets, alternative data sources
2126
+ 4. **High-Frequency Trading**: Microsecond execution, co-location
2127
+ 5. **Secrecy**: Proprietary algorithms, limited disclosure
2128
+
2129
+ ### CRCA-Q Advantages
2130
+
2131
+ #### 1. **Causal Reasoning**
2132
+
2133
+ **Renaissance**: Relies on statistical patterns (correlations, cointegrations)
2134
+
2135
+ **CRCA-Q**: Uses causal models to understand *why* patterns exist
2136
+
2137
+ **Example**:
2138
+ - **Renaissance**: "BTC and ETH prices move together (correlation = 0.85)"
2139
+ - **CRCA-Q**: "BTC price → market sentiment → ETH price (causal chain), with strength β=0.72"
2140
+
2141
+ **Benefit**: Causal models are more robust to regime changes. If the correlation breaks, Renaissance may not know why. CRCA-Q can detect regime shifts via causal stability checks.
2142
+
2143
+ #### 2. **Interpretability**
2144
+
2145
+ **Renaissance**: "Black box" models (neural networks with thousands of parameters)
2146
+
2147
+ **CRCA-Q**: Interpretable causal graphs showing:
2148
+ - Which variables cause which
2149
+ - Strength of causal relationships
2150
+ - Mediating pathways (e.g., sentiment → volume → price)
2151
+
2152
+ **Benefit**: Easier to debug, adapt, and explain to stakeholders.
2153
+
2154
+ #### 3. **Regime Adaptation**
2155
+
2156
+ **Renaissance**: May require retraining when regimes change
2157
+
2158
+ **CRCA-Q**: Automatically detects regime changes via:
2159
+ - Causal stability evaluation
2160
+ - Regime detection signals
2161
+ - Signal validation (regime invariance)
2162
+
2163
+ **Benefit**: Faster adaptation to new market conditions.
2164
+
2165
+ #### 4. **Alternative Data Integration**
2166
+
2167
+ **Renaissance**: Uses proprietary data sources (satellite imagery, credit card transactions, etc.)
2168
+
2169
+ **CRCA-Q**: Integrates:
2170
+ - On-chain blockchain data (unique to crypto)
2171
+ - Social sentiment (Twitter, Reddit)
2172
+ - GitHub activity (developer momentum)
2173
+ - News sentiment
2174
+ - Exchange metrics (funding rates, open interest)
2175
+
2176
+ **Benefit**: More comprehensive view of market drivers, especially in crypto.
2177
+
2178
+ #### 5. **Risk Management**
2179
+
2180
+ **Renaissance**: Sophisticated risk models (likely CVaR, stress testing)
2181
+
2182
+ **CRCA-Q**: Implements:
2183
+ - CVaR optimization
2184
+ - Causal stability blocking (unique feature)
2185
+ - Multi-layer risk checks (position size, leverage, correlation, drawdown)
2186
+ - Circuit breakers
2187
+
2188
+ **Benefit**: Similar risk management, but with causal validation layer.
2189
+
2190
+ ### CRCA-Q Limitations vs. Renaissance
2191
+
2192
+ 1. **Scale**: Renaissance trades billions; CRCA-Q is designed for smaller accounts
2193
+ 2. **Speed**: Renaissance uses HFT infrastructure; CRCA-Q is not optimized for microsecond execution
2194
+ 3. **Data**: Renaissance has proprietary datasets; CRCA-Q uses public APIs
2195
+ 4. **Complexity**: Renaissance likely uses more sophisticated ML models (deep learning, reinforcement learning)
2196
+
2197
+ ### When CRCA-Q Excels
2198
+
2199
+ 1. **Crypto Markets**: On-chain data provides unique alpha
2200
+ 2. **Regime Changes**: Causal models adapt faster than correlation-based systems
2201
+ 3. **Interpretability**: Useful for research, education, and regulatory compliance
2202
+ 4. **Small-Medium Accounts**: Designed for accounts $1K-$100K (Renaissance focuses on institutional scale)
2203
+
2204
+ ---
2205
+
2206
+ ## Quick Setup Guide {#quick-setup}
2207
+
2208
+ ### Installation
2209
+
2210
+ ```bash
2211
+ # Clone repository
2212
+ git clone https://github.com/IlumCI/CR-CA
2213
+ cd CRCA
2214
+
2215
+ # Install dependencies
2216
+ pip install pandas numpy requests loguru python-dotenv
2217
+ pip install ccxt websockets # For live trading
2218
+ pip install rich # For UI (optional)
2219
+
2220
+ # Optional (for advanced features):
2221
+ pip install torch xgboost lightgbm cvxpy optuna # ML and optimization
2222
+ pip install redis # For caching
2223
+ pip install yfinance # For stock data
2224
+ ```
2225
+
2226
+ ### Environment Variables
2227
+
2228
+ Create `.env` file:
2229
+
2230
+ ```bash
2231
+ # For live trading (Kraken example)
2232
+ KRAKEN_API_KEY=your_api_key
2233
+ KRAKEN_API_SECRET=your_api_secret
2234
+ KRAKEN_API_PASSPHRASE=your_passphrase # Optional for Kraken
2235
+
2236
+ # For alternative data (optional)
2237
+ TWITTER_BEARER_TOKEN=your_twitter_token
2238
+ NEWSAPI_KEY=your_newsapi_key
2239
+ ETHERSCAN_API_KEY=your_etherscan_key
2240
+ THEGRAPH_API_KEY=your_thegraph_key
2241
+ ```
2242
+
2243
+
2244
+ ## Advanced Configuration {#advanced-configuration}
2245
+
2246
+ ### Trading Configuration
2247
+
2248
+ Edit `TRADING_CONFIG` in the file:
2249
+
2250
+ ```python
2251
+ TRADING_CONFIG = {
2252
+ 'account_size': 10000, # Account size in USD
2253
+ 'max_position_size': 0.3, # Max 30% per position
2254
+ 'max_position_hard_cap': 0.3, # Hard limit
2255
+ 'min_trade_value': 5.0, # Minimum $5 per trade
2256
+ 'position_size_multiplier': 1.0, # Scale all positions
2257
+ 'conservative_mode': True, # Tighter risk controls
2258
+ 'aggressive_mode': False, # More aggressive sizing
2259
+ 'cooldown_enabled': False, # Enable cooldown periods
2260
+ 'stop_loss_pct': -10.0, # -10% stop loss
2261
+ 'stop_gain_pct': 20.0, # +20% take profit
2262
+ 'promotion_threshold_pct': 0.1, # 10% gain triggers baseline promotion
2263
+ }
2264
+ ```
2265
+
2266
+ ### Longterm Mode Configuration
2267
+
2268
+ ```python
2269
+ LONGTERM_MODE_CONFIG = {
2270
+ 'prediction_horizon_days': 7, # 7-day predictions
2271
+ 'position_evaluation_interval_hours': 1, # Check every hour
2272
+ 'max_position_size': 0.005, # 0.5% max position
2273
+ 'min_confidence_threshold': 0.85, # 85% confidence required
2274
+ 'crca_max_loops': 5, # More thorough causal analysis
2275
+ 'use_crca_agent_heavily': True, # Heavy use of CRCA validation
2276
+ }
2277
+ ```
2278
+
2279
+ ### Alternative Data Configuration
2280
+
2281
+ ```python
2282
+ ALTERNATIVE_DATA_CONFIG = {
2283
+ 'use_real_apis': True, # Use real APIs (vs mock data)
2284
+ 'cache_type': 'redis', # 'redis' or 'file'
2285
+ 'window_size_days': 7, # 7-day lookback
2286
+ 'enabled_sources': {
2287
+ 'onchain': True,
2288
+ 'social': True,
2289
+ 'news': True,
2290
+ 'github': True,
2291
+ 'exchange': True,
2292
+ },
2293
+ 'cache_ttl': {
2294
+ 'onchain': 7200, # 2 hours
2295
+ 'social': 1800, # 30 minutes
2296
+ 'news': 3600, # 1 hour
2297
+ 'github': 7200, # 2 hours
2298
+ 'exchange': 1800, # 30 minutes
2299
+ },
2300
+ }
2301
+ ```
2302
+
2303
+ ### Signal Priority Weights
2304
+
2305
+ ```python
2306
+ PRIORITY_WEIGHTS = {
2307
+ 'predicted_return': 0.45, # 45% weight on predictions
2308
+ 'volume': 0.15, # 15% on volume
2309
+ 'volatility': 0.15, # 15% on volatility
2310
+ 'trend_strength': 0.10, # 10% on trend
2311
+ 'signal_quality': 0.10, # 10% on signal quality
2312
+ 'market_cap': 0.05, # 5% on market cap
2313
+ }
2314
+ ```
2315
+
2316
+ ---
2317
+
2318
+ ## Conclusion
2319
+
2320
+ CRCA-Q represents a novel approach to quantitative trading by integrating **causal reasoning** with traditional quantitative finance techniques. Unlike correlation-based systems, CRCA-Q:
2321
+
2322
+ 1. **Understands why** market movements occur (via SCMs)
2323
+ 2. **Adapts to regime changes** (via causal stability checks)
2324
+ 3. **Validates signals** using causal criteria (regime invariance, structural consistency)
2325
+ 4. **Provides interpretability** (causal graphs, not black boxes)
2326
+
2327
+ While not a replacement for institutional-grade systems like Renaissance Technologies, CRCA-Q offers unique advantages for:
2328
+ - **Crypto markets** (on-chain data integration)
2329
+ - **Research and education** (interpretable models)
2330
+ - **Small-medium accounts** ($1K-$100K)
2331
+ - **Regime-adaptive trading** (causal reasoning)
2332
+
2333
+ **Key Takeaway**: CRCA-Q is not just another ML trading system—it's a **causal reasoning system** that happens to trade. This fundamental difference makes it more robust, interpretable, and adaptable than traditional correlation-based approaches.