FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Update analytics wrappers with enhanced FFN, Fortitudo, and Functime services
Aviral2610937af0c26960
diff --git a/fincept-terminal-desktop/bun.lock b/fincept-terminal-desktop/bun.lockindex 939061604..a06e28a7b 100644--- a/fincept-terminal-desktop/bun.lock+++ b/fincept-terminal-desktop/bun.lock@@ -56,7 +56,7 @@"cmdk": "^1.1.1","date-fns": "^4.1.0","embla-carousel-react": "^8.6.0",- "ethers": "^5.7.2",+ "ethers": "^6.16.0","fyers-web-sdk-v3": "^1.3.1","handsontable": "^16.2.0","hyperformula": "^3.1.1",@@ -130,6 +130,8 @@"readable-stream": "4.7.0",},"packages": {+ "@adraffy/ens-normalize": ["@adraffy/[email protected]", "", {}, "sha512-96Z2IP3mYmF1Xg2cDm8f1gWGf/HUVedQ3FMifV4kG/PQ4yEP51xDtRAEfhVNt5f/uzpNkZHwWQuUcu6D6K+Ekw=="],+"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" } }, "sha512-IjLt0gd3L4jlOfilxVXTifn42FnVffMgDC04RJK1KDZpmkBWLv0XC92MVVmkxrFZNS/7l3xWgP/I3nqtX1sQHw=="],"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="],@@ -244,66 +246,6 @@"@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],- "@ethersproject/abi": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/address": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/hash": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/strings": "^5.8.0" } }, "sha512-b9YS/43ObplgyV6SlyQsG53/vkSal0MNA1fskSC4mbnCMi8R+NkcH8K9FPYNESf6jUefBUniE4SOKms0E/KK1Q=="],-- "@ethersproject/abstract-provider": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/networks": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/transactions": "^5.8.0", "@ethersproject/web": "^5.8.0" } }, "sha512-wC9SFcmh4UK0oKuLJQItoQdzS/qZ51EJegK6EmAWlh+OptpQ/npECOR3QqECd8iGHC0RJb4WKbVdSfif4ammrg=="],-- "@ethersproject/abstract-signer": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-provider": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0" } }, "sha512-N0XhZTswXcmIZQdYtUnd79VJzvEwXQw6PK0dTl9VoYrEBxxCPXqS0Eod7q5TNKRxe1/5WUMuR0u0nqTF/avdCA=="],-- "@ethersproject/address": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/rlp": "^5.8.0" } }, "sha512-GhH/abcC46LJwshoN+uBNoKVFPxUuZm6dA257z0vZkKmU1+t8xTn8oK7B9qrj8W2rFRMch4gbJl6PmVxjxBEBA=="],-- "@ethersproject/base64": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0" } }, "sha512-lN0oIwfkYj9LbPx4xEkie6rAMJtySbpOAFXSDVQaBnAzYfB4X2Qr+FXJGxMoc3Bxp2Sm8OwvzMrywxyw0gLjIQ=="],-- "@ethersproject/basex": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/properties": "^5.8.0" } }, "sha512-PIgTszMlDRmNwW9nhS6iqtVfdTAKosA7llYXNmGPw4YAI1PUyMv28988wAb41/gHF/WqGdoLv0erHaRcHRKW2Q=="],-- "@ethersproject/bignumber": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "bn.js": "^5.2.1" } }, "sha512-ZyaT24bHaSeJon2tGPKIiHszWjD/54Sz8t57Toch475lCLljC6MgPmxk7Gtzz+ddNN5LuHea9qhAe0x3D+uYPA=="],-- "@ethersproject/bytes": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/logger": "^5.8.0" } }, "sha512-vTkeohgJVCPVHu5c25XWaWQOZ4v+DkGoC42/TS2ond+PARCxTJvgTFUNDZovyQ/uAQ4EcpqqowKydcdmRKjg7A=="],-- "@ethersproject/constants": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bignumber": "^5.8.0" } }, "sha512-wigX4lrf5Vu+axVTIvNsuL6YrV4O5AXl5ubcURKMEME5TnWBouUh0CDTWxZ2GpnRn1kcCgE7l8O5+VbV9QTTcg=="],-- "@ethersproject/contracts": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abi": "^5.8.0", "@ethersproject/abstract-provider": "^5.8.0", "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/address": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/transactions": "^5.8.0" } }, "sha512-0eFjGz9GtuAi6MZwhb4uvUM216F38xiuR0yYCjKJpNfSEy4HUM8hvqqBj9Jmm0IUz8l0xKEhWwLIhPgxNY0yvQ=="],-- "@ethersproject/hash": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/address": "^5.8.0", "@ethersproject/base64": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/strings": "^5.8.0" } }, "sha512-ac/lBcTbEWW/VGJij0CNSw/wPcw9bSRgCB0AIBz8CvED/jfvDoV9hsIIiWfvWmFEi8RcXtlNwp2jv6ozWOsooA=="],-- "@ethersproject/hdnode": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/basex": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/pbkdf2": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/sha2": "^5.8.0", "@ethersproject/signing-key": "^5.8.0", "@ethersproject/strings": "^5.8.0", "@ethersproject/transactions": "^5.8.0", "@ethersproject/wordlists": "^5.8.0" } }, "sha512-4bK1VF6E83/3/Im0ERnnUeWOY3P1BZml4ZD3wcH8Ys0/d1h1xaFt6Zc+Dh9zXf9TapGro0T4wvO71UTCp3/uoA=="],-- "@ethersproject/json-wallets": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/address": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/hdnode": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/pbkdf2": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/random": "^5.8.0", "@ethersproject/strings": "^5.8.0", "@ethersproject/transactions": "^5.8.0", "aes-js": "3.0.0", "scrypt-js": "3.0.1" } }, "sha512-HxblNck8FVUtNxS3VTEYJAcwiKYsBIF77W15HufqlBF9gGfhmYOJtYZp8fSDZtn9y5EaXTE87zDwzxRoTFk11w=="],-- "@ethersproject/keccak256": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "js-sha3": "0.8.0" } }, "sha512-A1pkKLZSz8pDaQ1ftutZoaN46I6+jvuqugx5KYNeQOPqq+JZ0Txm7dlWesCHB5cndJSu5vP2VKptKf7cksERng=="],-- "@ethersproject/logger": ["@ethersproject/[email protected]", "", {}, "sha512-Qe6knGmY+zPPWTC+wQrpitodgBfH7XoceCGL5bJVejmH+yCS3R8jJm8iiWuvWbG76RUmyEG53oqv6GMVWqunjA=="],-- "@ethersproject/networks": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/logger": "^5.8.0" } }, "sha512-egPJh3aPVAzbHwq8DD7Po53J4OUSsA1MjQp8Vf/OZPav5rlmWUaFLiq8cvQiGK0Z5K6LYzm29+VA/p4RL1FzNg=="],-- "@ethersproject/pbkdf2": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/sha2": "^5.8.0" } }, "sha512-wuHiv97BrzCmfEaPbUFpMjlVg/IDkZThp9Ri88BpjRleg4iePJaj2SW8AIyE8cXn5V1tuAaMj6lzvsGJkGWskg=="],-- "@ethersproject/properties": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/logger": "^5.8.0" } }, "sha512-PYuiEoQ+FMaZZNGrStmN7+lWjlsoufGIHdww7454FIaGdbe/p5rnaCXTr5MtBYl3NkeoVhHZuyzChPeGeKIpQw=="],-- "@ethersproject/providers": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-provider": "^5.8.0", "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/address": "^5.8.0", "@ethersproject/base64": "^5.8.0", "@ethersproject/basex": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/hash": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/networks": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/random": "^5.8.0", "@ethersproject/rlp": "^5.8.0", "@ethersproject/sha2": "^5.8.0", "@ethersproject/strings": "^5.8.0", "@ethersproject/transactions": "^5.8.0", "@ethersproject/web": "^5.8.0", "bech32": "1.1.4", "ws": "8.18.0" } }, "sha512-3Il3oTzEx3o6kzcg9ZzbE+oCZYyY+3Zh83sKkn4s1DZfTUjIegHnN2Cm0kbn9YFy45FDVcuCLLONhU7ny0SsCw=="],-- "@ethersproject/random": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0" } }, "sha512-E4I5TDl7SVqyg4/kkA/qTfuLWAQGXmSOgYyO01So8hLfwgKvYK5snIlzxJMk72IFdG/7oh8yuSqY2KX7MMwg+A=="],-- "@ethersproject/rlp": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0" } }, "sha512-LqZgAznqDbiEunaUvykH2JAoXTT9NV0Atqk8rQN9nx9SEgThA/WMx5DnW8a9FOufo//6FZOCHZ+XiClzgbqV9Q=="],-- "@ethersproject/sha2": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "hash.js": "1.1.7" } }, "sha512-dDOUrXr9wF/YFltgTBYS0tKslPEKr6AekjqDW2dbn1L1xmjGR+9GiKu4ajxovnrDbwxAKdHjW8jNcwfz8PAz4A=="],-- "@ethersproject/signing-key": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "bn.js": "^5.2.1", "elliptic": "6.6.1", "hash.js": "1.1.7" } }, "sha512-LrPW2ZxoigFi6U6aVkFN/fa9Yx/+4AtIUe4/HACTvKJdhm0eeb107EVCIQcrLZkxaSIgc/eCrX8Q1GtbH+9n3w=="],-- "@ethersproject/solidity": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/sha2": "^5.8.0", "@ethersproject/strings": "^5.8.0" } }, "sha512-4CxFeCgmIWamOHwYN9d+QWGxye9qQLilpgTU0XhYs1OahkclF+ewO+3V1U0mvpiuQxm5EHHmv8f7ClVII8EHsA=="],-- "@ethersproject/strings": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/logger": "^5.8.0" } }, "sha512-qWEAk0MAvl0LszjdfnZ2uC8xbR2wdv4cDabyHiBh3Cldq/T8dPH3V4BbBsAYJUeonwD+8afVXld274Ls+Y1xXg=="],-- "@ethersproject/transactions": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/address": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/rlp": "^5.8.0", "@ethersproject/signing-key": "^5.8.0" } }, "sha512-UglxSDjByHG0TuU17bDfCemZ3AnKO2vYrL5/2n2oXvKzvb7Cz+W9gOWXKARjp2URVwcWlQlPOEQyAviKwT4AHg=="],-- "@ethersproject/units": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bignumber": "^5.8.0", "@ethersproject/constants": "^5.8.0", "@ethersproject/logger": "^5.8.0" } }, "sha512-lxq0CAnc5kMGIiWW4Mr041VT8IhNM+Pn5T3haO74XZWFulk7wH1Gv64HqE96hT4a7iiNMdOCFEBgaxWuk8ETKQ=="],-- "@ethersproject/wallet": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/abstract-provider": "^5.8.0", "@ethersproject/abstract-signer": "^5.8.0", "@ethersproject/address": "^5.8.0", "@ethersproject/bignumber": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/hash": "^5.8.0", "@ethersproject/hdnode": "^5.8.0", "@ethersproject/json-wallets": "^5.8.0", "@ethersproject/keccak256": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/random": "^5.8.0", "@ethersproject/signing-key": "^5.8.0", "@ethersproject/transactions": "^5.8.0", "@ethersproject/wordlists": "^5.8.0" } }, "sha512-G+jnzmgg6UxurVKRKvw27h0kvG75YKXZKdlLYmAHeF32TGUzHkOFd7Zn6QHOTYRFWnfjtSSFjBowKo7vfrXzPA=="],-- "@ethersproject/web": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/base64": "^5.8.0", "@ethersproject/bytes": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/strings": "^5.8.0" } }, "sha512-j7+Ksi/9KfGviws6Qtf9Q7KCqRhpwrYKQPs+JBA/rKVFF/yaWLHJEH3zfVP2plVu+eys0d2DlFmhoQJayFewcw=="],-- "@ethersproject/wordlists": ["@ethersproject/[email protected]", "", { "dependencies": { "@ethersproject/bytes": "^5.8.0", "@ethersproject/hash": "^5.8.0", "@ethersproject/logger": "^5.8.0", "@ethersproject/properties": "^5.8.0", "@ethersproject/strings": "^5.8.0" } }, "sha512-2df9bbXicZws2Sb5S6ET493uJ0Z84Fjr3pC4tu/qlnZERibZCeUVuqdtt+7Tv9xxhUxHoIekIA7avrKUWHrezg=="],-"@floating-ui/core": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="],"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="],@@ -370,7 +312,9 @@"@maplibre/maplibre-gl-style-spec": ["@maplibre/[email protected]", "", { "dependencies": { "@mapbox/jsonlint-lines-primitives": "~2.0.2", "@mapbox/unitbezier": "^0.0.1", "json-stringify-pretty-compact": "^4.0.0", "minimist": "^1.2.8", "quickselect": "^2.0.0", "rw": "^1.3.3", "tinyqueue": "^3.0.0" }, "bin": { "gl-style-format": "dist/gl-style-format.mjs", "gl-style-migrate": "dist/gl-style-migrate.mjs", "gl-style-validate": "dist/gl-style-validate.mjs" } }, "sha512-AzBy3095fTFPjDjmWpR2w6HVRAZJ6hQZUCwk5Plz6EyfnfuQW1odeW5i2Ai47Y6TBA2hQnC+azscjBSALpaWgw=="],- "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],+ "@noble/curves": ["@noble/[email protected]", "", { "dependencies": { "@noble/hashes": "1.3.2" } }, "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw=="],++ "@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ=="],"@otplib/core": ["@otplib/[email protected]", "", {}, "sha512-4sGntwbA/AC+SbPhbsziRiD+jNDdIzsZ3JUyfZwjtKyc/wufl1pnSIaG4Uqx8ymPagujub0o92kgBnB89cuAMA=="],@@ -812,7 +756,7 @@"adler-32": ["[email protected]", "", {}, "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A=="],- "aes-js": ["[email protected]", "", {}, "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw=="],+ "aes-js": ["[email protected]", "", {}, "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q=="],"agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],@@ -858,8 +802,6 @@"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-PxSsosKQjI38iXkmb3d0Y32efqyA0uW4s41u4IVBsLlWLhCiYNpH/AfNOVWRqCQBlD8TFJTz6OUWNd4DFJCnmw=="],- "bech32": ["[email protected]", "", {}, "sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ=="],-"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-WwCZ/5Diz7rsF29o27o0Gcc1Du+l7Zsv7SYtVPG0X3G/uUI1LqdxrQI7c9Hs2FWpqXXERjW9hp6g3/tH7DlVKg=="],"bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],@@ -1214,7 +1156,7 @@"esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],- "ethers": ["[email protected]", "", { "dependencies": { "@ethersproject/abi": "5.8.0", "@ethersproject/abstract-provider": "5.8.0", "@ethersproject/abstract-signer": "5.8.0", "@ethersproject/address": "5.8.0", "@ethersproject/base64": "5.8.0", "@ethersproject/basex": "5.8.0", "@ethersproject/bignumber": "5.8.0", "@ethersproject/bytes": "5.8.0", "@ethersproject/constants": "5.8.0", "@ethersproject/contracts": "5.8.0", "@ethersproject/hash": "5.8.0", "@ethersproject/hdnode": "5.8.0", "@ethersproject/json-wallets": "5.8.0", "@ethersproject/keccak256": "5.8.0", "@ethersproject/logger": "5.8.0", "@ethersproject/networks": "5.8.0", "@ethersproject/pbkdf2": "5.8.0", "@ethersproject/properties": "5.8.0", "@ethersproject/providers": "5.8.0", "@ethersproject/random": "5.8.0", "@ethersproject/rlp": "5.8.0", "@ethersproject/sha2": "5.8.0", "@ethersproject/signing-key": "5.8.0", "@ethersproject/solidity": "5.8.0", "@ethersproject/strings": "5.8.0", "@ethersproject/transactions": "5.8.0", "@ethersproject/units": "5.8.0", "@ethersproject/wallet": "5.8.0", "@ethersproject/web": "5.8.0", "@ethersproject/wordlists": "5.8.0" } }, "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg=="],+ "ethers": ["[email protected]", "", { "dependencies": { "@adraffy/ens-normalize": "1.10.1", "@noble/curves": "1.2.0", "@noble/hashes": "1.3.2", "@types/node": "22.7.5", "aes-js": "4.0.0-beta.5", "tslib": "2.7.0", "ws": "8.17.1" } }, "sha512-U1wulmetNymijEhpSEQ7Ct/P/Jw9/e7R1j5XIbPRydgV2DjLVMsULDlNksq3RQnFgKoLlZf88ijYtWEXcPa07A=="],"event-emitter": ["[email protected]", "", { "dependencies": { "d": "1", "es5-ext": "~0.10.14" } }, "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA=="],@@ -1468,8 +1410,6 @@"jmespath": ["[email protected]", "", {}, "sha512-9FzQjJ7MATs1tSpnco1K6ayiYE3figslrXA72G2HQ/n76RzvYlofyi5QM+iX4YRs/pu3yzxlVQSST23+dMDknw=="],- "js-sha3": ["[email protected]", "", {}, "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q=="],-"js-tiktoken": ["[email protected]", "", { "dependencies": { "base64-js": "^1.5.1" } }, "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g=="],"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],@@ -1978,8 +1918,6 @@"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],- "scrypt-js": ["[email protected]", "", {}, "sha512-cdwTTnqPu0Hyvf5in5asVdZocVDTNRmR7XEcJuIzMjJeSHybHl7vpB66AzwTaIg6CLSbtjcxc8fqcySfnTkccA=="],-"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],"set-cookie-parser": ["[email protected]", "", {}, "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="],@@ -2268,8 +2206,6 @@"@browserbasehq/sdk/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],- "@ethersproject/providers/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="],-"@ibm-cloud/watsonx-ai/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],"@jridgewell/gen-mapping/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],@@ -2358,6 +2294,12 @@"escodegen/esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],+ "ethers/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.19.2" } }, "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ=="],++ "ethers/tslib": ["[email protected]", "", {}, "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="],++ "ethers/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],+"falafel/acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A=="],"global-prefix/ini": ["[email protected]", "", {}, "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg=="],@@ -2414,6 +2356,8 @@"node-stdlib-browser/buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],+ "otpauth/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],+"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],"parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],@@ -2464,6 +2408,8 @@"color-normalize/color-rgba/color-parse": ["[email protected]", "", { "dependencies": { "color-name": "^1.0.0" } }, "sha512-BADfVl/FHkQkyo8sRBwMYBqemqsgnu7JZAwUgvBvuwwuNUZAhSvLTbsEErS5bQXzOjDR0dWzJ4vXN2Q+QoPx0A=="],+ "ethers/@types/node/undici-types": ["[email protected]", "", {}, "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="],+"glslify/static-eval/escodegen": ["[email protected]", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="],"ibm-cloud-sdk-core/@types/node/undici-types": ["[email protected]", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex 92c03b61d..00d54d0fe 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -64,7 +64,7 @@"cmdk": "^1.1.1","date-fns": "^4.1.0","embla-carousel-react": "^8.6.0",- "ethers": "^5.7.2",+ "ethers": "^6.16.0","fyers-web-sdk-v3": "^1.3.1","handsontable": "^16.2.0","hyperformula": "^3.1.1",diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txtindex 423bfa995..0a2772850 100644--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy1.txt@@ -100,7 +100,8 @@ loguru>=0.6.0nbconvert>=7.0.0pydantic-settings>=2.0.0python-redis-lock>=4.0.0-ruamel.yaml>=0.17.38+# Use ruamel.yaml version with pre-built wheels (avoid C extension build issues)+ruamel.yaml>=0.17.38,<0.18.0nbformat>=5.0.0pandarallel>=1.6.0rich>=13.0.0diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txtindex 466795680..742e3b96c 100644--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt@@ -90,7 +90,8 @@ loguru>=0.6.0pydantic-settings>=2.0.0fire>=0.4.0dill>=0.3.0-ruamel.yaml>=0.17.38+# Use ruamel.yaml version with pre-built wheels (avoid C extension build issues)+ruamel.yaml>=0.17.38,<0.18.0python-redis-lock>=4.0.0setuptools-scm>=8.0.0tables>=3.8.0diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.pyindex fe3cad460..67065e2d2 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/ffn_wrapper/ffn_service.py@@ -444,6 +444,279 @@ def risk_metrics(params: Dict[str, Any]) -> Dict[str, Any]:return {"success": False, "error": str(e)}+def portfolio_optimization(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate optimal portfolio weights using various methods"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ method = params.get('method', 'erc') # erc, inv_vol, mean_var, equal+ rf = params.get('risk_free_rate', 0.0)+ weight_bounds = params.get('weight_bounds', [0.0, 1.0])++ if not isinstance(prices, pd.DataFrame):+ return {"success": False, "error": "Multiple assets required for portfolio optimization"}++ if len(prices.columns) < 2:+ return {"success": False, "error": "At least 2 assets required for portfolio optimization"}++ # Calculate returns+ returns = ffn.to_returns(prices).dropna()++ if len(returns) < 10:+ return {"success": False, "error": "Insufficient data for portfolio optimization (need at least 10 data points)"}++ # Calculate weights based on method+ weights = None+ method_name = ""++ if method == 'equal':+ # Equal weight+ n_assets = len(prices.columns)+ weights = np.array([1.0 / n_assets] * n_assets)+ method_name = "Equal Weight"++ elif method == 'inv_vol':+ # Inverse volatility weights+ weights = ffn.calc_inv_vol_weights(returns)+ method_name = "Inverse Volatility"++ elif method == 'erc':+ # Equal Risk Contribution+ try:+ weights = ffn.calc_erc_weights(+ returns,+ covar_method='ledoit-wolf',+ risk_parity_method='ccd',+ maximum_iterations=100,+ tolerance=1e-8+ )+ method_name = "Equal Risk Contribution (ERC)"+ except Exception as e:+ # Fallback to inverse volatility if ERC fails+ weights = ffn.calc_inv_vol_weights(returns)+ method_name = "Inverse Volatility (ERC fallback)"++ elif method == 'mean_var':+ # Mean-Variance optimization (Maximum Sharpe)+ try:+ weights = ffn.calc_mean_var_weights(+ returns,+ weight_bounds=tuple(weight_bounds),+ rf=rf,+ covar_method='ledoit-wolf'+ )+ method_name = "Mean-Variance (Max Sharpe)"+ except Exception as e:+ # Fallback to inverse volatility if mean-var fails+ weights = ffn.calc_inv_vol_weights(returns)+ method_name = "Inverse Volatility (Mean-Var fallback)"++ else:+ return {"success": False, "error": f"Unknown optimization method: {method}"}++ # Apply weight bounds and normalize+ weights = np.clip(weights, weight_bounds[0], weight_bounds[1])+ weights = weights / weights.sum()++ # Create weights dict+ weights_dict = {col: float(w) for col, w in zip(prices.columns, weights)}++ # Calculate portfolio returns+ portfolio_returns = (returns * weights).sum(axis=1)+ portfolio_prices = ffn.to_price_index(portfolio_returns, start=100)++ # Calculate portfolio stats+ portfolio_stats = {+ 'total_return': float(ffn.calc_total_return(portfolio_prices)),+ 'cagr': float(ffn.calc_cagr(portfolio_prices)),+ 'volatility': float(portfolio_returns.std() * np.sqrt(252)),+ 'sharpe_ratio': float(ffn.calc_sharpe(portfolio_returns, rf=rf, nperiods=252, annualize=True)),+ 'sortino_ratio': float(ffn.calc_sortino_ratio(portfolio_returns, rf=rf, nperiods=252, annualize=True)),+ 'max_drawdown': float(ffn.calc_max_drawdown(portfolio_prices)),+ 'calmar_ratio': float(ffn.calc_calmar_ratio(portfolio_prices)) if ffn.calc_calmar_ratio(portfolio_prices) is not None else None,+ }++ # Calculate individual asset contributions+ asset_contributions = {}+ total_portfolio_vol = portfolio_returns.std() * np.sqrt(252)++ for i, col in enumerate(prices.columns):+ asset_return = returns[col]+ asset_weight = weights[i]++ # Marginal contribution to volatility (simplified)+ asset_vol = asset_return.std() * np.sqrt(252)+ contribution = asset_weight * asset_vol / total_portfolio_vol if total_portfolio_vol > 0 else 0++ asset_contributions[col] = {+ 'weight': float(asset_weight),+ 'volatility': float(asset_vol),+ 'return': float(asset_return.mean() * 252), # Annualized+ 'risk_contribution': float(contribution * asset_weight)+ }++ # Calculate correlation matrix+ correlation = returns.corr()+ correlation_dict = {col: {str(idx): float(val) for idx, val in correlation[col].items()}+ for col in correlation.columns}++ return {+ "success": True,+ "method": method_name,+ "weights": weights_dict,+ "portfolio_stats": portfolio_stats,+ "asset_contributions": asset_contributions,+ "correlation_matrix": correlation_dict,+ "portfolio_prices": {str(k): float(v) for k, v in portfolio_prices.tail(252).items()}+ }++ except Exception as e:+ return {"success": False, "error": str(e)}+++def benchmark_comparison(params: Dict[str, Any]) -> Dict[str, Any]:+ """Compare portfolio/asset performance against a benchmark"""+ if not FFN_AVAILABLE:+ return {"success": False, "error": "FFN library not available"}++ try:+ prices = parse_prices_json(params['prices'])+ benchmark_prices = parse_prices_json(params['benchmark_prices'])+ benchmark_name = params.get('benchmark_name', 'Benchmark')+ rf = params.get('risk_free_rate', 0.0)++ # Handle single asset prices+ if isinstance(prices, pd.DataFrame):+ portfolio_prices = prices.iloc[:, 0]+ portfolio_name = prices.columns[0]+ else:+ portfolio_prices = prices+ portfolio_name = "Portfolio"++ if isinstance(benchmark_prices, pd.DataFrame):+ benchmark_prices = benchmark_prices.iloc[:, 0]++ # Align dates+ common_dates = portfolio_prices.index.intersection(benchmark_prices.index)+ if len(common_dates) < 10:+ return {"success": False, "error": "Insufficient overlapping dates between portfolio and benchmark"}++ portfolio_prices = portfolio_prices.loc[common_dates].sort_index()+ benchmark_prices = benchmark_prices.loc[common_dates].sort_index()++ # Calculate returns+ portfolio_returns = ffn.to_returns(portfolio_prices).dropna()+ benchmark_returns = ffn.to_returns(benchmark_prices).dropna()++ # Helper for safe float conversion+ def safe_float(val):+ if val is None:+ return None+ try:+ if pd.isna(val):+ return None+ return float(val)+ except:+ return None++ # Calculate performance metrics for both+ portfolio_stats = {+ 'total_return': safe_float(ffn.calc_total_return(portfolio_prices)),+ 'cagr': safe_float(ffn.calc_cagr(portfolio_prices)),+ 'volatility': safe_float(portfolio_returns.std() * np.sqrt(252)),+ 'sharpe_ratio': safe_float(ffn.calc_sharpe(portfolio_returns, rf=rf, nperiods=252, annualize=True)),+ 'sortino_ratio': safe_float(ffn.calc_sortino_ratio(portfolio_returns, rf=rf, nperiods=252, annualize=True)),+ 'max_drawdown': safe_float(ffn.calc_max_drawdown(portfolio_prices)),+ 'calmar_ratio': safe_float(ffn.calc_calmar_ratio(portfolio_prices)),+ }++ benchmark_stats = {+ 'total_return': safe_float(ffn.calc_total_return(benchmark_prices)),+ 'cagr': safe_float(ffn.calc_cagr(benchmark_prices)),+ 'volatility': safe_float(benchmark_returns.std() * np.sqrt(252)),+ 'sharpe_ratio': safe_float(ffn.calc_sharpe(benchmark_returns, rf=rf, nperiods=252, annualize=True)),+ 'sortino_ratio': safe_float(ffn.calc_sortino_ratio(benchmark_returns, rf=rf, nperiods=252, annualize=True)),+ 'max_drawdown': safe_float(ffn.calc_max_drawdown(benchmark_prices)),+ 'calmar_ratio': safe_float(ffn.calc_calmar_ratio(benchmark_prices)),+ }++ # Calculate alpha and beta+ beta = None+ alpha = None+ correlation = None+ try:+ # Calculate beta (covariance / variance of benchmark)+ covariance = portfolio_returns.cov(benchmark_returns)+ benchmark_variance = benchmark_returns.var()+ if benchmark_variance > 0:+ beta = safe_float(covariance / benchmark_variance)+ # Alpha = portfolio return - (risk-free + beta * (benchmark return - risk-free))+ portfolio_annual_return = portfolio_returns.mean() * 252+ benchmark_annual_return = benchmark_returns.mean() * 252+ alpha = safe_float(portfolio_annual_return - (rf + beta * (benchmark_annual_return - rf)))+ correlation = safe_float(portfolio_returns.corr(benchmark_returns))+ except Exception:+ pass++ # Calculate excess returns+ excess_returns = portfolio_returns - benchmark_returns+ tracking_error = safe_float(excess_returns.std() * np.sqrt(252))+ information_ratio = None+ if tracking_error and tracking_error > 0:+ information_ratio = safe_float((excess_returns.mean() * 252) / tracking_error)++ # Up/down capture ratios+ up_capture = None+ down_capture = None+ try:+ up_periods = benchmark_returns > 0+ down_periods = benchmark_returns < 0++ if up_periods.sum() > 0:+ up_capture = safe_float(+ portfolio_returns[up_periods].mean() / benchmark_returns[up_periods].mean()+ )+ if down_periods.sum() > 0:+ down_capture = safe_float(+ portfolio_returns[down_periods].mean() / benchmark_returns[down_periods].mean()+ )+ except Exception:+ pass++ # Rebase both to 100 for comparison chart+ rebased_portfolio = ffn.rebase(portfolio_prices, 100)+ rebased_benchmark = ffn.rebase(benchmark_prices, 100)++ return {+ "success": True,+ "portfolio_name": portfolio_name,+ "benchmark_name": benchmark_name,+ "portfolio_stats": portfolio_stats,+ "benchmark_stats": benchmark_stats,+ "relative_metrics": {+ "alpha": alpha,+ "beta": beta,+ "correlation": correlation,+ "tracking_error": tracking_error,+ "information_ratio": information_ratio,+ "up_capture": up_capture,+ "down_capture": down_capture,+ },+ "rebased_portfolio": {str(k): float(v) for k, v in rebased_portfolio.tail(252).items()},+ "rebased_benchmark": {str(k): float(v) for k, v in rebased_benchmark.tail(252).items()},+ "date_range": {+ "start": str(common_dates[0]),+ "end": str(common_dates[-1]),+ "data_points": len(common_dates)+ }+ }++ except Exception as e:+ return {"success": False, "error": str(e)}++def full_analysis(params: Dict[str, Any]) -> Dict[str, Any]:"""Full portfolio analysis combining all metrics"""if not FFN_AVAILABLE:@@ -574,6 +847,8 @@ COMMANDS = {"compare_assets": compare_assets,"risk_metrics": risk_metrics,"full_analysis": full_analysis,+ "portfolio_optimization": portfolio_optimization,+ "benchmark_comparison": benchmark_comparison,}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/advanced.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/advanced.pyindex 1875823ae..915c55ab1 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/advanced.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/advanced.py@@ -3,6 +3,8 @@ Fortitudo.tech Advanced Functions Wrapper==========================================Entropy pooling, exposure stacking, and visualization+Includes fallback implementations using NumPy/SciPy for Python 3.14+ compatibility.+Usage:python advanced.py"""@@ -12,10 +14,115 @@ import pandas as pdimport jsonfrom typing import Dict, Any, Optional, Tupleimport warnings-import fortitudo.tech as ftwarnings.filterwarnings('ignore')+# Try to import fortitudo.tech, fallback to pure implementations+try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+except ImportError:+ FORTITUDO_AVAILABLE = False+ ft = None+++# ============================================================================+# FALLBACK IMPLEMENTATIONS (Pure NumPy/SciPy)+# ============================================================================++def _fallback_entropy_pooling(+ p: np.ndarray,+ A: np.ndarray,+ b: np.ndarray,+ G: Optional[np.ndarray] = None,+ h: Optional[np.ndarray] = None,+ method: str = 'L-BFGS-B'+) -> np.ndarray:+ """+ Fallback entropy pooling using scipy optimization.++ Minimizes KL divergence D(q||p) subject to constraints Aq = b, Gq <= h+ """+ from scipy.optimize import minimize++ n = len(p.flatten())+ p_flat = p.flatten()++ # Objective: KL divergence D(q||p) = sum(q * log(q/p))+ def objective(q):+ q = np.maximum(q, 1e-10) # Avoid log(0)+ return np.sum(q * (np.log(q) - np.log(p_flat)))++ def gradient(q):+ q = np.maximum(q, 1e-10)+ return np.log(q) - np.log(p_flat) + 1++ # Constraints+ constraints = []++ # Equality constraints: Aq = b+ if A is not None and b is not None:+ for i in range(A.shape[0]):+ constraints.append({+ 'type': 'eq',+ 'fun': lambda q, i=i: A[i] @ q - b.flatten()[i]+ })++ # Inequality constraints: Gq <= h+ if G is not None and h is not None:+ for i in range(G.shape[0]):+ constraints.append({+ 'type': 'ineq',+ 'fun': lambda q, i=i: h.flatten()[i] - G[i] @ q+ })++ # Bounds: probabilities must be positive+ bounds = [(1e-10, 1.0) for _ in range(n)]++ # Initial guess: prior probabilities+ x0 = p_flat.copy()++ # Optimize+ result = minimize(+ objective,+ x0,+ method=method,+ jac=gradient,+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ # Normalize result+ q = result.x+ q = np.maximum(q, 0)+ q = q / q.sum()++ return q.reshape(-1, 1)+++def _fallback_exposure_stacking(+ L: int,+ sample_portfolios: np.ndarray+) -> np.ndarray:+ """+ Fallback exposure stacking implementation.++ Simple mean aggregation of sample portfolios as approximation.+ For full implementation, see SSRN paper 4709317.+ """+ # Simple approximation: weighted average+ # In practice, this should use cross-validation partitioning+ n_assets, n_samples = sample_portfolios.shape++ # Use mean as a simple approximation+ stacked = sample_portfolios.mean(axis=1)++ # Normalize to sum to 1+ stacked = stacked / stacked.sum()++ return stacked+def apply_entropy_pooling(prior_probabilities: np.ndarray,@@ -41,13 +148,6 @@ def apply_entropy_pooling(Returns:Posterior probability vector, shape (S, 1)-- Example:- >>> # 100 scenarios, probabilities must sum to 1- >>> p_prior = np.ones((100, 1)) / 100- >>> A = np.ones((1, 100)) # Sum constraint- >>> b = np.array([[1.0]])- >>> p_post = apply_entropy_pooling(p_prior, A, b)"""# Ensure correct shapesif prior_probabilities.ndim == 1:@@ -57,16 +157,25 @@ def apply_entropy_pooling(if inequality_constraints_h is not None and inequality_constraints_h.ndim == 1:inequality_constraints_h = inequality_constraints_h.reshape(-1, 1)- posterior = ft.entropy_pooling(- p=prior_probabilities,- A=equality_constraints_A,- b=equality_constraints_b,- G=inequality_constraints_G,- h=inequality_constraints_h,- method=method- )-- return posterior+ if FORTITUDO_AVAILABLE:+ posterior = ft.entropy_pooling(+ p=prior_probabilities,+ A=equality_constraints_A,+ b=equality_constraints_b,+ G=inequality_constraints_G,+ h=inequality_constraints_h,+ method=method+ )+ return posterior+ else:+ return _fallback_entropy_pooling(+ prior_probabilities,+ equality_constraints_A,+ equality_constraints_b,+ inequality_constraints_G,+ inequality_constraints_h,+ method+ )def apply_entropy_pooling_simple(@@ -136,20 +245,23 @@ def calculate_exposure_stacking(n_assets, n_samples = sample_portfolios.shape# Calculate exposure stacking portfolio- stacked_weights = ft.exposure_stacking(L=n_partitions, sample_portfolios=sample_portfolios)+ if FORTITUDO_AVAILABLE:+ stacked_weights = ft.exposure_stacking(L=n_partitions, sample_portfolios=sample_portfolios)+ else:+ stacked_weights = _fallback_exposure_stacking(n_partitions, sample_portfolios)# Calculate statisticsmean_weights = sample_portfolios.mean(axis=1)std_weights = sample_portfolios.std(axis=1)return {- 'stacked_weights': stacked_weights.tolist(),+ 'stacked_weights': stacked_weights.tolist() if hasattr(stacked_weights, 'tolist') else list(stacked_weights),'mean_sample_weights': mean_weights.tolist(),'std_sample_weights': std_weights.tolist(),'n_assets': n_assets,'n_samples': n_samples,'n_partitions': n_partitions,- 'weights_sum': float(stacked_weights.sum())+ 'weights_sum': float(np.sum(stacked_weights))}@@ -178,20 +290,36 @@ def plot_volatility_surface(import matplotlibmatplotlib.use('Agg') # Non-interactive backendimport matplotlib.pyplot as plt+ from mpl_toolkits.mplot3d import Axes3D- fig, ax = ft.plot_vol_surface(- index=scenario_index,- vol_surface=vol_surface_data,- figsize=figsize,- zoom=zoom- )+ # Extract surface for statistics+ surface = vol_surface_data[scenario_index].reshape(5, 7)++ if FORTITUDO_AVAILABLE:+ fig, ax = ft.plot_vol_surface(+ index=scenario_index,+ vol_surface=vol_surface_data,+ figsize=figsize,+ zoom=zoom+ )+ else:+ # Fallback: create our own 3D plot+ fig = plt.figure(figsize=figsize if figsize else (10, 8))+ ax = fig.add_subplot(111, projection='3d')++ strikes = np.arange(7)+ maturities = np.arange(5)+ X, Y = np.meshgrid(strikes, maturities)++ ax.plot_surface(X, Y, surface, cmap='viridis', alpha=0.8)+ ax.set_xlabel('Strike')+ ax.set_ylabel('Maturity')+ ax.set_zlabel('Volatility')+ ax.set_title(f'Volatility Surface (Scenario {scenario_index})')if save_path:fig.savefig(save_path, dpi=150, bbox_inches='tight')- # Extract surface for statistics- surface = vol_surface_data[scenario_index].reshape(5, 7)-plt.close(fig)return {diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/data.pyindex 8f83a660e..fc3f13342 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/data.py@@ -3,6 +3,8 @@ Fortitudo.tech Data Loading Wrapper====================================Example data loading functions+Includes fallback implementations using generated sample data for Python 3.14+ compatibility.+Usage:python data.py"""@@ -10,7 +12,115 @@ Usage:import pandas as pdimport numpy as npfrom typing import Tuple, List-import fortitudo.tech as ft++# Try to import fortitudo.tech, fallback to sample data generators+try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+except ImportError:+ FORTITUDO_AVAILABLE = False+ ft = None+++# ============================================================================+# FALLBACK DATA GENERATORS+# ============================================================================++def _generate_sample_time_series(n_scenarios: int = 5040, seed: int = 42) -> pd.DataFrame:+ """Generate sample time series data similar to fortitudo.tech example data."""+ np.random.seed(seed)++ # Create date index+ dates = pd.date_range(start='2004-01-01', periods=n_scenarios, freq='B')++ # 1 equity index+ equity_returns = np.random.randn(n_scenarios) * 0.01 + 0.0003+ equity_cumulative = 100 * np.exp(np.cumsum(equity_returns))++ # 34 yield curve columns (1m to 30y)+ maturities = ['1M', '2M', '3M', '6M', '1Y', '2Y', '3Y', '5Y', '7Y', '10Y', '15Y', '20Y', '30Y']+ yield_data = {}+ base_yield = 0.02+ for i, mat in enumerate(maturities):+ # Yield curve with term structure+ term_premium = i * 0.002+ yield_data[f'Yield_{mat}'] = base_yield + term_premium + np.random.randn(n_scenarios) * 0.001+ yield_data[f'Yield_{mat}'] = np.cumsum(yield_data[f'Yield_{mat}']) * 0.01 + base_yield + term_premium++ # 35 option columns (various strikes and maturities)+ option_data = {}+ for strike in range(90, 111, 5): # 5 strikes+ for mat in ['1M', '3M', '6M', '1Y', '2Y', '3Y', '5Y']: # 7 maturities+ key = f'Option_K{strike}_{mat}'+ base_iv = 0.20 + abs(strike - 100) * 0.002 # Smile+ option_data[key] = base_iv + np.random.randn(n_scenarios) * 0.02++ # 10 credit spread columns+ credit_data = {}+ for rating in ['AAA', 'AA', 'A', 'BBB', 'BB', 'B', 'CCC', 'HY', 'IG', 'Total']:+ base_spread = {'AAA': 0.005, 'AA': 0.01, 'A': 0.015, 'BBB': 0.02,+ 'BB': 0.03, 'B': 0.05, 'CCC': 0.08, 'HY': 0.04, 'IG': 0.01, 'Total': 0.02}+ credit_data[f'Credit_{rating}'] = base_spread.get(rating, 0.02) + np.random.randn(n_scenarios) * 0.005++ # Combine all data+ data = {'Equity_Index': equity_cumulative}+ data.update(yield_data)+ data.update(option_data)+ data.update(credit_data)++ df = pd.DataFrame(data, index=dates)+ return df+++def _generate_sample_risk_factors(n_scenarios: int = 1000, seed: int = 42) -> pd.DataFrame:+ """Generate sample risk factor data."""+ np.random.seed(seed)++ dates = pd.date_range(start='2020-01-01', periods=n_scenarios, freq='B')++ factors = {+ 'Equity': np.random.randn(n_scenarios) * 0.02,+ 'Duration': np.random.randn(n_scenarios) * 0.005,+ 'Credit': np.random.randn(n_scenarios) * 0.01,+ 'FX': np.random.randn(n_scenarios) * 0.008,+ 'Commodity': np.random.randn(n_scenarios) * 0.015,+ 'Volatility': np.random.randn(n_scenarios) * 0.02+ }++ return pd.DataFrame(factors, index=dates)+++def _generate_sample_pnl(n_scenarios: int = 1000, n_positions: int = 10, seed: int = 42) -> pd.DataFrame:+ """Generate sample P&L data."""+ np.random.seed(seed)++ position_names = [f'Position_{i+1}' for i in range(n_positions)]+ pnl_data = {}++ for pos in position_names:+ pnl_data[pos] = np.random.randn(n_scenarios) * 10000 + 500++ return pd.DataFrame(pnl_data)+++def _generate_sample_parameters() -> Tuple[List, np.ndarray, np.ndarray]:+ """Generate sample parameters for volatility surface."""+ # Strike levels+ strikes = [0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.2]++ # Maturities in years+ maturities = np.array([0.0833, 0.25, 0.5, 1.0, 2.0])++ # Sample volatility surface parameters+ base_vols = np.array([+ [0.25, 0.22, 0.20, 0.19, 0.20, 0.22, 0.25], # 1M+ [0.24, 0.21, 0.19, 0.18, 0.19, 0.21, 0.24], # 3M+ [0.23, 0.20, 0.18, 0.17, 0.18, 0.20, 0.23], # 6M+ [0.22, 0.19, 0.17, 0.16, 0.17, 0.19, 0.22], # 1Y+ [0.21, 0.18, 0.16, 0.15, 0.16, 0.18, 0.21], # 2Y+ ])++ return strikes, maturities, base_volsdef load_example_time_series() -> pd.DataFrame:@@ -24,7 +134,10 @@ def load_example_time_series() -> pd.DataFrame:- 35 option columns (various strikes and maturities)- 10 credit spread columns"""- return ft.load_time_series()+ if FORTITUDO_AVAILABLE:+ return ft.load_time_series()+ else:+ return _generate_sample_time_series()def load_example_risk_factors() -> pd.DataFrame:@@ -34,7 +147,10 @@ def load_example_risk_factors() -> pd.DataFrame:Returns:DataFrame with risk factor time series"""- return ft.load_risk_factors()+ if FORTITUDO_AVAILABLE:+ return ft.load_risk_factors()+ else:+ return _generate_sample_risk_factors()def load_example_pnl() -> pd.DataFrame:@@ -44,7 +160,10 @@ def load_example_pnl() -> pd.DataFrame:Returns:DataFrame with P&L scenarios"""- return ft.load_pnl()+ if FORTITUDO_AVAILABLE:+ return ft.load_pnl()+ else:+ return _generate_sample_pnl()def load_example_parameters() -> Tuple[List, np.ndarray, np.ndarray]:@@ -54,7 +173,10 @@ def load_example_parameters() -> Tuple[List, np.ndarray, np.ndarray]:Returns:Tuple of (list, array, array) containing parameters"""- return ft.load_parameters()+ if FORTITUDO_AVAILABLE:+ return ft.load_parameters()+ else:+ return _generate_sample_parameters()def get_dataset_info(df: pd.DataFrame) -> dict:diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.pynew file mode 100644index 000000000..5df99b777--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/fortitudo_service.py@@ -0,0 +1,590 @@+"""+Fortitudo.tech Service - Python backend for portfolio risk analytics via PyO3+===============================================================================++Provides JSON-RPC interface for Rust/Tauri to call fortitudo.tech analytics functions.+Includes portfolio risk metrics, option pricing, entropy pooling, and exposure stacking.++Supports Python 3.14+ via pure NumPy/SciPy fallback implementations when fortitudo.tech+is not available (requires Python <3.14).+"""++import json+import sys+import os+from typing import Dict, List, Any, Optional+from datetime import datetime++# Add this script's directory to Python path for local imports+_script_dir = os.path.dirname(os.path.abspath(__file__))+if _script_dir not in sys.path:+ sys.path.insert(0, _script_dir)++import pandas as pd+import numpy as np++try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+ FORTITUDO_VERSION = getattr(ft, '__version__', '1.2')+except ImportError:+ FORTITUDO_AVAILABLE = False+ FORTITUDO_VERSION = 'fallback'++# Import local wrapper modules (with fallback support)+try:+ from functions import (+ calculate_portfolio_volatility,+ calculate_portfolio_var,+ calculate_portfolio_cvar,+ calculate_covariance_matrix,+ calculate_correlation_matrix,+ calculate_simulation_moments,+ calculate_exp_decay_probabilities,+ calculate_normal_calibration,+ calculate_all_metrics,+ FORTITUDO_AVAILABLE as FUNCTIONS_AVAILABLE+ )+ from option_pricing import (+ price_call_option,+ price_put_option,+ calculate_forward_price,+ price_option_straddle,+ calculate_put_call_parity_check,+ calculate_all_greeks,+ FORTITUDO_AVAILABLE as OPTIONS_AVAILABLE+ )+ from advanced import (+ apply_entropy_pooling,+ apply_entropy_pooling_simple,+ calculate_exposure_stacking,+ FORTITUDO_AVAILABLE as ADVANCED_AVAILABLE+ )+ from optimization import (+ MeanVarianceOptimizer,+ MeanCVaROptimizer+ )+ WRAPPERS_AVAILABLE = True+ OPTIMIZATION_AVAILABLE = True+except ImportError as e:+ WRAPPERS_AVAILABLE = False+ OPTIMIZATION_AVAILABLE = False+ print(f"[fortitudo_service] Warning: Could not import wrappers: {e}", file=sys.stderr)+++def serialize_result(data: Any) -> str:+ """Serialize result to JSON, handling numpy/pandas types"""+ def convert(obj):+ if obj is None:+ return None+ if isinstance(obj, (np.integer, np.floating)):+ if np.isnan(obj):+ return None+ return float(obj)+ elif isinstance(obj, np.ndarray):+ return obj.tolist()+ elif isinstance(obj, np.bool_):+ return bool(obj)+ elif isinstance(obj, pd.DataFrame):+ return obj.to_dict()+ elif isinstance(obj, pd.Series):+ return obj.to_dict()+ elif isinstance(obj, pd.Timestamp):+ return str(obj)+ elif isinstance(obj, datetime):+ return obj.isoformat()+ elif isinstance(obj, dict):+ return {k: convert(v) for k, v in obj.items()}+ elif isinstance(obj, (list, tuple)):+ return [convert(i) for i in obj]+ return obj++ return json.dumps(convert(data), default=str)+++def parse_returns_json(returns_json: str) -> pd.DataFrame:+ """Parse JSON returns data into DataFrame"""+ data = json.loads(returns_json)++ if isinstance(data, dict):+ first_value = next(iter(data.values()), None)+ if isinstance(first_value, dict):+ # Multi-asset: {symbol: {date: return}}+ df = pd.DataFrame(data)+ df.index = pd.to_datetime(df.index)+ else:+ # Single asset: {date: return}+ df = pd.DataFrame({'returns': data})+ df.index = pd.to_datetime(df.index)+ elif isinstance(data, list):+ df = pd.DataFrame(data)+ if 'date' in df.columns:+ df['date'] = pd.to_datetime(df['date'])+ df.set_index('date', inplace=True)+ if 'symbol' in df.columns:+ df = df.pivot(columns='symbol', values='returns')+ else:+ raise ValueError(f"Unsupported returns data format: {type(data)}")++ df = df.sort_index()+ return df+++def parse_weights(weights_json: str) -> np.ndarray:+ """Parse JSON weights into numpy array"""+ data = json.loads(weights_json)+ if isinstance(data, list):+ return np.array(data)+ elif isinstance(data, dict):+ return np.array(list(data.values()))+ else:+ raise ValueError(f"Unsupported weights format: {type(data)}")+++# ============================================================================+# COMMAND HANDLERS+# ============================================================================++def check_status() -> Dict[str, Any]:+ """Check fortitudo.tech library status"""+ mode = "native" if FORTITUDO_AVAILABLE else "fallback"+ return {+ "success": True,+ "available": WRAPPERS_AVAILABLE, # Changed: now True even in fallback mode+ "native_available": FORTITUDO_AVAILABLE,+ "wrappers_available": WRAPPERS_AVAILABLE,+ "mode": mode,+ "version": FORTITUDO_VERSION,+ "message": f"Fortitudo.tech analytics ready ({mode} mode)"+ }+++def portfolio_metrics(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate comprehensive portfolio risk metrics"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ returns = parse_returns_json(params['returns'])+ weights = parse_weights(params['weights'])+ alpha = params.get('alpha', 0.05)++ # Get optional probabilities+ probabilities = None+ if 'probabilities' in params and params['probabilities']:+ probabilities = np.array(json.loads(params['probabilities']))++ # Calculate all metrics+ metrics = calculate_all_metrics(weights, returns, probabilities, alpha)++ return {+ "success": True,+ "metrics": metrics,+ "n_scenarios": len(returns),+ "n_assets": len(weights)+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def covariance_analysis(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate covariance and correlation matrices"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ returns = parse_returns_json(params['returns'])++ probabilities = None+ if 'probabilities' in params and params['probabilities']:+ probabilities = np.array(json.loads(params['probabilities']))++ cov_matrix = calculate_covariance_matrix(returns, probabilities)+ corr_matrix = calculate_correlation_matrix(returns, probabilities)+ moments = calculate_simulation_moments(returns, probabilities)++ return {+ "success": True,+ "covariance_matrix": cov_matrix.to_dict() if isinstance(cov_matrix, pd.DataFrame) else cov_matrix,+ "correlation_matrix": corr_matrix.to_dict() if isinstance(corr_matrix, pd.DataFrame) else corr_matrix,+ "moments": moments.to_dict() if isinstance(moments, pd.DataFrame) else moments,+ "assets": list(returns.columns) if hasattr(returns, 'columns') else None+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def exp_decay_weighting(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate exponentially decaying probabilities"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ returns = parse_returns_json(params['returns'])+ half_life = params.get('half_life', 252)++ probs = calculate_exp_decay_probabilities(returns, half_life)++ return {+ "success": True,+ "probabilities": probs.flatten().tolist(),+ "half_life": half_life,+ "n_scenarios": len(probs),+ "sum": float(probs.sum())+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def option_pricing(params: Dict[str, Any]) -> Dict[str, Any]:+ """Price options using Black-Scholes model"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ spot = params['spot_price']+ strike = params['strike']+ volatility = params['volatility']+ risk_free_rate = params.get('risk_free_rate', 0.05)+ dividend_yield = params.get('dividend_yield', 0.0)+ time_to_maturity = params.get('time_to_maturity', 1.0)++ # Calculate forward price+ forward = calculate_forward_price(spot, risk_free_rate, dividend_yield, time_to_maturity)++ # Price call and put+ call_price = price_call_option(forward, strike, volatility, risk_free_rate, time_to_maturity)+ put_price = price_put_option(forward, strike, volatility, risk_free_rate, time_to_maturity)++ # Straddle+ straddle = price_option_straddle(forward, strike, volatility, risk_free_rate, time_to_maturity)++ # Put-call parity check+ parity = calculate_put_call_parity_check(spot, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity)++ return {+ "success": True,+ "forward_price": forward,+ "call_price": call_price,+ "put_price": put_price,+ "straddle": straddle,+ "parity_check": parity+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def option_chain(params: Dict[str, Any]) -> Dict[str, Any]:+ """Generate option chain for multiple strikes"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ spot = params['spot_price']+ strikes = params.get('strikes', [spot * 0.9, spot * 0.95, spot, spot * 1.05, spot * 1.1])+ volatility = params['volatility']+ risk_free_rate = params.get('risk_free_rate', 0.05)+ dividend_yield = params.get('dividend_yield', 0.0)+ time_to_maturity = params.get('time_to_maturity', 1.0)++ forward = calculate_forward_price(spot, risk_free_rate, dividend_yield, time_to_maturity)++ chain = []+ for strike in strikes:+ call = price_call_option(forward, strike, volatility, risk_free_rate, time_to_maturity)+ put = price_put_option(forward, strike, volatility, risk_free_rate, time_to_maturity)+ chain.append({+ "strike": strike,+ "call_price": call,+ "put_price": put,+ "moneyness": strike / spot+ })++ return {+ "success": True,+ "spot_price": spot,+ "forward_price": forward,+ "chain": chain+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def entropy_pooling(params: Dict[str, Any]) -> Dict[str, Any]:+ """Apply entropy pooling for scenario probability adjustment"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ n_scenarios = params['n_scenarios']+ max_probability = params.get('max_probability', None)++ result = apply_entropy_pooling_simple(+ n_scenarios=n_scenarios,+ max_probability=max_probability+ )++ return {+ "success": True,+ "prior_probabilities": result['prior_probabilities'].tolist(),+ "posterior_probabilities": result['posterior_probabilities'].tolist(),+ "effective_scenarios_prior": result['effective_scenarios_prior'],+ "effective_scenarios_posterior": result['effective_scenarios_posterior'],+ "max_probability": result['max_probability'],+ "min_probability": result['min_probability']+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def exposure_stacking(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate exposure stacking portfolio"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ sample_portfolios = np.array(json.loads(params['sample_portfolios']))+ n_partitions = params.get('n_partitions', 4)++ result = calculate_exposure_stacking(sample_portfolios, n_partitions)++ return {+ "success": True,+ "stacked_weights": result['stacked_weights'],+ "mean_sample_weights": result['mean_sample_weights'],+ "std_sample_weights": result['std_sample_weights'],+ "n_assets": result['n_assets'],+ "n_samples": result['n_samples'],+ "n_partitions": result['n_partitions'],+ "weights_sum": result['weights_sum']+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def full_analysis(params: Dict[str, Any]) -> Dict[str, Any]:+ """Complete portfolio risk analysis"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ returns = parse_returns_json(params['returns'])+ weights = parse_weights(params['weights'])+ alpha = params.get('alpha', 0.05)+ half_life = params.get('half_life', 252)++ # Calculate exp decay probabilities+ probs = calculate_exp_decay_probabilities(returns, half_life)++ # Calculate metrics with equal weights+ metrics_equal = calculate_all_metrics(weights, returns, None, alpha)++ # Calculate metrics with exp decay weights+ metrics_weighted = calculate_all_metrics(weights, returns, probs, alpha)++ # Covariance and correlation+ cov_matrix = calculate_covariance_matrix(returns)+ corr_matrix = calculate_correlation_matrix(returns)++ # Moments+ moments = calculate_simulation_moments(returns)++ return {+ "success": True,+ "analysis": {+ "metrics_equal_weight": metrics_equal,+ "metrics_exp_decay": metrics_weighted,+ "covariance_matrix": cov_matrix.to_dict() if isinstance(cov_matrix, pd.DataFrame) else None,+ "correlation_matrix": corr_matrix.to_dict() if isinstance(corr_matrix, pd.DataFrame) else None,+ "moments": moments.to_dict() if isinstance(moments, pd.DataFrame) else None,+ "half_life": half_life,+ "alpha": alpha,+ "n_scenarios": len(returns),+ "n_assets": len(weights),+ "assets": list(returns.columns) if hasattr(returns, 'columns') else None+ }+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# MAIN ENTRY POINT+# ============================================================================++def option_greeks(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate option Greeks (Delta, Gamma, Vega, Theta, Rho)"""+ if not WRAPPERS_AVAILABLE:+ return {"success": False, "error": "Wrapper modules not available"}++ try:+ spot = params['spot_price']+ strike = params['strike']+ volatility = params['volatility']+ risk_free_rate = params.get('risk_free_rate', 0.05)+ dividend_yield = params.get('dividend_yield', 0.0)+ time_to_maturity = params.get('time_to_maturity', 1.0)++ greeks = calculate_all_greeks(+ spot_price=spot,+ strike=strike,+ volatility=volatility,+ risk_free_rate=risk_free_rate,+ dividend_yield=dividend_yield,+ time_to_maturity=time_to_maturity+ )++ return {+ "success": True,+ **greeks+ }+ except Exception as e:+ return {"success": False, "error": str(e)}+++def optimize_mean_variance(params: Dict[str, Any]) -> Dict[str, Any]:+ """Mean-Variance portfolio optimization"""+ if not OPTIMIZATION_AVAILABLE:+ return {"success": False, "error": "Optimization module not available"}++ try:+ returns = parse_returns_json(params['returns'])+ objective = params.get('objective', 'min_variance') # min_variance, max_sharpe, target_return+ long_only = params.get('long_only', True)+ max_weight = params.get('max_weight', None)+ min_weight = params.get('min_weight', None)+ risk_free_rate = params.get('risk_free_rate', 0.0)+ target_return = params.get('target_return', None)++ optimizer = MeanVarianceOptimizer(returns, risk_free_rate=risk_free_rate)++ if objective == 'min_variance':+ result = optimizer.minimum_variance(long_only=long_only, max_weight=max_weight, min_weight=min_weight)+ elif objective == 'max_sharpe':+ result = optimizer.max_sharpe(long_only=long_only, max_weight=max_weight)+ elif objective == 'target_return' and target_return is not None:+ result = optimizer.target_return(target=target_return, long_only=long_only, max_weight=max_weight)+ else:+ result = optimizer.minimum_variance(long_only=long_only, max_weight=max_weight)++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++def optimize_mean_cvar(params: Dict[str, Any]) -> Dict[str, Any]:+ """Mean-CVaR portfolio optimization"""+ if not OPTIMIZATION_AVAILABLE:+ return {"success": False, "error": "Optimization module not available"}++ try:+ returns = parse_returns_json(params['returns'])+ objective = params.get('objective', 'min_cvar') # min_cvar, target_return+ alpha = params.get('alpha', 0.05)+ long_only = params.get('long_only', True)+ max_weight = params.get('max_weight', None)+ min_weight = params.get('min_weight', None)+ risk_free_rate = params.get('risk_free_rate', 0.0)+ target_return = params.get('target_return', None)++ optimizer = MeanCVaROptimizer(returns, alpha=alpha, risk_free_rate=risk_free_rate)++ if objective == 'min_cvar':+ result = optimizer.minimum_cvar(long_only=long_only, max_weight=max_weight, min_weight=min_weight)+ elif objective == 'target_return' and target_return is not None:+ result = optimizer.target_return(target=target_return, long_only=long_only, max_weight=max_weight)+ else:+ result = optimizer.minimum_cvar(long_only=long_only, max_weight=max_weight)++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++def efficient_frontier_mv(params: Dict[str, Any]) -> Dict[str, Any]:+ """Generate Mean-Variance efficient frontier"""+ if not OPTIMIZATION_AVAILABLE:+ return {"success": False, "error": "Optimization module not available"}++ try:+ returns = parse_returns_json(params['returns'])+ n_points = params.get('n_points', 20)+ long_only = params.get('long_only', True)+ max_weight = params.get('max_weight', None)+ risk_free_rate = params.get('risk_free_rate', 0.0)++ optimizer = MeanVarianceOptimizer(returns, risk_free_rate=risk_free_rate)+ result = optimizer.efficient_frontier(n_points=n_points, long_only=long_only, max_weight=max_weight)++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++def efficient_frontier_cvar(params: Dict[str, Any]) -> Dict[str, Any]:+ """Generate Mean-CVaR efficient frontier"""+ if not OPTIMIZATION_AVAILABLE:+ return {"success": False, "error": "Optimization module not available"}++ try:+ returns = parse_returns_json(params['returns'])+ n_points = params.get('n_points', 20)+ alpha = params.get('alpha', 0.05)+ long_only = params.get('long_only', True)+ max_weight = params.get('max_weight', None)++ optimizer = MeanCVaROptimizer(returns, alpha=alpha)+ result = optimizer.efficient_frontier(n_points=n_points, long_only=long_only, max_weight=max_weight)++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++def main(args: list) -> str:+ """Main entry point for Tauri command execution"""+ if not args:+ return serialize_result({"success": False, "error": "No command specified"})++ command = args[0]++ # Parse params if provided+ params = {}+ if len(args) > 1:+ try:+ params = json.loads(args[1])+ except json.JSONDecodeError as e:+ return serialize_result({"success": False, "error": f"Invalid JSON params: {e}"})++ # Route commands+ handlers = {+ "check_status": lambda: check_status(),+ "portfolio_metrics": lambda: portfolio_metrics(params),+ "covariance_analysis": lambda: covariance_analysis(params),+ "exp_decay_weighting": lambda: exp_decay_weighting(params),+ "option_pricing": lambda: option_pricing(params),+ "option_chain": lambda: option_chain(params),+ "option_greeks": lambda: option_greeks(params),+ "entropy_pooling": lambda: entropy_pooling(params),+ "exposure_stacking": lambda: exposure_stacking(params),+ "full_analysis": lambda: full_analysis(params),+ "optimize_mean_variance": lambda: optimize_mean_variance(params),+ "optimize_mean_cvar": lambda: optimize_mean_cvar(params),+ "efficient_frontier_mv": lambda: efficient_frontier_mv(params),+ "efficient_frontier_cvar": lambda: efficient_frontier_cvar(params),+ }++ if command in handlers:+ result = handlers[command]()+ return serialize_result(result)+ else:+ return serialize_result({+ "success": False,+ "error": f"Unknown command: {command}",+ "available_commands": list(handlers.keys())+ })+++if __name__ == "__main__":+ result = main(sys.argv[1:] if len(sys.argv) > 1 else [])+ print(result)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/functions.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/functions.pyindex 77f73506d..7c814b476 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/functions.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/functions.py@@ -3,6 +3,8 @@ Fortitudo.tech Portfolio Functions Wrapper===========================================Portfolio risk metrics and matrix calculations+Includes fallback implementations using NumPy/SciPy for Python 3.14+ compatibility.+Usage:python functions.py"""@@ -12,10 +14,228 @@ import numpy as npimport jsonfrom typing import Dict, Any, Optional, Union, Tupleimport warnings-import fortitudo.tech as ftwarnings.filterwarnings('ignore')+# Try to import fortitudo.tech, fallback to pure NumPy implementations+try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+except ImportError:+ FORTITUDO_AVAILABLE = False+ ft = None+++# ============================================================================+# FALLBACK IMPLEMENTATIONS (Pure NumPy/SciPy)+# ============================================================================++def _fallback_portfolio_vol(weights: np.ndarray, returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None) -> float:+ """Fallback portfolio volatility calculation using NumPy."""+ # Flatten weights for calculation+ w = weights.flatten()++ if isinstance(returns, pd.DataFrame):+ returns = returns.values++ # Calculate weighted covariance matrix+ if probabilities is not None:+ if probabilities.ndim == 2:+ p = probabilities.flatten()+ else:+ p = probabilities+ # Weighted mean+ mean_returns = returns.T @ p+ # Weighted covariance+ centered = returns - mean_returns+ cov = (centered.T * p) @ centered+ else:+ cov = np.cov(returns, rowvar=False)++ # Portfolio variance: w' * cov * w+ port_var = w @ cov @ w+ return float(np.sqrt(port_var))+++def _fallback_portfolio_var(weights: np.ndarray, returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None,+ alpha: float = 0.05, demean: bool = False) -> float:+ """Fallback VaR calculation using NumPy."""+ # Always flatten weights to ensure 1D array for matrix multiplication+ w = weights.flatten()++ if isinstance(returns, pd.DataFrame):+ returns = returns.values++ # Calculate portfolio returns (result should be 1D)+ port_returns = returns @ w++ if demean:+ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ port_returns = port_returns - np.sum(port_returns * p)+ else:+ port_returns = port_returns - np.mean(port_returns)++ if probabilities is not None:+ # Weighted quantile+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ sorted_idx = np.argsort(port_returns)+ sorted_returns = port_returns[sorted_idx]+ sorted_probs = p[sorted_idx]+ cumsum = np.cumsum(sorted_probs)+ var_idx = np.searchsorted(cumsum, alpha)+ var = -sorted_returns[min(var_idx, len(sorted_returns) - 1)]+ else:+ var = -np.percentile(port_returns, alpha * 100)++ return float(var)+++def _fallback_portfolio_cvar(weights: np.ndarray, returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None,+ alpha: float = 0.05, demean: bool = False) -> float:+ """Fallback CVaR (Expected Shortfall) calculation using NumPy."""+ # Always flatten weights to ensure 1D array for matrix multiplication+ w = weights.flatten()++ if isinstance(returns, pd.DataFrame):+ returns = returns.values++ # Calculate portfolio returns (result should be 1D)+ port_returns = returns @ w++ if demean:+ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ port_returns = port_returns - np.sum(port_returns * p)+ else:+ port_returns = port_returns - np.mean(port_returns)++ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ sorted_idx = np.argsort(port_returns)+ sorted_returns = port_returns[sorted_idx]+ sorted_probs = p[sorted_idx]+ cumsum = np.cumsum(sorted_probs)+ tail_mask = cumsum <= alpha+ if np.any(tail_mask):+ tail_probs = sorted_probs[tail_mask]+ tail_returns = sorted_returns[tail_mask]+ cvar = -np.sum(tail_returns * tail_probs) / np.sum(tail_probs)+ else:+ cvar = -sorted_returns[0]+ else:+ threshold = np.percentile(port_returns, alpha * 100)+ tail_returns = port_returns[port_returns <= threshold]+ cvar = -np.mean(tail_returns) if len(tail_returns) > 0 else -threshold++ return float(cvar)+++def _fallback_covariance_matrix(returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:+ """Fallback covariance matrix calculation."""+ if isinstance(returns, pd.DataFrame):+ columns = returns.columns+ returns_arr = returns.values+ else:+ columns = [f'Asset_{i}' for i in range(returns.shape[1])]+ returns_arr = returns++ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ mean_returns = returns_arr.T @ p+ centered = returns_arr - mean_returns+ cov = (centered.T * p) @ centered+ else:+ cov = np.cov(returns_arr, rowvar=False)++ return pd.DataFrame(cov, index=columns, columns=columns)+++def _fallback_correlation_matrix(returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:+ """Fallback correlation matrix calculation."""+ cov = _fallback_covariance_matrix(returns, probabilities)+ std = np.sqrt(np.diag(cov.values))+ corr = cov.values / np.outer(std, std)+ np.fill_diagonal(corr, 1.0)+ return pd.DataFrame(corr, index=cov.index, columns=cov.columns)+++def _fallback_simulation_moments(returns: np.ndarray,+ probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:+ """Fallback statistical moments calculation."""+ if isinstance(returns, pd.DataFrame):+ columns = returns.columns+ returns_arr = returns.values+ else:+ columns = [f'Asset_{i}' for i in range(returns.shape[1])]+ returns_arr = returns++ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ mean = returns_arr.T @ p+ centered = returns_arr - mean+ var = (centered ** 2).T @ p+ std = np.sqrt(var)+ skew = ((centered ** 3).T @ p) / (std ** 3)+ kurt = ((centered ** 4).T @ p) / (std ** 4) - 3+ else:+ mean = np.mean(returns_arr, axis=0)+ std = np.std(returns_arr, axis=0, ddof=1)+ from scipy import stats+ skew = stats.skew(returns_arr, axis=0)+ kurt = stats.kurtosis(returns_arr, axis=0)++ moments = pd.DataFrame({+ 'Mean': mean,+ 'Volatility': std,+ 'Skewness': skew,+ 'Kurtosis': kurt+ }, index=columns)++ return moments+++def _fallback_exp_decay_probs(returns: np.ndarray, half_life: int = 252) -> np.ndarray:+ """Fallback exponential decay probabilities."""+ if isinstance(returns, pd.DataFrame):+ n = len(returns)+ else:+ n = returns.shape[0]++ # Calculate decay factor+ decay = np.log(2) / half_life++ # Generate weights (most recent = highest weight)+ weights = np.exp(-decay * np.arange(n)[::-1])++ # Normalize to probabilities+ probs = weights / np.sum(weights)++ return probs.reshape(-1, 1)+++def _fallback_normal_exp_decay_calib(returns: np.ndarray,+ half_life: int = 252) -> Tuple[np.ndarray, np.ndarray]:+ """Fallback normal distribution calibration with exponential decay."""+ probs = _fallback_exp_decay_probs(returns, half_life)++ if isinstance(returns, pd.DataFrame):+ returns_arr = returns.values+ else:+ returns_arr = returns++ p = probs.flatten()+ mean = returns_arr.T @ p+ centered = returns_arr - mean+ cov = (centered.T * p) @ centered++ return mean, cov+def calculate_portfolio_volatility(weights: np.ndarray,@@ -23,12 +243,14 @@ def calculate_portfolio_volatility(probabilities: Optional[np.ndarray] = None) -> float:"""Calculate portfolio volatility"""- # Ensure weights are 2D- if weights.ndim == 1:- weights = weights.reshape(-1, 1)-- vol = ft.portfolio_vol(e=weights, R=returns, p=probabilities)- return float(vol)+ if FORTITUDO_AVAILABLE:+ # Ensure weights are 2D+ if weights.ndim == 1:+ weights = weights.reshape(-1, 1)+ vol = ft.portfolio_vol(e=weights, R=returns, p=probabilities)+ return float(vol)+ else:+ return _fallback_portfolio_vol(weights, returns, probabilities)def calculate_portfolio_var(@@ -39,11 +261,13 @@ def calculate_portfolio_var(demean: bool = False) -> float:"""Calculate portfolio Value-at-Risk"""- if weights.ndim == 1:- weights = weights.reshape(-1, 1)-- var = ft.portfolio_var(e=weights, R=returns, p=probabilities, alpha=alpha, demean=demean)- return float(var)+ if FORTITUDO_AVAILABLE:+ if weights.ndim == 1:+ weights = weights.reshape(-1, 1)+ var = ft.portfolio_var(e=weights, R=returns, p=probabilities, alpha=alpha, demean=demean)+ return float(var)+ else:+ return _fallback_portfolio_var(weights, returns, probabilities, alpha, demean)def calculate_portfolio_cvar(@@ -54,11 +278,13 @@ def calculate_portfolio_cvar(demean: bool = False) -> float:"""Calculate portfolio Conditional Value-at-Risk"""- if weights.ndim == 1:- weights = weights.reshape(-1, 1)-- cvar = ft.portfolio_cvar(e=weights, R=returns, p=probabilities, alpha=alpha, demean=demean)- return float(cvar)+ if FORTITUDO_AVAILABLE:+ if weights.ndim == 1:+ weights = weights.reshape(-1, 1)+ cvar = ft.portfolio_cvar(e=weights, R=returns, p=probabilities, alpha=alpha, demean=demean)+ return float(cvar)+ else:+ return _fallback_portfolio_cvar(weights, returns, probabilities, alpha, demean)def calculate_covariance_matrix(@@ -66,8 +292,11 @@ def calculate_covariance_matrix(probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:"""Calculate covariance matrix"""- cov = ft.covariance_matrix(R=returns, p=probabilities)- return cov+ if FORTITUDO_AVAILABLE:+ cov = ft.covariance_matrix(R=returns, p=probabilities)+ return cov+ else:+ return _fallback_covariance_matrix(returns, probabilities)def calculate_correlation_matrix(@@ -75,8 +304,11 @@ def calculate_correlation_matrix(probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:"""Calculate correlation matrix"""- corr = ft.correlation_matrix(R=returns, p=probabilities)- return corr+ if FORTITUDO_AVAILABLE:+ corr = ft.correlation_matrix(R=returns, p=probabilities)+ return corr+ else:+ return _fallback_correlation_matrix(returns, probabilities)def calculate_simulation_moments(@@ -84,8 +316,11 @@ def calculate_simulation_moments(probabilities: Optional[np.ndarray] = None) -> pd.DataFrame:"""Calculate statistical moments (mean, volatility, skewness, kurtosis)"""- moments = ft.simulation_moments(R=returns, p=probabilities)- return moments+ if FORTITUDO_AVAILABLE:+ moments = ft.simulation_moments(R=returns, p=probabilities)+ return moments+ else:+ return _fallback_simulation_moments(returns, probabilities)def calculate_exp_decay_probabilities(@@ -93,8 +328,11 @@ def calculate_exp_decay_probabilities(half_life: int = 252) -> np.ndarray:"""Calculate exponentially decaying probabilities"""- probs = ft.exp_decay_probs(R=returns, half_life=half_life)- return probs+ if FORTITUDO_AVAILABLE:+ probs = ft.exp_decay_probs(R=returns, half_life=half_life)+ return probs+ else:+ return _fallback_exp_decay_probs(returns, half_life)def calculate_normal_calibration(@@ -102,8 +340,11 @@ def calculate_normal_calibration(half_life: int = 252) -> Tuple:"""Calibrate normal distribution with exponential decay"""- mean, cov = ft.normal_exp_decay_calib(R=returns, half_life=half_life)- return mean, cov+ if FORTITUDO_AVAILABLE:+ mean, cov = ft.normal_exp_decay_calib(R=returns, half_life=half_life)+ return mean, cov+ else:+ return _fallback_normal_exp_decay_calib(returns, half_life)def calculate_all_metrics(diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/optimization.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/optimization.pynew file mode 100644index 000000000..fa24330cb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/optimization.py@@ -0,0 +1,653 @@+"""+Fortitudo.tech Portfolio Optimization Wrapper+==============================================+Mean-Variance and Mean-CVaR optimization using convex optimization.++Implements portfolio optimization with constraints using scipy or cvxopt.++Usage:+ python optimization.py+"""++import numpy as np+import pandas as pd+from typing import Dict, Any, Optional, List, Tuple, Union+import warnings++warnings.filterwarnings('ignore')++# Try to import optimization backends+try:+ from scipy.optimize import minimize, LinearConstraint, Bounds+ SCIPY_AVAILABLE = True+except ImportError:+ SCIPY_AVAILABLE = False++try:+ import cvxopt+ from cvxopt import matrix, solvers+ solvers.options['show_progress'] = False+ CVXOPT_AVAILABLE = True+except ImportError:+ CVXOPT_AVAILABLE = False++try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+except ImportError:+ FORTITUDO_AVAILABLE = False+ ft = None+++class MeanVarianceOptimizer:+ """+ Mean-Variance Portfolio Optimization++ Minimizes portfolio variance for a given target return,+ or maximizes return for a given risk level.++ Methods:+ - minimum_variance(): Find the global minimum variance portfolio+ - efficient_frontier(): Generate efficient frontier points+ - max_sharpe(): Find the maximum Sharpe ratio portfolio+ - target_return(): Find portfolio with target return and minimum variance+ - target_risk(): Find portfolio with target risk and maximum return+ """++ def __init__(+ self,+ returns: Union[pd.DataFrame, np.ndarray],+ probabilities: Optional[np.ndarray] = None,+ risk_free_rate: float = 0.0+ ):+ """+ Initialize optimizer with return data.++ Args:+ returns: Asset returns matrix (n_scenarios x n_assets)+ probabilities: Scenario probabilities (optional)+ risk_free_rate: Risk-free rate for Sharpe ratio calculation+ """+ if isinstance(returns, pd.DataFrame):+ self.asset_names = list(returns.columns)+ self.returns = returns.values+ else:+ self.returns = returns+ self.asset_names = [f'Asset_{i}' for i in range(returns.shape[1])]++ self.n_scenarios, self.n_assets = self.returns.shape+ self.probabilities = probabilities+ self.risk_free_rate = risk_free_rate++ # Calculate mean returns and covariance matrix+ if probabilities is not None:+ p = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ self.mean_returns = self.returns.T @ p+ centered = self.returns - self.mean_returns+ self.cov_matrix = (centered.T * p) @ centered+ else:+ self.mean_returns = np.mean(self.returns, axis=0)+ self.cov_matrix = np.cov(self.returns, rowvar=False)++ def _portfolio_variance(self, weights: np.ndarray) -> float:+ """Calculate portfolio variance."""+ return float(weights @ self.cov_matrix @ weights)++ def _portfolio_volatility(self, weights: np.ndarray) -> float:+ """Calculate portfolio volatility."""+ return np.sqrt(self._portfolio_variance(weights))++ def _portfolio_return(self, weights: np.ndarray) -> float:+ """Calculate portfolio expected return."""+ return float(weights @ self.mean_returns)++ def _sharpe_ratio(self, weights: np.ndarray) -> float:+ """Calculate portfolio Sharpe ratio."""+ port_return = self._portfolio_return(weights)+ port_vol = self._portfolio_volatility(weights)+ if port_vol == 0:+ return 0.0+ return (port_return - self.risk_free_rate) / port_vol++ def minimum_variance(+ self,+ long_only: bool = True,+ max_weight: Optional[float] = None,+ min_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Find the global minimum variance portfolio.++ Args:+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset+ min_weight: Minimum weight per asset++ Returns:+ Dictionary with optimal weights and metrics+ """+ if not SCIPY_AVAILABLE:+ return {"success": False, "error": "scipy not available"}++ n = self.n_assets++ # Initial guess: equal weights+ x0 = np.ones(n) / n++ # Bounds+ if long_only:+ lower = min_weight if min_weight is not None else 0.0+ upper = max_weight if max_weight is not None else 1.0+ bounds = Bounds(np.full(n, lower), np.full(n, upper))+ else:+ lower = min_weight if min_weight is not None else -1.0+ upper = max_weight if max_weight is not None else 1.0+ bounds = Bounds(np.full(n, lower), np.full(n, upper))++ # Sum to 1 constraint+ constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]++ # Minimize variance+ result = minimize(+ self._portfolio_variance,+ x0,+ method='SLSQP',+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ if result.success:+ weights = result.x+ return {+ "success": True,+ "weights": dict(zip(self.asset_names, weights.tolist())),+ "expected_return": self._portfolio_return(weights),+ "volatility": self._portfolio_volatility(weights),+ "sharpe_ratio": self._sharpe_ratio(weights),+ "variance": self._portfolio_variance(weights)+ }+ else:+ return {"success": False, "error": result.message}++ def max_sharpe(+ self,+ long_only: bool = True,+ max_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Find the maximum Sharpe ratio portfolio.++ Args:+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset++ Returns:+ Dictionary with optimal weights and metrics+ """+ if not SCIPY_AVAILABLE:+ return {"success": False, "error": "scipy not available"}++ n = self.n_assets+ x0 = np.ones(n) / n++ # Negative Sharpe ratio for minimization+ def neg_sharpe(weights):+ return -self._sharpe_ratio(weights)++ # Bounds+ if long_only:+ bounds = Bounds(np.zeros(n), np.full(n, max_weight if max_weight else 1.0))+ else:+ bounds = Bounds(np.full(n, -1.0), np.full(n, max_weight if max_weight else 1.0))++ constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]++ result = minimize(+ neg_sharpe,+ x0,+ method='SLSQP',+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ if result.success:+ weights = result.x+ return {+ "success": True,+ "weights": dict(zip(self.asset_names, weights.tolist())),+ "expected_return": self._portfolio_return(weights),+ "volatility": self._portfolio_volatility(weights),+ "sharpe_ratio": self._sharpe_ratio(weights),+ "variance": self._portfolio_variance(weights)+ }+ else:+ return {"success": False, "error": result.message}++ def target_return(+ self,+ target: float,+ long_only: bool = True,+ max_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Find minimum variance portfolio for a target return.++ Args:+ target: Target expected return+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset++ Returns:+ Dictionary with optimal weights and metrics+ """+ if not SCIPY_AVAILABLE:+ return {"success": False, "error": "scipy not available"}++ n = self.n_assets+ x0 = np.ones(n) / n++ if long_only:+ bounds = Bounds(np.zeros(n), np.full(n, max_weight if max_weight else 1.0))+ else:+ bounds = Bounds(np.full(n, -1.0), np.full(n, max_weight if max_weight else 1.0))++ constraints = [+ {'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0},+ {'type': 'eq', 'fun': lambda w: self._portfolio_return(w) - target}+ ]++ result = minimize(+ self._portfolio_variance,+ x0,+ method='SLSQP',+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ if result.success:+ weights = result.x+ return {+ "success": True,+ "weights": dict(zip(self.asset_names, weights.tolist())),+ "expected_return": self._portfolio_return(weights),+ "volatility": self._portfolio_volatility(weights),+ "sharpe_ratio": self._sharpe_ratio(weights),+ "target_return": target+ }+ else:+ return {"success": False, "error": result.message}++ def efficient_frontier(+ self,+ n_points: int = 20,+ long_only: bool = True,+ max_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Generate the efficient frontier.++ Args:+ n_points: Number of points on the frontier+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset++ Returns:+ Dictionary with frontier points+ """+ # Get min and max returns+ min_var_result = self.minimum_variance(long_only, max_weight)+ if not min_var_result["success"]:+ return min_var_result++ min_return = min_var_result["expected_return"]++ # Find max return portfolio (100% in highest return asset if long_only)+ if long_only:+ max_return = np.max(self.mean_returns)+ else:+ max_return = min_return + 3 * min_var_result["volatility"]++ # Generate target returns+ target_returns = np.linspace(min_return, max_return, n_points)++ frontier = []+ for target in target_returns:+ result = self.target_return(target, long_only, max_weight)+ if result["success"]:+ frontier.append({+ "expected_return": result["expected_return"],+ "volatility": result["volatility"],+ "sharpe_ratio": result["sharpe_ratio"],+ "weights": result["weights"]+ })++ return {+ "success": True,+ "frontier": frontier,+ "n_points": len(frontier),+ "min_variance_portfolio": min_var_result+ }+++class MeanCVaROptimizer:+ """+ Mean-CVaR Portfolio Optimization++ Minimizes Conditional Value-at-Risk (Expected Shortfall) for a given target return,+ or maximizes return for a given CVaR level.++ CVaR is a coherent risk measure that considers the expected loss in the worst cases.+ """++ def __init__(+ self,+ returns: Union[pd.DataFrame, np.ndarray],+ probabilities: Optional[np.ndarray] = None,+ alpha: float = 0.05,+ risk_free_rate: float = 0.0+ ):+ """+ Initialize optimizer.++ Args:+ returns: Asset returns matrix (n_scenarios x n_assets)+ probabilities: Scenario probabilities (optional)+ alpha: Significance level for CVaR (e.g., 0.05 for 95% CVaR)+ risk_free_rate: Risk-free rate+ """+ if isinstance(returns, pd.DataFrame):+ self.asset_names = list(returns.columns)+ self.returns = returns.values+ else:+ self.returns = returns+ self.asset_names = [f'Asset_{i}' for i in range(returns.shape[1])]++ self.n_scenarios, self.n_assets = self.returns.shape+ self.alpha = alpha+ self.risk_free_rate = risk_free_rate++ if probabilities is not None:+ self.probabilities = probabilities.flatten() if probabilities.ndim == 2 else probabilities+ else:+ self.probabilities = np.ones(self.n_scenarios) / self.n_scenarios++ # Mean returns+ self.mean_returns = self.returns.T @ self.probabilities++ def _portfolio_return(self, weights: np.ndarray) -> float:+ """Calculate portfolio expected return."""+ return float(weights @ self.mean_returns)++ def _portfolio_cvar(self, weights: np.ndarray) -> float:+ """Calculate portfolio CVaR."""+ port_returns = self.returns @ weights++ # Sort returns and probabilities+ sorted_idx = np.argsort(port_returns)+ sorted_returns = port_returns[sorted_idx]+ sorted_probs = self.probabilities[sorted_idx]++ # Find CVaR+ cumsum = np.cumsum(sorted_probs)+ tail_mask = cumsum <= self.alpha+ if np.any(tail_mask):+ tail_probs = sorted_probs[tail_mask]+ tail_returns = sorted_returns[tail_mask]+ cvar = -np.sum(tail_returns * tail_probs) / np.sum(tail_probs)+ else:+ cvar = -sorted_returns[0]++ return float(cvar)++ def _portfolio_var(self, weights: np.ndarray) -> float:+ """Calculate portfolio VaR."""+ port_returns = self.returns @ weights+ sorted_idx = np.argsort(port_returns)+ sorted_returns = port_returns[sorted_idx]+ sorted_probs = self.probabilities[sorted_idx]+ cumsum = np.cumsum(sorted_probs)+ var_idx = np.searchsorted(cumsum, self.alpha)+ return -sorted_returns[min(var_idx, len(sorted_returns) - 1)]++ def minimum_cvar(+ self,+ long_only: bool = True,+ max_weight: Optional[float] = None,+ min_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Find the minimum CVaR portfolio.++ Args:+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset+ min_weight: Minimum weight per asset++ Returns:+ Dictionary with optimal weights and metrics+ """+ if not SCIPY_AVAILABLE:+ return {"success": False, "error": "scipy not available"}++ n = self.n_assets+ x0 = np.ones(n) / n++ # Bounds+ if long_only:+ lower = min_weight if min_weight is not None else 0.0+ upper = max_weight if max_weight is not None else 1.0+ bounds = Bounds(np.full(n, lower), np.full(n, upper))+ else:+ lower = min_weight if min_weight is not None else -1.0+ upper = max_weight if max_weight is not None else 1.0+ bounds = Bounds(np.full(n, lower), np.full(n, upper))++ constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]++ result = minimize(+ self._portfolio_cvar,+ x0,+ method='SLSQP',+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ if result.success:+ weights = result.x+ return {+ "success": True,+ "weights": dict(zip(self.asset_names, weights.tolist())),+ "expected_return": self._portfolio_return(weights),+ "cvar": self._portfolio_cvar(weights),+ "var": self._portfolio_var(weights),+ "alpha": self.alpha+ }+ else:+ return {"success": False, "error": result.message}++ def target_return(+ self,+ target: float,+ long_only: bool = True,+ max_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Find minimum CVaR portfolio for a target return.++ Args:+ target: Target expected return+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset++ Returns:+ Dictionary with optimal weights and metrics+ """+ if not SCIPY_AVAILABLE:+ return {"success": False, "error": "scipy not available"}++ n = self.n_assets+ x0 = np.ones(n) / n++ if long_only:+ bounds = Bounds(np.zeros(n), np.full(n, max_weight if max_weight else 1.0))+ else:+ bounds = Bounds(np.full(n, -1.0), np.full(n, max_weight if max_weight else 1.0))++ constraints = [+ {'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0},+ {'type': 'eq', 'fun': lambda w: self._portfolio_return(w) - target}+ ]++ result = minimize(+ self._portfolio_cvar,+ x0,+ method='SLSQP',+ bounds=bounds,+ constraints=constraints,+ options={'maxiter': 1000}+ )++ if result.success:+ weights = result.x+ return {+ "success": True,+ "weights": dict(zip(self.asset_names, weights.tolist())),+ "expected_return": self._portfolio_return(weights),+ "cvar": self._portfolio_cvar(weights),+ "var": self._portfolio_var(weights),+ "target_return": target,+ "alpha": self.alpha+ }+ else:+ return {"success": False, "error": result.message}++ def efficient_frontier(+ self,+ n_points: int = 20,+ long_only: bool = True,+ max_weight: Optional[float] = None+ ) -> Dict[str, Any]:+ """+ Generate the CVaR-efficient frontier.++ Args:+ n_points: Number of points on the frontier+ long_only: If True, enforce non-negative weights+ max_weight: Maximum weight per asset++ Returns:+ Dictionary with frontier points+ """+ # Get min CVaR portfolio+ min_cvar_result = self.minimum_cvar(long_only, max_weight)+ if not min_cvar_result["success"]:+ return min_cvar_result++ min_return = min_cvar_result["expected_return"]++ # Find max return+ if long_only:+ max_return = np.max(self.mean_returns)+ else:+ max_return = min_return + 3 * min_cvar_result["cvar"]++ # Generate target returns+ target_returns = np.linspace(min_return, max_return, n_points)++ frontier = []+ for target in target_returns:+ result = self.target_return(target, long_only, max_weight)+ if result["success"]:+ frontier.append({+ "expected_return": result["expected_return"],+ "cvar": result["cvar"],+ "var": result["var"],+ "weights": result["weights"]+ })++ return {+ "success": True,+ "frontier": frontier,+ "n_points": len(frontier),+ "min_cvar_portfolio": min_cvar_result,+ "alpha": self.alpha+ }+++def main():+ """Test optimization functions."""+ print("=== Portfolio Optimization Test ===\n")++ # Generate test data+ np.random.seed(42)+ n_scenarios = 200+ n_assets = 4+ asset_names = ['Stocks', 'Bonds', 'Commodities', 'Cash']++ # Different return characteristics for each asset+ returns = np.column_stack([+ np.random.randn(n_scenarios) * 0.02 + 0.0003, # Stocks: high vol, high return+ np.random.randn(n_scenarios) * 0.005 + 0.0001, # Bonds: low vol, low return+ np.random.randn(n_scenarios) * 0.015 + 0.0002, # Commodities: med vol+ np.random.randn(n_scenarios) * 0.001 + 0.0001, # Cash: very low vol+ ])++ returns_df = pd.DataFrame(returns, columns=asset_names)++ # Test Mean-Variance Optimizer+ print("1. Mean-Variance Optimization")+ print("-" * 50)++ mv_optimizer = MeanVarianceOptimizer(returns_df, risk_free_rate=0.0001)++ # Minimum variance portfolio+ min_var = mv_optimizer.minimum_variance()+ if min_var["success"]:+ print(" Minimum Variance Portfolio:")+ print(f" Return: {min_var['expected_return']:.6f}")+ print(f" Volatility: {min_var['volatility']:.6f}")+ print(f" Sharpe: {min_var['sharpe_ratio']:.4f}")+ print(f" Weights: {min_var['weights']}")++ # Max Sharpe portfolio+ max_sharpe = mv_optimizer.max_sharpe()+ if max_sharpe["success"]:+ print("\n Maximum Sharpe Portfolio:")+ print(f" Return: {max_sharpe['expected_return']:.6f}")+ print(f" Volatility: {max_sharpe['volatility']:.6f}")+ print(f" Sharpe: {max_sharpe['sharpe_ratio']:.4f}")+ print(f" Weights: {max_sharpe['weights']}")++ # Test Mean-CVaR Optimizer+ print("\n2. Mean-CVaR Optimization")+ print("-" * 50)++ cvar_optimizer = MeanCVaROptimizer(returns_df, alpha=0.05)++ # Minimum CVaR portfolio+ min_cvar = cvar_optimizer.minimum_cvar()+ if min_cvar["success"]:+ print(" Minimum CVaR Portfolio (95%):")+ print(f" Return: {min_cvar['expected_return']:.6f}")+ print(f" CVaR: {min_cvar['cvar']:.6f}")+ print(f" VaR: {min_cvar['var']:.6f}")+ print(f" Weights: {min_cvar['weights']}")++ # Efficient frontier+ print("\n3. Efficient Frontier (5 points)")+ print("-" * 50)+ frontier = mv_optimizer.efficient_frontier(n_points=5)+ if frontier["success"]:+ print(" Return Volatility Sharpe")+ for pt in frontier["frontier"]:+ print(f" {pt['expected_return']:.6f} {pt['volatility']:.6f} {pt['sharpe_ratio']:.4f}")++ print("\n=== Test: PASSED ===")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/option_pricing.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/option_pricing.pyindex 0aa2792a6..8375d2410 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/option_pricing.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/option_pricing.py@@ -3,13 +3,301 @@ Fortitudo.tech Option Pricing Wrapper======================================Black-Scholes option pricing and forward calculations+Includes fallback implementations using NumPy/SciPy for Python 3.14+ compatibility.+Usage:python option_pricing.py"""import json+import mathfrom typing import Dict, Any-import fortitudo.tech as ft+import numpy as np+from scipy import stats as scipy_stats++# Try to import fortitudo.tech, fallback to pure implementations+try:+ import fortitudo.tech as ft+ FORTITUDO_AVAILABLE = True+except ImportError:+ FORTITUDO_AVAILABLE = False+ ft = None+++# ============================================================================+# FALLBACK IMPLEMENTATIONS (Pure NumPy/SciPy Black-Scholes)+# ============================================================================++def _d1(F: float, K: float, sigma: float, T: float) -> float:+ """Calculate d1 for Black-Scholes formula."""+ return (np.log(F / K) + 0.5 * sigma**2 * T) / (sigma * np.sqrt(T))+++def _d2(F: float, K: float, sigma: float, T: float) -> float:+ """Calculate d2 for Black-Scholes formula."""+ return _d1(F, K, sigma, T) - sigma * np.sqrt(T)+++def _fallback_call_option(F: float, K: float, sigma: float, r: float, T: float) -> float:+ """Fallback Black-Scholes call option pricing."""+ d1 = _d1(F, K, sigma, T)+ d2 = _d2(F, K, sigma, T)+ discount = np.exp(-r * T)+ return float(discount * (F * scipy_stats.norm.cdf(d1) - K * scipy_stats.norm.cdf(d2)))+++def _fallback_put_option(F: float, K: float, sigma: float, r: float, T: float) -> float:+ """Fallback Black-Scholes put option pricing."""+ d1 = _d1(F, K, sigma, T)+ d2 = _d2(F, K, sigma, T)+ discount = np.exp(-r * T)+ return float(discount * (K * scipy_stats.norm.cdf(-d2) - F * scipy_stats.norm.cdf(-d1)))+++def _fallback_forward(S: float, r: float, q: float, T: float) -> float:+ """Fallback forward price calculation."""+ return float(S * np.exp((r - q) * T))+++# ============================================================================+# OPTION GREEKS (Delta, Gamma, Vega, Theta, Rho)+# ============================================================================++def calculate_call_delta(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate call option delta.++ Delta measures the sensitivity of option price to underlying price changes.++ Returns:+ Delta value (0 to 1 for calls)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ delta = np.exp(-dividend_yield * time_to_maturity) * scipy_stats.norm.cdf(d1)+ return float(delta)+++def calculate_put_delta(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate put option delta.++ Returns:+ Delta value (-1 to 0 for puts)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ delta = np.exp(-dividend_yield * time_to_maturity) * (scipy_stats.norm.cdf(d1) - 1)+ return float(delta)+++def calculate_gamma(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate option gamma (same for calls and puts).++ Gamma measures the rate of change of delta with respect to underlying price.++ Returns:+ Gamma value+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ gamma = (np.exp(-dividend_yield * time_to_maturity) * scipy_stats.norm.pdf(d1) /+ (spot_price * volatility * np.sqrt(time_to_maturity)))+ return float(gamma)+++def calculate_vega(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate option vega (same for calls and puts).++ Vega measures sensitivity to volatility changes.+ Returns vega per 1% change in volatility.++ Returns:+ Vega value (per 1% vol change)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ vega = (spot_price * np.exp(-dividend_yield * time_to_maturity) *+ scipy_stats.norm.pdf(d1) * np.sqrt(time_to_maturity))+ return float(vega / 100) # Per 1% change+++def calculate_call_theta(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate call option theta (time decay).++ Theta measures the sensitivity to time passing.+ Returns theta per day.++ Returns:+ Theta value (per day)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ d2 = _d2(forward, strike, volatility, time_to_maturity)++ term1 = -(spot_price * scipy_stats.norm.pdf(d1) * volatility *+ np.exp(-dividend_yield * time_to_maturity)) / (2 * np.sqrt(time_to_maturity))+ term2 = dividend_yield * spot_price * scipy_stats.norm.cdf(d1) * np.exp(-dividend_yield * time_to_maturity)+ term3 = -risk_free_rate * strike * np.exp(-risk_free_rate * time_to_maturity) * scipy_stats.norm.cdf(d2)++ theta = (term1 + term2 + term3) / 365 # Per day+ return float(theta)+++def calculate_put_theta(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate put option theta (time decay).++ Returns:+ Theta value (per day)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d1 = _d1(forward, strike, volatility, time_to_maturity)+ d2 = _d2(forward, strike, volatility, time_to_maturity)++ term1 = -(spot_price * scipy_stats.norm.pdf(d1) * volatility *+ np.exp(-dividend_yield * time_to_maturity)) / (2 * np.sqrt(time_to_maturity))+ term2 = -dividend_yield * spot_price * scipy_stats.norm.cdf(-d1) * np.exp(-dividend_yield * time_to_maturity)+ term3 = risk_free_rate * strike * np.exp(-risk_free_rate * time_to_maturity) * scipy_stats.norm.cdf(-d2)++ theta = (term1 + term2 + term3) / 365 # Per day+ return float(theta)+++def calculate_call_rho(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate call option rho.++ Rho measures sensitivity to interest rate changes.+ Returns rho per 1% change in rates.++ Returns:+ Rho value (per 1% rate change)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d2 = _d2(forward, strike, volatility, time_to_maturity)+ rho = strike * time_to_maturity * np.exp(-risk_free_rate * time_to_maturity) * scipy_stats.norm.cdf(d2)+ return float(rho / 100) # Per 1% change+++def calculate_put_rho(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> float:+ """+ Calculate put option rho.++ Returns:+ Rho value (per 1% rate change)+ """+ forward = _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)+ d2 = _d2(forward, strike, volatility, time_to_maturity)+ rho = -strike * time_to_maturity * np.exp(-risk_free_rate * time_to_maturity) * scipy_stats.norm.cdf(-d2)+ return float(rho / 100) # Per 1% change+++def calculate_all_greeks(+ spot_price: float,+ strike: float,+ volatility: float,+ risk_free_rate: float,+ dividend_yield: float,+ time_to_maturity: float+) -> Dict[str, Any]:+ """+ Calculate all option Greeks for both call and put.++ Args:+ spot_price: Current underlying price+ strike: Strike price+ volatility: Implied volatility (annual)+ risk_free_rate: Risk-free rate (annual)+ dividend_yield: Dividend yield (annual)+ time_to_maturity: Time to maturity in years++ Returns:+ Dictionary with all Greeks for call and put options+ """+ return {+ 'call': {+ 'delta': calculate_call_delta(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'gamma': calculate_gamma(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'vega': calculate_vega(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'theta': calculate_call_theta(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'rho': calculate_call_rho(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ },+ 'put': {+ 'delta': calculate_put_delta(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'gamma': calculate_gamma(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'vega': calculate_vega(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'theta': calculate_put_theta(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ 'rho': calculate_put_rho(spot_price, strike, volatility, risk_free_rate, dividend_yield, time_to_maturity),+ },+ 'inputs': {+ 'spot_price': spot_price,+ 'strike': strike,+ 'volatility': volatility,+ 'risk_free_rate': risk_free_rate,+ 'dividend_yield': dividend_yield,+ 'time_to_maturity': time_to_maturity+ }+ }def price_call_option(@@ -32,14 +320,17 @@ def price_call_option(Returns:Call option price"""- price = ft.call_option(- F=forward_price,- K=strike,- sigma=volatility,- r=risk_free_rate,- T=time_to_maturity- )- return float(price)+ if FORTITUDO_AVAILABLE:+ price = ft.call_option(+ F=forward_price,+ K=strike,+ sigma=volatility,+ r=risk_free_rate,+ T=time_to_maturity+ )+ return float(price)+ else:+ return _fallback_call_option(forward_price, strike, volatility, risk_free_rate, time_to_maturity)def price_put_option(@@ -62,14 +353,17 @@ def price_put_option(Returns:Put option price"""- price = ft.put_option(- F=forward_price,- K=strike,- sigma=volatility,- r=risk_free_rate,- T=time_to_maturity- )- return float(price)+ if FORTITUDO_AVAILABLE:+ price = ft.put_option(+ F=forward_price,+ K=strike,+ sigma=volatility,+ r=risk_free_rate,+ T=time_to_maturity+ )+ return float(price)+ else:+ return _fallback_put_option(forward_price, strike, volatility, risk_free_rate, time_to_maturity)def calculate_forward_price(@@ -90,13 +384,16 @@ def calculate_forward_price(Returns:Forward price"""- fwd = ft.forward(- S=spot_price,- r=risk_free_rate,- q=dividend_yield,- T=time_to_maturity- )- return float(fwd)+ if FORTITUDO_AVAILABLE:+ fwd = ft.forward(+ S=spot_price,+ r=risk_free_rate,+ q=dividend_yield,+ T=time_to_maturity+ )+ return float(fwd)+ else:+ return _fallback_forward(spot_price, risk_free_rate, dividend_yield, time_to_maturity)def price_option_straddle(diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/test_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/test_service.pynew file mode 100644index 000000000..0dceaef10--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/fortitudo_tech_wrapper/test_service.py@@ -0,0 +1,129 @@+"""Test script for fortitudo_service.py"""++import sys+import os+import json++# Add this directory to path+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++import fortitudo_service as fs+import numpy as np++def test_all():+ print("=" * 60)+ print("FORTITUDO.TECH SERVICE TESTS")+ print("=" * 60)+ print()++ # Test 1: Check Status+ print("1. CHECK STATUS")+ print("-" * 40)+ status = fs.check_status()+ print(f" Available: {status['available']}")+ print(f" Wrappers: {status['wrappers_available']}")+ print(f" Version: {status.get('version')}")+ print(f" Message: {status.get('message')}")+ print()++ if not status['available']:+ print("ERROR: Fortitudo.tech not available, cannot continue tests")+ return++ # Test 2: Option Pricing+ print("2. OPTION PRICING")+ print("-" * 40)+ option_params = {+ 'spot_price': 100,+ 'strike': 105,+ 'volatility': 0.25,+ 'risk_free_rate': 0.05,+ 'dividend_yield': 0.0,+ 'time_to_maturity': 1.0+ }+ opt_result = fs.option_pricing(option_params)+ if opt_result['success']:+ print(f" Forward Price: ${opt_result['forward_price']:.2f}")+ print(f" Call Price: ${opt_result['call_price']:.4f}")+ print(f" Put Price: ${opt_result['put_price']:.4f}")+ print(f" Straddle: ${opt_result['straddle']['straddle_price']:.4f}")+ else:+ print(f" ERROR: {opt_result.get('error')}")+ print()++ # Test 3: Entropy Pooling+ print("3. ENTROPY POOLING")+ print("-" * 40)+ ep_params = {+ 'n_scenarios': 100,+ 'max_probability': 0.03+ }+ ep_result = fs.entropy_pooling(ep_params)+ if ep_result['success']:+ print(f" Effective Scenarios (Prior): {ep_result['effective_scenarios_prior']:.1f}")+ print(f" Effective Scenarios (Posterior): {ep_result['effective_scenarios_posterior']:.1f}")+ print(f" Max Probability: {ep_result['max_probability']*100:.2f}%")+ print(f" Min Probability: {ep_result['min_probability']*100:.4f}%")+ else:+ print(f" ERROR: {ep_result.get('error')}")+ print()++ # Test 4: Portfolio Metrics+ print("4. PORTFOLIO METRICS")+ print("-" * 40)++ # Generate sample returns+ np.random.seed(42)+ n_scenarios = 200+ returns = {+ 'Stocks': {f'2024-01-{i+1:02d}': float(0.0003 + (np.random.random() - 0.5) * 0.02) for i in range(min(n_scenarios, 28))},+ 'Bonds': {f'2024-01-{i+1:02d}': float(0.0001 + (np.random.random() - 0.5) * 0.005) for i in range(min(n_scenarios, 28))}+ }+ weights = [0.6, 0.4]++ params = {+ 'returns': json.dumps(returns),+ 'weights': json.dumps(weights),+ 'alpha': 0.05+ }+ result = fs.portfolio_metrics(params)+ if result['success']:+ m = result['metrics']+ print(f" Expected Return: {m['expected_return']*100:.4f}%")+ print(f" Volatility: {m['volatility']*100:.4f}%")+ print(f" VaR (95%): {m['var']*100:.4f}%")+ print(f" CVaR (95%): {m['cvar']*100:.4f}%")+ print(f" Sharpe Ratio: {m['sharpe_ratio']:.3f}")+ print(f" N Scenarios: {result['n_scenarios']}")+ print(f" N Assets: {result['n_assets']}")+ else:+ print(f" ERROR: {result.get('error')}")+ print()++ # Test 5: Full Analysis+ print("5. FULL ANALYSIS")+ print("-" * 40)+ full_params = {+ 'returns': json.dumps(returns),+ 'weights': json.dumps(weights),+ 'alpha': 0.05,+ 'half_life': 120+ }+ full_result = fs.full_analysis(full_params)+ if full_result['success']:+ analysis = full_result['analysis']+ print(f" Equal Weight Sharpe: {analysis['metrics_equal_weight']['sharpe_ratio']:.3f}")+ print(f" Exp Decay Sharpe: {analysis['metrics_exp_decay']['sharpe_ratio']:.3f}")+ print(f" Half-Life: {analysis['half_life']} days")+ print(f" Alpha: {analysis['alpha']}")+ else:+ print(f" ERROR: {full_result.get('error')}")+ print()++ print("=" * 60)+ print("ALL TESTS COMPLETED SUCCESSFULLY!")+ print("=" * 60)+++if __name__ == "__main__":+ test_all()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_cv.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_cv.pynew file mode 100644index 000000000..84e722601--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_cv.py@@ -0,0 +1,555 @@+"""+Advanced Cross-Validation Module+================================++Provides sophisticated cross-validation strategies for time series:+- Blocked time series CV (prevents leakage)+- Purged/Embargo CV (for financial data)+- Combinatorial purged CV+- Walk-forward validation+- Nested cross-validation++Critical for proper model evaluation in time series.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple, Generator+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')+++# ============================================================================+# BLOCKED TIME SERIES CV+# ============================================================================++def blocked_time_series_cv(+ y: pl.DataFrame,+ n_splits: int = 5,+ test_size: int = 1,+ gap: int = 0+) -> Dict[str, Any]:+ """+ Blocked time series cross-validation with optional gap.++ Unlike expanding window, uses fixed-size training blocks to+ prevent data leakage and maintain stationarity.++ Args:+ y: Panel data+ n_splits: Number of CV splits+ test_size: Test set size per split+ gap: Gap between train and test (prevents leakage)+ """+ splits = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ # Calculate block size+ total_test = n_splits * test_size+ total_gap = n_splits * gap+ available_for_train = n - total_test - total_gap++ if available_for_train < n_splits * 10:+ continue++ block_size = available_for_train // n_splits++ entity_splits = []+ for i in range(n_splits):+ train_start = i * block_size+ train_end = (i + 1) * block_size+ test_start = train_end + gap+ test_end = test_start + test_size++ if test_end > n:+ break++ train_data = entity_data[train_start:train_end]+ test_data = entity_data[test_start:test_end]++ entity_splits.append({+ 'split': i,+ 'train_start': train_start,+ 'train_end': train_end,+ 'test_start': test_start,+ 'test_end': test_end,+ 'train_shape': train_data.shape,+ 'test_shape': test_data.shape,+ 'train': train_data.to_dicts(),+ 'test': test_data.to_dicts()+ })++ splits.append({+ 'entity_id': entity_id,+ 'n_splits': len(entity_splits),+ 'splits': entity_splits+ })++ return {+ 'success': True,+ 'method': 'blocked',+ 'n_splits': n_splits,+ 'test_size': test_size,+ 'gap': gap,+ 'data': splits+ }+++# ============================================================================+# PURGED K-FOLD CV+# ============================================================================++def purged_kfold_cv(+ y: pl.DataFrame,+ n_splits: int = 5,+ embargo_pct: float = 0.01,+ purge_pct: float = 0.01+) -> Dict[str, Any]:+ """+ Purged K-Fold cross-validation for financial data.++ Removes observations that could leak information from train to test:+ - Purge: Remove training samples close to test set+ - Embargo: Remove period after test set from subsequent training++ Essential for time series with overlapping windows or labels.++ Args:+ y: Panel data+ n_splits: Number of folds+ embargo_pct: Percentage of data to embargo after test set+ purge_pct: Percentage of data to purge before test set+ """+ splits = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ fold_size = n // n_splits+ embargo_size = int(n * embargo_pct)+ purge_size = int(n * purge_pct)++ entity_splits = []++ for i in range(n_splits):+ test_start = i * fold_size+ test_end = min((i + 1) * fold_size, n)++ # Purge period (before test)+ purge_start = max(0, test_start - purge_size)++ # Embargo period (after test)+ embargo_end = min(n, test_end + embargo_size)++ # Training indices (everything except test, purge, embargo)+ train_indices = list(range(0, purge_start)) + list(range(embargo_end, n))++ if len(train_indices) < 10:+ continue++ train_data = entity_data[train_indices]+ test_data = entity_data[test_start:test_end]++ entity_splits.append({+ 'split': i,+ 'test_start': test_start,+ 'test_end': test_end,+ 'purge_start': purge_start,+ 'embargo_end': embargo_end,+ 'train_size': len(train_indices),+ 'test_size': test_end - test_start,+ 'train_shape': train_data.shape,+ 'test_shape': test_data.shape,+ 'train': train_data.to_dicts(),+ 'test': test_data.to_dicts()+ })++ splits.append({+ 'entity_id': entity_id,+ 'n_splits': len(entity_splits),+ 'splits': entity_splits+ })++ return {+ 'success': True,+ 'method': 'purged_kfold',+ 'n_splits': n_splits,+ 'embargo_pct': embargo_pct,+ 'purge_pct': purge_pct,+ 'data': splits+ }+++# ============================================================================+# COMBINATORIAL PURGED CV+# ============================================================================++def combinatorial_purged_cv(+ y: pl.DataFrame,+ n_test_splits: int = 2,+ n_groups: int = 6,+ embargo_pct: float = 0.01+) -> Dict[str, Any]:+ """+ Combinatorial Purged Cross-Validation (CPCV).++ Generates all combinations of test groups, providing more robust+ evaluation for small datasets.++ Args:+ y: Panel data+ n_test_splits: Number of groups used as test set+ n_groups: Total number of groups+ embargo_pct: Embargo percentage+ """+ from itertools import combinations++ splits = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ group_size = n // n_groups+ embargo_size = int(n * embargo_pct)++ # All combinations of test groups+ test_combinations = list(combinations(range(n_groups), n_test_splits))++ entity_splits = []++ for combo_idx, test_groups in enumerate(test_combinations):+ test_groups = set(test_groups)++ # Identify test indices+ test_indices = []+ for g in test_groups:+ start = g * group_size+ end = min((g + 1) * group_size, n)+ test_indices.extend(range(start, end))++ # Identify train indices with embargo+ train_indices = []+ for g in range(n_groups):+ if g in test_groups:+ continue++ start = g * group_size+ end = min((g + 1) * group_size, n)++ # Apply embargo if adjacent to test group+ if g + 1 in test_groups:+ end = max(start, end - embargo_size)+ if g - 1 in test_groups:+ start = min(end, start + embargo_size)++ train_indices.extend(range(start, end))++ if len(train_indices) < 10 or len(test_indices) < 1:+ continue++ train_data = entity_data[train_indices]+ test_data = entity_data[test_indices]++ entity_splits.append({+ 'split': combo_idx,+ 'test_groups': list(test_groups),+ 'train_size': len(train_indices),+ 'test_size': len(test_indices),+ 'train': train_data.to_dicts(),+ 'test': test_data.to_dicts()+ })++ splits.append({+ 'entity_id': entity_id,+ 'n_splits': len(entity_splits),+ 'n_combinations': len(test_combinations),+ 'splits': entity_splits+ })++ return {+ 'success': True,+ 'method': 'combinatorial_purged',+ 'n_test_splits': n_test_splits,+ 'n_groups': n_groups,+ 'embargo_pct': embargo_pct,+ 'data': splits+ }+++# ============================================================================+# WALK-FORWARD VALIDATION+# ============================================================================++def walk_forward_validation(+ y: pl.DataFrame,+ initial_train_size: int = 100,+ test_size: int = 1,+ step_size: int = 1,+ anchored: bool = False+) -> Dict[str, Any]:+ """+ Walk-forward (rolling origin) validation.++ Simulates real-world forecasting by training on past data+ and testing on future data in a rolling manner.++ Args:+ y: Panel data+ initial_train_size: Initial training window size+ test_size: Test window size+ step_size: Step size between origins+ anchored: If True, always start from beginning (expanding window)+ """+ splits = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ if n < initial_train_size + test_size:+ continue++ entity_splits = []+ origin = initial_train_size++ split_idx = 0+ while origin + test_size <= n:+ if anchored:+ train_start = 0+ else:+ train_start = max(0, origin - initial_train_size)++ train_end = origin+ test_start = origin+ test_end = min(origin + test_size, n)++ train_data = entity_data[train_start:train_end]+ test_data = entity_data[test_start:test_end]++ entity_splits.append({+ 'split': split_idx,+ 'origin': origin,+ 'train_start': train_start,+ 'train_end': train_end,+ 'test_start': test_start,+ 'test_end': test_end,+ 'train_shape': train_data.shape,+ 'test_shape': test_data.shape,+ 'train': train_data.to_dicts(),+ 'test': test_data.to_dicts()+ })++ origin += step_size+ split_idx += 1++ splits.append({+ 'entity_id': entity_id,+ 'n_splits': len(entity_splits),+ 'splits': entity_splits+ })++ return {+ 'success': True,+ 'method': 'walk_forward',+ 'initial_train_size': initial_train_size,+ 'test_size': test_size,+ 'step_size': step_size,+ 'anchored': anchored,+ 'data': splits+ }+++# ============================================================================+# NESTED CROSS-VALIDATION+# ============================================================================++def nested_cv(+ y: pl.DataFrame,+ outer_splits: int = 5,+ inner_splits: int = 3,+ test_size: int = 1+) -> Dict[str, Any]:+ """+ Nested cross-validation for unbiased model selection and evaluation.++ Outer loop: Model evaluation+ Inner loop: Hyperparameter tuning++ Prevents overfitting during model selection.++ Args:+ y: Panel data+ outer_splits: Number of outer CV splits+ inner_splits: Number of inner CV splits+ test_size: Test size per split+ """+ results = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ outer_fold_size = n // outer_splits++ entity_results = []++ for outer_i in range(outer_splits):+ # Outer test set+ outer_test_start = outer_i * outer_fold_size+ outer_test_end = min((outer_i + 1) * outer_fold_size, n)++ # Outer train set (everything before test)+ outer_train_end = outer_test_start++ if outer_train_end < inner_splits * 10:+ continue++ outer_train = entity_data[:outer_train_end]+ outer_test = entity_data[outer_test_start:outer_test_end]++ # Inner CV on outer training set+ inner_fold_size = len(outer_train) // inner_splits+ inner_splits_data = []++ for inner_i in range(inner_splits):+ inner_test_start = inner_i * inner_fold_size+ inner_test_end = min((inner_i + 1) * inner_fold_size, len(outer_train))+ inner_train_end = inner_test_start++ if inner_train_end < 10:+ continue++ inner_train = outer_train[:inner_train_end]+ inner_test = outer_train[inner_test_start:inner_test_end]++ inner_splits_data.append({+ 'inner_split': inner_i,+ 'inner_train_shape': inner_train.shape,+ 'inner_test_shape': inner_test.shape+ })++ entity_results.append({+ 'outer_split': outer_i,+ 'outer_train_shape': outer_train.shape,+ 'outer_test_shape': outer_test.shape,+ 'outer_train': outer_train.to_dicts(),+ 'outer_test': outer_test.to_dicts(),+ 'inner_splits': inner_splits_data+ })++ results.append({+ 'entity_id': entity_id,+ 'n_outer_splits': len(entity_results),+ 'splits': entity_results+ })++ return {+ 'success': True,+ 'method': 'nested',+ 'outer_splits': outer_splits,+ 'inner_splits': inner_splits,+ 'data': results+ }+++# ============================================================================+# UTILITY: GET CV GENERATOR+# ============================================================================++def get_cv_splits(+ y: pl.DataFrame,+ method: str = 'expanding',+ **kwargs+) -> Generator[Tuple[pl.DataFrame, pl.DataFrame], None, None]:+ """+ Get a generator of (train, test) splits.++ Args:+ y: Panel data+ method: CV method ('expanding', 'sliding', 'blocked', 'purged', 'walk_forward')+ **kwargs: Additional arguments for the CV method+ """+ if method == 'expanding':+ from cross_validation import create_expanding_window_splits+ result = create_expanding_window_splits(y, **kwargs)+ elif method == 'sliding':+ from cross_validation import create_sliding_window_splits+ result = create_sliding_window_splits(y, **kwargs)+ elif method == 'blocked':+ result = blocked_time_series_cv(y, **kwargs)+ elif method == 'purged':+ result = purged_kfold_cv(y, **kwargs)+ elif method == 'walk_forward':+ result = walk_forward_validation(y, **kwargs)+ else:+ result = walk_forward_validation(y, **kwargs)++ # Yield splits+ if 'data' in result:+ for entity_result in result['data']:+ for split in entity_result.get('splits', []):+ train_df = pl.DataFrame(split['train'])+ test_df = pl.DataFrame(split['test'])+ yield train_df, test_df+++def main():+ """Test advanced CV methods."""+ print("Testing Advanced Cross-Validation Module")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 12, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.1 * i + np.random.randn() * 5 for i in range(n)]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Test blocked CV+ blocked_result = blocked_time_series_cv(df, n_splits=5, test_size=10, gap=5)+ print(f"Blocked CV: {blocked_result['data'][0]['n_splits']} splits")++ # Test purged K-fold+ purged_result = purged_kfold_cv(df, n_splits=5, embargo_pct=0.02)+ print(f"Purged K-Fold: {purged_result['data'][0]['n_splits']} splits")++ # Test walk-forward+ wf_result = walk_forward_validation(df, initial_train_size=100, test_size=10, step_size=10)+ print(f"Walk-Forward: {wf_result['data'][0]['n_splits']} splits")++ # Test combinatorial purged+ cpcv_result = combinatorial_purged_cv(df, n_test_splits=2, n_groups=5)+ print(f"CPCV: {cpcv_result['data'][0]['n_combinations']} combinations")++ # Test nested CV+ nested_result = nested_cv(df, outer_splits=3, inner_splits=3)+ print(f"Nested CV: {nested_result['data'][0]['n_outer_splits']} outer splits")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_models.pynew file mode 100644index 000000000..c0f74ab1e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/advanced_models.py@@ -0,0 +1,704 @@+"""+Advanced Forecasting Models for Functime Wrapper+=================================================++Provides additional forecasting models beyond the base functime models:+- Naive/Seasonal Naive (baseline models)+- XGBoost forecasting+- Theta Method+- Croston's method for intermittent demand+- Simple Exponential Smoothing++Uses sklearn/numpy implementations for compatibility.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')++# Try importing XGBoost+try:+ import xgboost as xgb+ XGBOOST_AVAILABLE = True+except ImportError:+ XGBOOST_AVAILABLE = False++# Try importing CatBoost+try:+ import catboost as cb+ CATBOOST_AVAILABLE = True+except ImportError:+ CATBOOST_AVAILABLE = False+++# ============================================================================+# NAIVE MODELS+# ============================================================================++def forecast_naive(+ y_train: pl.DataFrame,+ fh: int,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Naive forecast - uses last value as forecast for all horizons.+ Good baseline model for comparison.+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ last_value = entity_data['value'].to_list()[-1]+ last_time = entity_data['time'].to_list()[-1]++ # Generate future times+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = last_time + (delta * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(last_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'Naive',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh+ }+++def forecast_seasonal_naive(+ y_train: pl.DataFrame,+ fh: int,+ sp: int = 7, # Seasonal period (7 for weekly, 12 for monthly, etc.)+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Seasonal Naive forecast - uses value from same season in previous period.+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_list()+ times = entity_data['time'].to_list()+ last_time = times[-1]++ # Generate future times+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = last_time + (delta * i)+ # Get value from sp periods ago (with wraparound)+ seasonal_idx = len(values) - sp + ((i - 1) % sp)+ if seasonal_idx < 0:+ seasonal_idx = len(values) - 1 # Fallback to last value+ forecast_value = values[seasonal_idx]++ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'SeasonalNaive',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'seasonal_period': sp+ }+++def forecast_drift(+ y_train: pl.DataFrame,+ fh: int,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Drift method - linear extrapolation from first to last value.+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_list()+ times = entity_data['time'].to_list()++ first_value = values[0]+ last_value = values[-1]+ n = len(values)++ # Calculate drift+ drift = (last_value - first_value) / (n - 1) if n > 1 else 0++ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ forecast_value = last_value + (drift * i)++ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'Drift',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh+ }+++# ============================================================================+# EXPONENTIAL SMOOTHING+# ============================================================================++def forecast_ses(+ y_train: pl.DataFrame,+ fh: int,+ alpha: float = 0.3,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Simple Exponential Smoothing (SES).+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()++ # Fit SES+ level = values[0]+ for v in values[1:]:+ level = alpha * v + (1 - alpha) * level++ # Forecast is constant (the final level)+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(level)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'SES',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'alpha': alpha+ }+++def forecast_holt(+ y_train: pl.DataFrame,+ fh: int,+ alpha: float = 0.3,+ beta: float = 0.1,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Holt's Linear Trend Method (Double Exponential Smoothing).+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()++ # Initialize+ level = values[0]+ trend = values[1] - values[0] if len(values) > 1 else 0++ # Fit+ for v in values[1:]:+ prev_level = level+ level = alpha * v + (1 - alpha) * (level + trend)+ trend = beta * (level - prev_level) + (1 - beta) * trend++ # Forecast+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ forecast_value = level + (trend * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'Holt',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'alpha': alpha,+ 'beta': beta+ }+++# ============================================================================+# THETA METHOD+# ============================================================================++def forecast_theta(+ y_train: pl.DataFrame,+ fh: int,+ theta: float = 2.0,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Theta Method - decomposes series and applies SES to theta-line.+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()+ n = len(values)++ # Decompose into trend and residual+ # Theta line: z_t = theta * y_t - (theta - 1) * trend_t+ x = np.arange(n)+ slope, intercept = np.polyfit(x, values, 1)+ trend = intercept + slope * x++ # Apply theta transformation+ theta_line = theta * values - (theta - 1) * trend++ # Apply SES to theta line+ alpha = 0.3+ level = theta_line[0]+ for v in theta_line[1:]:+ level = alpha * v + (1 - alpha) * level++ # Forecast+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ future_x = n + i - 1+ future_trend = intercept + slope * future_x+ # Invert theta transformation+ forecast_value = (level + (theta - 1) * future_trend) / theta+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'Theta',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'theta': theta+ }+++# ============================================================================+# CROSTON'S METHOD (Intermittent Demand)+# ============================================================================++def forecast_croston(+ y_train: pl.DataFrame,+ fh: int,+ alpha: float = 0.3,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Croston's method for intermittent demand forecasting.+ Separates demand size from demand occurrence.+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()++ # Separate demand and intervals+ demand_times = []+ demand_sizes = []+ last_demand_idx = -1++ for i, v in enumerate(values):+ if v > 0:+ demand_sizes.append(v)+ if last_demand_idx >= 0:+ demand_times.append(i - last_demand_idx)+ else:+ demand_times.append(1)+ last_demand_idx = i++ if len(demand_sizes) == 0:+ # No demand - forecast zero+ forecast_value = 0.0+ elif len(demand_sizes) == 1:+ # Single demand - use that value+ forecast_value = demand_sizes[0]+ else:+ # Smooth demand sizes+ z = demand_sizes[0]+ for d in demand_sizes[1:]:+ z = alpha * d + (1 - alpha) * z++ # Smooth intervals+ p = demand_times[0]+ for t in demand_times[1:]:+ p = alpha * t + (1 - alpha) * p++ # Forecast = demand / interval+ forecast_value = z / p if p > 0 else z++ # Generate forecasts+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'Croston',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'alpha': alpha+ }+++# ============================================================================+# XGBOOST FORECASTING+# ============================================================================++def forecast_xgboost(+ y_train: pl.DataFrame,+ fh: int,+ lags: int = 10,+ freq: str = '1d',+ **xgb_params+) -> Dict[str, Any]:+ """+ XGBoost forecaster with lag features.+ """+ if not XGBOOST_AVAILABLE:+ return {+ 'success': False,+ 'error': 'XGBoost not installed. Run: pip install xgboost'+ }++ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ default_params = {+ 'n_estimators': 100,+ 'max_depth': 5,+ 'learning_rate': 0.1,+ 'objective': 'reg:squarederror'+ }+ default_params.update(xgb_params)++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()++ # Create lag features+ X, y = _create_lag_features(values, lags)++ if len(X) < 10:+ # Not enough data, fall back to naive+ forecast_value = values[-1]+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })+ continue++ # Fit XGBoost+ model = xgb.XGBRegressor(**default_params)+ model.fit(X, y)++ # Recursive forecasting+ last_lags = values[-lags:].tolist()+ delta = _get_time_delta(freq)++ for i in range(1, fh + 1):+ X_pred = np.array([last_lags[-lags:]]).reshape(1, -1)+ pred = float(model.predict(X_pred)[0])+ future_time = times[-1] + (delta * i)++ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': pred+ })++ # Update lags for next prediction+ last_lags.append(pred)++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'XGBoost',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'lags': lags,+ 'params': default_params+ }+++def forecast_catboost(+ y_train: pl.DataFrame,+ fh: int,+ lags: int = 10,+ freq: str = '1d',+ **cb_params+) -> Dict[str, Any]:+ """+ CatBoost forecaster with lag features.+ """+ if not CATBOOST_AVAILABLE:+ return {+ 'success': False,+ 'error': 'CatBoost not installed. Run: pip install catboost'+ }++ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ default_params = {+ 'iterations': 100,+ 'depth': 5,+ 'learning_rate': 0.1,+ 'loss_function': 'RMSE',+ 'verbose': False+ }+ default_params.update(cb_params)++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = np.array(entity_data['value'].to_list())+ times = entity_data['time'].to_list()++ # Create lag features+ X, y = _create_lag_features(values, lags)++ if len(X) < 10:+ forecast_value = values[-1]+ delta = _get_time_delta(freq)+ for i in range(1, fh + 1):+ future_time = times[-1] + (delta * i)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': float(forecast_value)+ })+ continue++ # Fit CatBoost+ model = cb.CatBoostRegressor(**default_params)+ model.fit(X, y)++ # Recursive forecasting+ last_lags = values[-lags:].tolist()+ delta = _get_time_delta(freq)++ for i in range(1, fh + 1):+ X_pred = np.array([last_lags[-lags:]]).reshape(1, -1)+ pred = float(model.predict(X_pred)[0])+ future_time = times[-1] + (delta * i)++ result_rows.append({+ 'entity_id': entity_id,+ 'time': future_time,+ 'value': pred+ })++ last_lags.append(pred)++ forecast = pl.DataFrame(result_rows)++ return {+ 'model_type': 'CatBoost',+ 'forecast': forecast.to_dicts(),+ 'shape': forecast.shape,+ 'horizon': fh,+ 'lags': lags+ }+++# ============================================================================+# HELPER FUNCTIONS+# ============================================================================++def _get_time_delta(freq: str) -> timedelta:+ """Convert frequency string to timedelta."""+ freq_map = {+ '1d': timedelta(days=1),+ '1w': timedelta(weeks=1),+ '1h': timedelta(hours=1),+ '30m': timedelta(minutes=30),+ '15m': timedelta(minutes=15),+ '1m': timedelta(minutes=1),+ '1mo': timedelta(days=30),+ '1q': timedelta(days=91),+ '1y': timedelta(days=365),+ }+ return freq_map.get(freq, timedelta(days=1))+++def _create_lag_features(values: np.ndarray, lags: int) -> Tuple[np.ndarray, np.ndarray]:+ """Create lag features for supervised learning."""+ n = len(values)+ X = []+ y = []++ for i in range(lags, n):+ X.append(values[i-lags:i])+ y.append(values[i])++ return np.array(X), np.array(y)+++def get_available_models() -> List[Dict[str, str]]:+ """Return list of available advanced models."""+ models = [+ {'id': 'naive', 'name': 'Naive', 'description': 'Last value forecast (baseline)'},+ {'id': 'seasonal_naive', 'name': 'Seasonal Naive', 'description': 'Seasonal last value'},+ {'id': 'drift', 'name': 'Drift', 'description': 'Linear extrapolation'},+ {'id': 'ses', 'name': 'SES', 'description': 'Simple Exponential Smoothing'},+ {'id': 'holt', 'name': 'Holt', 'description': 'Double Exponential Smoothing'},+ {'id': 'theta', 'name': 'Theta', 'description': 'Theta method'},+ {'id': 'croston', 'name': 'Croston', 'description': 'Intermittent demand'},+ ]++ if XGBOOST_AVAILABLE:+ models.append({'id': 'xgboost', 'name': 'XGBoost', 'description': 'Gradient boosting'})++ if CATBOOST_AVAILABLE:+ models.append({'id': 'catboost', 'name': 'CatBoost', 'description': 'Categorical boosting'})++ return models+++# ============================================================================+# ALIASES FOR COMPATIBILITY+# ============================================================================++# These aliases match the import names expected by functime_service.py+naive_forecast = forecast_naive+seasonal_naive_forecast = forecast_seasonal_naive+drift_forecast = forecast_drift+ses_forecast = forecast_ses+holt_forecast = forecast_holt+theta_forecast = forecast_theta+croston_forecast = forecast_croston+xgboost_forecast = forecast_xgboost+catboost_forecast = forecast_catboost+++def main():+ """Test advanced models."""+ print("Testing Advanced Forecasting Models")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 3, 31),+ interval='1d',+ eager=True+ ).to_list()++ # Generate synthetic data with trend and seasonality+ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.5 * i + 10 * np.sin(2 * np.pi * i / 7) + np.random.randn() * 3 for i in range(n)]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ fh = 7++ # Test Naive+ naive_result = forecast_naive(df, fh=fh)+ print(f"Naive: {len(naive_result['forecast'])} predictions")++ # Test Seasonal Naive+ snaive_result = forecast_seasonal_naive(df, fh=fh, sp=7)+ print(f"Seasonal Naive: {len(snaive_result['forecast'])} predictions")++ # Test SES+ ses_result = forecast_ses(df, fh=fh, alpha=0.3)+ print(f"SES: {len(ses_result['forecast'])} predictions")++ # Test Holt+ holt_result = forecast_holt(df, fh=fh, alpha=0.3, beta=0.1)+ print(f"Holt: {len(holt_result['forecast'])} predictions")++ # Test Theta+ theta_result = forecast_theta(df, fh=fh, theta=2.0)+ print(f"Theta: {len(theta_result['forecast'])} predictions")++ # Test Croston (with some zeros)+ df_intermittent = df.with_columns([+ pl.when(pl.col('value') < 105).then(0).otherwise(pl.col('value')).alias('value')+ ])+ croston_result = forecast_croston(df_intermittent, fh=fh)+ print(f"Croston: {len(croston_result['forecast'])} predictions")++ # Test XGBoost if available+ if XGBOOST_AVAILABLE:+ xgb_result = forecast_xgboost(df, fh=fh, lags=7)+ print(f"XGBoost: {len(xgb_result['forecast'])} predictions")++ print("\nAvailable models:", [m['id'] for m in get_available_models()])+ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/anomaly_detection.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/anomaly_detection.pynew file mode 100644index 000000000..6a7875243--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/anomaly_detection.py@@ -0,0 +1,680 @@+"""+Time Series Anomaly Detection Module+=====================================++Provides anomaly detection for time series data:+- Statistical methods (Z-score, IQR, Grubbs)+- Isolation Forest+- Residual-based detection+- Seasonal decomposition anomalies+- Change point detection++Designed for financial time series and forecasting applications.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple+from datetime import datetime, timedelta+from scipy import stats as scipy_stats+import warnings++warnings.filterwarnings('ignore')++# Try importing sklearn+try:+ from sklearn.ensemble import IsolationForest+ from sklearn.neighbors import LocalOutlierFactor+ from sklearn.preprocessing import StandardScaler+ SKLEARN_AVAILABLE = True+except ImportError:+ SKLEARN_AVAILABLE = False+++# ============================================================================+# STATISTICAL ANOMALY DETECTION+# ============================================================================++def detect_zscore(+ y: pl.DataFrame,+ threshold: float = 3.0,+ window: Optional[int] = None+) -> Dict[str, Any]:+ """+ Detect anomalies using Z-score (standard deviations from mean).++ Args:+ y: Panel data with entity_id, time, value+ threshold: Z-score threshold for anomaly (default: 3.0)+ window: Optional rolling window size for local Z-scores+ """+ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if window is not None and window < len(values):+ # Rolling Z-score+ zscores = _rolling_zscore(values, window)+ else:+ # Global Z-score+ mean = np.mean(values)+ std = np.std(values)+ if std == 0:+ zscores = np.zeros_like(values)+ else:+ zscores = (values - mean) / std++ for i, (t, v, z) in enumerate(zip(times, values, zscores)):+ is_anomaly = bool(abs(z) > threshold)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'zscore': float(z),+ 'is_anomaly': is_anomaly,+ 'anomaly_type': 'high' if z > threshold else ('low' if z < -threshold else None)+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'zscore',+ 'threshold': threshold,+ 'window': window,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++def detect_iqr(+ y: pl.DataFrame,+ k: float = 1.5,+ window: Optional[int] = None+) -> Dict[str, Any]:+ """+ Detect anomalies using Interquartile Range (IQR) method.++ Args:+ y: Panel data+ k: IQR multiplier (default: 1.5 for outliers, 3.0 for extreme)+ window: Optional rolling window+ """+ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if window is not None and window < len(values):+ # Rolling IQR+ for i in range(len(values)):+ start_idx = max(0, i - window)+ window_values = values[start_idx:i+1]+ q1, q3 = np.percentile(window_values, [25, 75])+ iqr = q3 - q1+ lower = q1 - k * iqr+ upper = q3 + k * iqr+ v = values[i]+ is_anomaly = bool(v < lower or v > upper)++ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(v),+ 'lower_bound': float(lower),+ 'upper_bound': float(upper),+ 'is_anomaly': is_anomaly,+ 'anomaly_type': 'high' if v > upper else ('low' if v < lower else None)+ })+ if is_anomaly:+ summary['n_anomalies'] += 1+ else:+ # Global IQR+ q1, q3 = np.percentile(values, [25, 75])+ iqr = q3 - q1+ lower = q1 - k * iqr+ upper = q3 + k * iqr++ for i, (t, v) in enumerate(zip(times, values)):+ is_anomaly = bool(v < lower or v > upper)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'lower_bound': float(lower),+ 'upper_bound': float(upper),+ 'is_anomaly': is_anomaly,+ 'anomaly_type': 'high' if v > upper else ('low' if v < lower else None)+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'iqr',+ 'k': k,+ 'window': window,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++def detect_grubbs(+ y: pl.DataFrame,+ alpha: float = 0.05+) -> Dict[str, Any]:+ """+ Grubbs' test for outliers (one outlier at a time).++ Args:+ y: Panel data+ alpha: Significance level+ """+ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()+ n = len(values)++ if n < 3:+ for t, v in zip(times, values):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'g_stat': None,+ 'critical_value': None,+ 'is_anomaly': False+ })+ continue++ # Calculate Grubbs statistic for each point+ mean = np.mean(values)+ std = np.std(values, ddof=1)++ # Critical value+ t_crit = scipy_stats.t.ppf(1 - alpha / (2 * n), n - 2)+ g_crit = ((n - 1) / np.sqrt(n)) * np.sqrt(t_crit ** 2 / (n - 2 + t_crit ** 2))++ for i, (t, v) in enumerate(zip(times, values)):+ if std == 0:+ g_stat = 0+ else:+ g_stat = abs(v - mean) / std+ is_anomaly = bool(g_stat > g_crit)++ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'g_stat': float(g_stat),+ 'critical_value': float(g_crit),+ 'is_anomaly': is_anomaly+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'grubbs',+ 'alpha': alpha,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++# ============================================================================+# MACHINE LEARNING ANOMALY DETECTION+# ============================================================================++def detect_isolation_forest(+ y: pl.DataFrame,+ contamination: float = 0.05,+ n_estimators: int = 100,+ use_features: bool = True,+ lags: int = 5+) -> Dict[str, Any]:+ """+ Detect anomalies using Isolation Forest.++ Args:+ y: Panel data+ contamination: Expected proportion of outliers+ n_estimators: Number of trees+ use_features: Whether to create lag features+ lags: Number of lag features to create+ """+ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available'}++ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ # Create features+ if use_features and len(values) > lags:+ X = _create_feature_matrix(values, lags)+ start_idx = lags+ else:+ X = values.reshape(-1, 1)+ start_idx = 0++ # Fit Isolation Forest+ iso = IsolationForest(+ n_estimators=n_estimators,+ contamination=contamination,+ random_state=42+ )+ predictions = iso.fit_predict(X)+ scores = iso.decision_function(X)++ # Map back to original indices+ for i in range(len(times)):+ if i < start_idx:+ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(values[i]),+ 'anomaly_score': None,+ 'is_anomaly': False+ })+ else:+ feat_idx = i - start_idx+ is_anomaly = bool(predictions[feat_idx] == -1)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(values[i]),+ 'anomaly_score': float(scores[feat_idx]),+ 'is_anomaly': is_anomaly+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'isolation_forest',+ 'contamination': contamination,+ 'n_estimators': n_estimators,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++def detect_lof(+ y: pl.DataFrame,+ n_neighbors: int = 20,+ contamination: float = 0.05,+ lags: int = 5+) -> Dict[str, Any]:+ """+ Detect anomalies using Local Outlier Factor (LOF).+ """+ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available'}++ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if len(values) < n_neighbors + lags:+ for t, v in zip(times, values):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'lof_score': None,+ 'is_anomaly': False+ })+ continue++ # Create features+ X = _create_feature_matrix(values, lags)+ start_idx = lags++ # Fit LOF+ lof = LocalOutlierFactor(n_neighbors=n_neighbors, contamination=contamination)+ predictions = lof.fit_predict(X)+ scores = -lof.negative_outlier_factor_ # Convert to positive (higher = more anomalous)++ for i in range(len(times)):+ if i < start_idx:+ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(values[i]),+ 'lof_score': None,+ 'is_anomaly': False+ })+ else:+ feat_idx = i - start_idx+ is_anomaly = bool(predictions[feat_idx] == -1)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(values[i]),+ 'lof_score': float(scores[feat_idx]),+ 'is_anomaly': is_anomaly+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'lof',+ 'n_neighbors': n_neighbors,+ 'contamination': contamination,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++# ============================================================================+# RESIDUAL-BASED ANOMALY DETECTION+# ============================================================================++def detect_residual_anomalies(+ y: pl.DataFrame,+ forecast: pl.DataFrame,+ threshold: float = 3.0+) -> Dict[str, Any]:+ """+ Detect anomalies based on forecast residuals.++ Args:+ y: Actual values (panel data)+ forecast: Forecast values (panel data)+ threshold: Z-score threshold for residuals+ """+ result_rows = []+ summary = {'n_anomalies': 0, 'anomaly_rate': 0.0}++ # Join actual and forecast+ actual = y.select(['entity_id', 'time', 'value']).rename({'value': 'actual'})+ pred = forecast.select(['entity_id', 'time', 'value']).rename({'value': 'predicted'})+ joined = actual.join(pred, on=['entity_id', 'time'], how='inner')++ if len(joined) == 0:+ return {'success': False, 'error': 'No matching data between actual and forecast'}++ # Calculate residuals+ joined = joined.with_columns([+ (pl.col('actual') - pl.col('predicted')).alias('residual')+ ])++ entities = joined['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = joined.filter(pl.col('entity_id') == entity_id).sort('time')+ residuals = entity_data['residual'].to_numpy()++ # Calculate Z-scores of residuals+ mean_res = np.mean(residuals)+ std_res = np.std(residuals)++ for row in entity_data.iter_rows(named=True):+ if std_res == 0:+ z = 0+ else:+ z = (row['residual'] - mean_res) / std_res++ is_anomaly = bool(abs(z) > threshold)++ result_rows.append({+ 'entity_id': row['entity_id'],+ 'time': row['time'],+ 'actual': float(row['actual']),+ 'predicted': float(row['predicted']),+ 'residual': float(row['residual']),+ 'residual_zscore': float(z),+ 'is_anomaly': is_anomaly+ })+ if is_anomaly:+ summary['n_anomalies'] += 1++ result = pl.DataFrame(result_rows)+ summary['anomaly_rate'] = summary['n_anomalies'] / len(result) if len(result) > 0 else 0++ return {+ 'success': True,+ 'method': 'residual',+ 'threshold': threshold,+ 'data': result.to_dicts(),+ 'anomalies': result.filter(pl.col('is_anomaly')).to_dicts(),+ 'summary': summary+ }+++# ============================================================================+# CHANGE POINT DETECTION+# ============================================================================++def detect_change_points(+ y: pl.DataFrame,+ method: str = 'cusum',+ threshold: float = 5.0+) -> Dict[str, Any]:+ """+ Detect change points in time series.++ Args:+ y: Panel data+ method: 'cusum' or 'pelt'+ threshold: Threshold for detection+ """+ result_rows = []+ change_points = []++ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if method == 'cusum':+ # CUSUM change point detection+ cps = _cusum_detection(values, threshold)+ else:+ cps = _cusum_detection(values, threshold) # Default to CUSUM++ for i, (t, v) in enumerate(zip(times, values)):+ is_change_point = i in cps+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'value': float(v),+ 'is_change_point': is_change_point+ })+ if is_change_point:+ change_points.append({+ 'entity_id': entity_id,+ 'time': t,+ 'index': i+ })++ result = pl.DataFrame(result_rows)++ return {+ 'success': True,+ 'method': f'change_point_{method}',+ 'threshold': threshold,+ 'data': result.to_dicts(),+ 'change_points': change_points,+ 'n_change_points': len(change_points)+ }+++# ============================================================================+# HELPER FUNCTIONS+# ============================================================================++def _rolling_zscore(values: np.ndarray, window: int) -> np.ndarray:+ """Calculate rolling Z-score."""+ n = len(values)+ zscores = np.zeros(n)++ for i in range(n):+ start_idx = max(0, i - window + 1)+ window_values = values[start_idx:i+1]+ mean = np.mean(window_values)+ std = np.std(window_values)+ if std == 0:+ zscores[i] = 0+ else:+ zscores[i] = (values[i] - mean) / std++ return zscores+++def _create_feature_matrix(values: np.ndarray, lags: int) -> np.ndarray:+ """Create feature matrix with lag features."""+ n = len(values)+ X = []++ for i in range(lags, n):+ features = list(values[i-lags:i]) + [values[i]]+ X.append(features)++ return np.array(X)+++def _cusum_detection(values: np.ndarray, threshold: float) -> List[int]:+ """CUSUM change point detection."""+ n = len(values)+ if n < 3:+ return []++ mean = np.mean(values)+ std = np.std(values)+ if std == 0:+ std = 1++ # Standardize+ z = (values - mean) / std++ # Calculate cumulative sum+ s_pos = np.zeros(n)+ s_neg = np.zeros(n)++ for i in range(1, n):+ s_pos[i] = max(0, s_pos[i-1] + z[i] - 0.5)+ s_neg[i] = min(0, s_neg[i-1] + z[i] + 0.5)++ # Detect change points+ change_points = []+ for i in range(1, n):+ if s_pos[i] > threshold or s_neg[i] < -threshold:+ change_points.append(i)+ # Reset+ s_pos[i] = 0+ s_neg[i] = 0++ return change_points+++def main():+ """Test anomaly detection methods."""+ print("Testing Anomaly Detection Module")+ print("=" * 50)++ # Create sample data with anomalies+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 3, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.5 * i + np.random.randn() * 3 for i in range(n)]++ # Inject anomalies+ values[10] = 150 # Spike+ values[30] = 50 # Drop+ values[50] = 180 # Large spike++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Test Z-score+ zscore_result = detect_zscore(df, threshold=3.0)+ print(f"Z-score: {zscore_result['summary']['n_anomalies']} anomalies detected")++ # Test IQR+ iqr_result = detect_iqr(df, k=1.5)+ print(f"IQR: {iqr_result['summary']['n_anomalies']} anomalies detected")++ # Test Grubbs+ grubbs_result = detect_grubbs(df, alpha=0.05)+ print(f"Grubbs: {grubbs_result['summary']['n_anomalies']} anomalies detected")++ # Test Isolation Forest+ if SKLEARN_AVAILABLE:+ iso_result = detect_isolation_forest(df, contamination=0.05)+ print(f"Isolation Forest: {iso_result['summary']['n_anomalies']} anomalies detected")++ lof_result = detect_lof(df, n_neighbors=10, contamination=0.05)+ print(f"LOF: {lof_result['summary']['n_anomalies']} anomalies detected")++ # Test Change Point Detection+ cp_result = detect_change_points(df, method='cusum', threshold=5.0)+ print(f"Change Points: {cp_result['n_change_points']} detected")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/backtesting.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/backtesting.pynew file mode 100644index 000000000..831bf74e4--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/backtesting.py@@ -0,0 +1,507 @@+"""+Backtesting Framework Module+============================++Provides comprehensive backtesting for time series forecasting:+- Walk-forward backtesting+- Rolling origin evaluation+- Multi-horizon accuracy tracking+- Model comparison framework+- Performance attribution++Essential for validating forecasting models in production.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple, Callable+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')+++# ============================================================================+# WALK-FORWARD BACKTESTING+# ============================================================================++def walk_forward_backtest(+ y: pl.DataFrame,+ forecaster: Callable,+ initial_train_size: int = 100,+ test_size: int = 1,+ step_size: int = 1,+ horizons: Optional[List[int]] = None,+ freq: str = '1d',+ retrain: bool = True+) -> Dict[str, Any]:+ """+ Walk-forward backtesting with optional retraining.++ Simulates real-world forecasting by generating forecasts at each+ origin and comparing with actual values.++ Args:+ y: Panel data+ forecaster: Forecasting function (y_train, fh, freq) -> result+ initial_train_size: Initial training window+ test_size: Number of periods to forecast+ step_size: Step between forecast origins+ horizons: Specific horizons to track (default: all up to test_size)+ freq: Data frequency+ retrain: Whether to retrain at each origin+ """+ if horizons is None:+ horizons = list(range(1, test_size + 1))++ results = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ if n < initial_train_size + max(horizons):+ continue++ entity_results = []+ forecasts_by_horizon = {h: [] for h in horizons}+ actuals_by_horizon = {h: [] for h in horizons}++ origin = initial_train_size++ while origin + max(horizons) <= n:+ train_data = entity_data[:origin]+ actual_data = entity_data[origin:origin + max(horizons)]+ actual_values = actual_data['value'].to_list()++ try:+ fc_result = forecaster(train_data, fh=max(horizons), freq=freq)++ if 'forecast' in fc_result:+ fc_values = [f['value'] for f in fc_result['forecast']]++ for h in horizons:+ if h - 1 < len(fc_values) and h - 1 < len(actual_values):+ forecasts_by_horizon[h].append(fc_values[h - 1])+ actuals_by_horizon[h].append(actual_values[h - 1])++ entity_results.append({+ 'origin': origin,+ 'horizon': h,+ 'forecast': float(fc_values[h - 1]),+ 'actual': float(actual_values[h - 1]),+ 'error': float(fc_values[h - 1] - actual_values[h - 1]),+ 'abs_error': float(abs(fc_values[h - 1] - actual_values[h - 1]))+ })++ except Exception as e:+ pass++ origin += step_size++ # Calculate metrics by horizon+ metrics_by_horizon = {}+ for h in horizons:+ if len(forecasts_by_horizon[h]) > 0:+ fc = np.array(forecasts_by_horizon[h])+ act = np.array(actuals_by_horizon[h])+ errors = fc - act++ metrics_by_horizon[h] = {+ 'mae': float(np.mean(np.abs(errors))),+ 'rmse': float(np.sqrt(np.mean(errors ** 2))),+ 'mape': float(np.mean(np.abs(errors / (act + 1e-10))) * 100),+ 'bias': float(np.mean(errors)),+ 'n_forecasts': len(fc)+ }++ results.append({+ 'entity_id': entity_id,+ 'n_origins': len(set([r['origin'] for r in entity_results])),+ 'forecasts': entity_results,+ 'metrics_by_horizon': metrics_by_horizon+ })++ return {+ 'success': True,+ 'method': 'walk_forward_backtest',+ 'initial_train_size': initial_train_size,+ 'test_size': test_size,+ 'step_size': step_size,+ 'horizons': horizons,+ 'results': results+ }+++# ============================================================================+# MODEL COMPARISON BACKTEST+# ============================================================================++def compare_models_backtest(+ y: pl.DataFrame,+ forecasters: Dict[str, Callable],+ initial_train_size: int = 100,+ test_size: int = 1,+ step_size: int = 5,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Compare multiple forecasting models via backtesting.++ Args:+ y: Panel data+ forecasters: Dict of {model_name: forecaster_function}+ initial_train_size: Initial training window+ test_size: Forecast horizon+ step_size: Step between origins+ freq: Data frequency+ """+ results = {}+ comparison = []++ for model_name, forecaster in forecasters.items():+ bt_result = walk_forward_backtest(+ y=y,+ forecaster=forecaster,+ initial_train_size=initial_train_size,+ test_size=test_size,+ step_size=step_size,+ freq=freq+ )++ results[model_name] = bt_result++ # Aggregate metrics+ if bt_result['results']:+ all_metrics = []+ for entity_result in bt_result['results']:+ for h, metrics in entity_result['metrics_by_horizon'].items():+ all_metrics.append(metrics)++ if all_metrics:+ avg_mae = np.mean([m['mae'] for m in all_metrics])+ avg_rmse = np.mean([m['rmse'] for m in all_metrics])+ avg_mape = np.mean([m['mape'] for m in all_metrics])++ comparison.append({+ 'model': model_name,+ 'mae': float(avg_mae),+ 'rmse': float(avg_rmse),+ 'mape': float(avg_mape),+ 'n_forecasts': sum([m['n_forecasts'] for m in all_metrics])+ })++ # Rank models+ comparison = sorted(comparison, key=lambda x: x['mae'])+ for i, c in enumerate(comparison):+ c['rank'] = i + 1++ return {+ 'success': True,+ 'method': 'model_comparison',+ 'comparison': comparison,+ 'best_model': comparison[0]['model'] if comparison else None,+ 'detailed_results': results+ }+++# ============================================================================+# ROLLING ORIGIN EVALUATION+# ============================================================================++def rolling_origin_evaluation(+ y: pl.DataFrame,+ forecaster: Callable,+ min_train_size: int = 50,+ max_train_size: Optional[int] = None,+ test_size: int = 1,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Rolling origin evaluation with varying training sizes.++ Analyzes how forecast accuracy changes with training set size.++ Args:+ y: Panel data+ forecaster: Forecasting function+ min_train_size: Minimum training window+ max_train_size: Maximum training window (None = use all available)+ test_size: Test set size+ freq: Data frequency+ """+ results = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ n = len(entity_data)++ if n < min_train_size + test_size:+ continue++ entity_results = []+ train_size_metrics = {}++ train_size = min_train_size+ actual_max = max_train_size or (n - test_size)++ while train_size <= min(actual_max, n - test_size):+ # Use most recent data for training+ train_end = n - test_size+ train_start = max(0, train_end - train_size)++ train_data = entity_data[train_start:train_end]+ test_data = entity_data[train_end:train_end + test_size]+ actual_values = test_data['value'].to_list()++ try:+ fc_result = forecaster(train_data, fh=test_size, freq=freq)++ if 'forecast' in fc_result:+ fc_values = [f['value'] for f in fc_result['forecast']]++ errors = [fc_values[i] - actual_values[i]+ for i in range(min(len(fc_values), len(actual_values)))]++ mae = np.mean(np.abs(errors))+ rmse = np.sqrt(np.mean(np.array(errors) ** 2))++ train_size_metrics[train_size] = {+ 'mae': float(mae),+ 'rmse': float(rmse),+ 'train_size': train_size+ }++ except Exception:+ pass++ # Increase train size+ train_size = int(train_size * 1.2) + 1++ results.append({+ 'entity_id': entity_id,+ 'metrics_by_train_size': train_size_metrics,+ 'optimal_train_size': min(train_size_metrics.items(),+ key=lambda x: x[1]['mae'])[0] if train_size_metrics else None+ })++ return {+ 'success': True,+ 'method': 'rolling_origin_evaluation',+ 'min_train_size': min_train_size,+ 'max_train_size': max_train_size,+ 'results': results+ }+++# ============================================================================+# PERFORMANCE ATTRIBUTION+# ============================================================================++def performance_attribution(+ backtest_results: Dict[str, Any],+ segments: Optional[Dict[str, Callable]] = None+) -> Dict[str, Any]:+ """+ Attribute forecast performance to different segments/regimes.++ Args:+ backtest_results: Results from walk_forward_backtest+ segments: Dict of {segment_name: condition_function}+ """+ if segments is None:+ # Default segments based on volatility and trend+ segments = {+ 'high_volatility': lambda data: np.std(data) > np.median(np.std(data)),+ 'low_volatility': lambda data: np.std(data) <= np.median(np.std(data)),+ 'uptrend': lambda data: data[-1] > data[0] if len(data) > 1 else False,+ 'downtrend': lambda data: data[-1] < data[0] if len(data) > 1 else False+ }++ attribution = {}++ for entity_result in backtest_results.get('results', []):+ entity_id = entity_result['entity_id']+ forecasts = entity_result.get('forecasts', [])++ if not forecasts:+ continue++ # Simple attribution based on error magnitude+ errors = [f['abs_error'] for f in forecasts]+ horizons = [f['horizon'] for f in forecasts]++ # By horizon+ horizon_attribution = {}+ for h in set(horizons):+ h_errors = [e for e, ho in zip(errors, horizons) if ho == h]+ if h_errors:+ horizon_attribution[h] = {+ 'mean_error': float(np.mean(h_errors)),+ 'contribution_pct': float(sum(h_errors) / sum(errors) * 100) if sum(errors) > 0 else 0+ }++ # By error percentile+ percentile_attribution = {+ 'p25': float(np.percentile(errors, 25)),+ 'p50': float(np.percentile(errors, 50)),+ 'p75': float(np.percentile(errors, 75)),+ 'p90': float(np.percentile(errors, 90)),+ 'p95': float(np.percentile(errors, 95))+ }++ # Worst forecasts+ sorted_forecasts = sorted(forecasts, key=lambda x: x['abs_error'], reverse=True)+ worst_forecasts = sorted_forecasts[:5]++ attribution[entity_id] = {+ 'by_horizon': horizon_attribution,+ 'by_percentile': percentile_attribution,+ 'worst_forecasts': worst_forecasts,+ 'total_error': float(sum(errors)),+ 'n_forecasts': len(forecasts)+ }++ return {+ 'success': True,+ 'method': 'performance_attribution',+ 'attribution': attribution+ }+++# ============================================================================+# SUMMARY STATISTICS+# ============================================================================++def backtest_summary(+ backtest_results: Dict[str, Any]+) -> Dict[str, Any]:+ """+ Generate summary statistics from backtest results.+ """+ if not backtest_results.get('results'):+ return {'success': False, 'error': 'No results to summarize'}++ all_forecasts = []+ all_metrics = []++ for entity_result in backtest_results['results']:+ all_forecasts.extend(entity_result.get('forecasts', []))+ for h, m in entity_result.get('metrics_by_horizon', {}).items():+ m['horizon'] = h+ all_metrics.append(m)++ if not all_forecasts:+ return {'success': False, 'error': 'No forecasts found'}++ errors = [f['error'] for f in all_forecasts]+ abs_errors = [f['abs_error'] for f in all_forecasts]++ summary = {+ 'total_forecasts': len(all_forecasts),+ 'total_origins': len(set([f['origin'] for f in all_forecasts])),+ 'overall_metrics': {+ 'mae': float(np.mean(abs_errors)),+ 'rmse': float(np.sqrt(np.mean(np.array(errors) ** 2))),+ 'bias': float(np.mean(errors)),+ 'std_error': float(np.std(errors))+ },+ 'error_distribution': {+ 'min': float(np.min(abs_errors)),+ 'p25': float(np.percentile(abs_errors, 25)),+ 'median': float(np.median(abs_errors)),+ 'p75': float(np.percentile(abs_errors, 75)),+ 'p95': float(np.percentile(abs_errors, 95)),+ 'max': float(np.max(abs_errors))+ },+ 'by_horizon': {}+ }++ # Metrics by horizon+ for h in sorted(set([m['horizon'] for m in all_metrics])):+ h_metrics = [m for m in all_metrics if m['horizon'] == h]+ summary['by_horizon'][h] = {+ 'mae': float(np.mean([m['mae'] for m in h_metrics])),+ 'rmse': float(np.mean([m['rmse'] for m in h_metrics])),+ 'n_forecasts': sum([m['n_forecasts'] for m in h_metrics])+ }++ return {+ 'success': True,+ 'summary': summary+ }+++def main():+ """Test backtesting framework."""+ print("Testing Backtesting Framework Module")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 12, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.1 * i + np.random.randn() * 3 for i in range(n)]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Simple naive forecaster for testing+ def naive_forecaster(y_train, fh, freq='1d'):+ last_value = y_train['value'].to_list()[-1]+ last_time = y_train['time'].to_list()[-1]+ delta = timedelta(days=1)++ forecast = []+ for i in range(1, fh + 1):+ forecast.append({+ 'entity_id': y_train['entity_id'].to_list()[0],+ 'time': last_time + (delta * i),+ 'value': last_value+ })++ return {'forecast': forecast}++ # Test walk-forward backtest+ bt_result = walk_forward_backtest(+ df, naive_forecaster,+ initial_train_size=100,+ test_size=5,+ step_size=10+ )+ print(f"Walk-forward backtest: {bt_result['results'][0]['n_origins']} origins")++ # Test backtest summary+ summary = backtest_summary(bt_result)+ if summary['success']:+ print(f"Overall MAE: {summary['summary']['overall_metrics']['mae']:.4f}")++ # Test performance attribution+ attr_result = performance_attribution(bt_result)+ print(f"Performance attribution: {len(attr_result['attribution'])} entities")++ # Test rolling origin evaluation+ roe_result = rolling_origin_evaluation(+ df, naive_forecaster,+ min_train_size=50,+ max_train_size=200+ )+ if roe_result['results']:+ print(f"Optimal train size: {roe_result['results'][0]['optimal_train_size']}")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/confidence_intervals.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/confidence_intervals.pynew file mode 100644index 000000000..3a1434b05--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/confidence_intervals.py@@ -0,0 +1,581 @@+"""+Confidence Intervals and Prediction Intervals Module+====================================================++Provides uncertainty quantification for forecasts:+- Bootstrap confidence intervals+- Quantile regression intervals+- Residual-based prediction intervals+- Conformal prediction intervals+- Monte Carlo simulation intervals++Essential for risk management in financial forecasting.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple, Callable+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')++# Try importing sklearn+try:+ from sklearn.linear_model import QuantileRegressor+ SKLEARN_AVAILABLE = True+except ImportError:+ SKLEARN_AVAILABLE = False+++# ============================================================================+# BOOTSTRAP CONFIDENCE INTERVALS+# ============================================================================++def bootstrap_prediction_intervals(+ y_train: pl.DataFrame,+ forecaster: Callable,+ fh: int,+ n_bootstrap: int = 100,+ confidence_levels: List[float] = [0.80, 0.95],+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Generate prediction intervals using bootstrap resampling.++ Args:+ y_train: Training data (panel format)+ forecaster: Forecasting function that takes (y_train, fh, freq)+ fh: Forecast horizon+ n_bootstrap: Number of bootstrap samples+ confidence_levels: Confidence levels (e.g., [0.80, 0.95])+ freq: Data frequency+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()+ n = len(values)++ if n < 10:+ continue++ # Generate bootstrap forecasts+ bootstrap_forecasts = []++ for _ in range(n_bootstrap):+ # Resample with replacement+ indices = np.random.choice(n, size=n, replace=True)+ resampled = entity_data[indices.tolist()].sort('time')++ try:+ fc_result = forecaster(resampled, fh=fh, freq=freq)+ if 'forecast' in fc_result:+ fc_values = [f['value'] for f in fc_result['forecast']]+ fc_times = [f['time'] for f in fc_result['forecast']]+ bootstrap_forecasts.append(fc_values)+ except Exception:+ continue++ if len(bootstrap_forecasts) < 10:+ continue++ # Calculate point forecast (median)+ bootstrap_array = np.array(bootstrap_forecasts)+ point_forecast = np.median(bootstrap_array, axis=0)++ # Calculate intervals for each confidence level+ for h_idx in range(fh):+ row = {+ 'entity_id': entity_id,+ 'time': fc_times[h_idx],+ 'forecast': float(point_forecast[h_idx]),+ 'horizon': h_idx + 1+ }++ for conf in confidence_levels:+ alpha = 1 - conf+ lower_pct = alpha / 2 * 100+ upper_pct = (1 - alpha / 2) * 100++ lower = np.percentile(bootstrap_array[:, h_idx], lower_pct)+ upper = np.percentile(bootstrap_array[:, h_idx], upper_pct)++ row[f'lower_{int(conf*100)}'] = float(lower)+ row[f'upper_{int(conf*100)}'] = float(upper)++ result_rows.append(row)++ result = pl.DataFrame(result_rows) if result_rows else pl.DataFrame()++ return {+ 'success': True,+ 'method': 'bootstrap',+ 'n_bootstrap': n_bootstrap,+ 'confidence_levels': confidence_levels,+ 'data': result.to_dicts() if len(result) > 0 else [],+ 'shape': result.shape if len(result) > 0 else (0, 0)+ }+++# ============================================================================+# RESIDUAL-BASED PREDICTION INTERVALS+# ============================================================================++def residual_prediction_intervals(+ y_train: pl.DataFrame,+ forecast: pl.DataFrame,+ y_validation: Optional[pl.DataFrame] = None,+ confidence_levels: List[float] = [0.80, 0.95]+) -> Dict[str, Any]:+ """+ Generate prediction intervals based on historical residuals.++ If y_validation is provided, uses actual residuals from validation.+ Otherwise, uses in-sample residuals.++ Args:+ y_train: Training data+ forecast: Point forecasts+ y_validation: Optional validation actuals for residual calculation+ confidence_levels: Confidence levels+ """+ result_rows = []+ entities = forecast['entity_id'].unique().to_list()++ for entity_id in entities:+ fc_data = forecast.filter(pl.col('entity_id') == entity_id).sort('time')++ # Get residuals+ if y_validation is not None:+ val_data = y_validation.filter(pl.col('entity_id') == entity_id).sort('time')+ # Calculate residuals from validation+ residuals = _calculate_residuals(val_data, fc_data)+ else:+ # Use in-sample estimation (assume residuals from training)+ train_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = train_data['value'].to_numpy()+ # Estimate residuals as deviations from rolling mean+ window = min(10, len(values) // 2)+ if window > 1:+ rolling_mean = np.convolve(values, np.ones(window)/window, mode='valid')+ residuals = values[window-1:] - rolling_mean+ else:+ residuals = values - np.mean(values)++ if len(residuals) < 5:+ continue++ # Assume residuals are normally distributed+ residual_std = np.std(residuals)+ residual_mean = np.mean(residuals)++ # Apply intervals to forecast+ for row in fc_data.iter_rows(named=True):+ result_row = {+ 'entity_id': row['entity_id'],+ 'time': row['time'],+ 'forecast': float(row['value'])+ }++ for conf in confidence_levels:+ from scipy import stats+ z = stats.norm.ppf((1 + conf) / 2)++ lower = row['value'] - z * residual_std + residual_mean+ upper = row['value'] + z * residual_std + residual_mean++ result_row[f'lower_{int(conf*100)}'] = float(lower)+ result_row[f'upper_{int(conf*100)}'] = float(upper)++ result_rows.append(result_row)++ result = pl.DataFrame(result_rows) if result_rows else pl.DataFrame()++ return {+ 'success': True,+ 'method': 'residual',+ 'confidence_levels': confidence_levels,+ 'data': result.to_dicts() if len(result) > 0 else [],+ 'shape': result.shape if len(result) > 0 else (0, 0)+ }+++def _calculate_residuals(actuals: pl.DataFrame, forecasts: pl.DataFrame) -> np.ndarray:+ """Calculate residuals between actuals and forecasts."""+ joined = actuals.join(+ forecasts.select(['entity_id', 'time', 'value']).rename({'value': 'forecast'}),+ on=['entity_id', 'time'],+ how='inner'+ )++ if len(joined) == 0:+ return np.array([])++ return (joined['value'] - joined['forecast']).to_numpy()+++# ============================================================================+# QUANTILE REGRESSION INTERVALS+# ============================================================================++def quantile_prediction_intervals(+ y_train: pl.DataFrame,+ fh: int,+ lags: int = 10,+ quantiles: List[float] = [0.025, 0.10, 0.25, 0.50, 0.75, 0.90, 0.975],+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Generate prediction intervals using quantile regression.++ Args:+ y_train: Training data+ fh: Forecast horizon+ lags: Number of lag features+ quantiles: Quantiles to predict+ freq: Data frequency+ """+ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available for quantile regression'}++ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if len(values) < lags + 10:+ continue++ # Create lag features+ X, y = _create_lag_features(values, lags)++ # Fit quantile regressors+ quantile_predictions = {}++ for q in quantiles:+ try:+ qr = QuantileRegressor(quantile=q, alpha=0.1, solver='highs')+ qr.fit(X, y)+ quantile_predictions[q] = qr+ except Exception:+ continue++ if len(quantile_predictions) < len(quantiles):+ continue++ # Generate forecasts+ last_lags = values[-lags:].tolist()+ delta = _get_time_delta(freq)++ for h in range(1, fh + 1):+ X_pred = np.array([last_lags[-lags:]]).reshape(1, -1)++ row = {+ 'entity_id': entity_id,+ 'time': times[-1] + (delta * h),+ 'horizon': h+ }++ median_pred = None+ for q, model in quantile_predictions.items():+ pred = float(model.predict(X_pred)[0])+ row[f'q{int(q*100):02d}'] = pred+ if q == 0.50:+ median_pred = pred++ if median_pred is not None:+ row['forecast'] = median_pred+ last_lags.append(median_pred)++ result_rows.append(row)++ result = pl.DataFrame(result_rows) if result_rows else pl.DataFrame()++ return {+ 'success': True,+ 'method': 'quantile_regression',+ 'quantiles': quantiles,+ 'data': result.to_dicts() if len(result) > 0 else [],+ 'shape': result.shape if len(result) > 0 else (0, 0)+ }+++# ============================================================================+# CONFORMAL PREDICTION INTERVALS+# ============================================================================++def conformal_prediction_intervals(+ y_train: pl.DataFrame,+ forecast: pl.DataFrame,+ calibration_size: int = 50,+ confidence_levels: List[float] = [0.80, 0.95]+) -> Dict[str, Any]:+ """+ Generate prediction intervals using conformal prediction.++ Uses a calibration set to determine interval widths that+ guarantee coverage at the specified confidence level.++ Args:+ y_train: Full training data (includes calibration portion)+ forecast: Point forecasts+ calibration_size: Number of recent points for calibration+ confidence_levels: Coverage levels+ """+ result_rows = []+ entities = forecast['entity_id'].unique().to_list()++ for entity_id in entities:+ train_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ fc_data = forecast.filter(pl.col('entity_id') == entity_id).sort('time')++ values = train_data['value'].to_numpy()+ n = len(values)++ if n < calibration_size + 10:+ continue++ # Split into proper training and calibration+ cal_values = values[-calibration_size:]++ # Calculate nonconformity scores (absolute residuals from rolling forecast)+ # Simple: use deviation from previous value as nonconformity+ scores = np.abs(np.diff(cal_values))++ if len(scores) < 5:+ continue++ # Calculate conformal quantiles+ for row in fc_data.iter_rows(named=True):+ result_row = {+ 'entity_id': row['entity_id'],+ 'time': row['time'],+ 'forecast': float(row['value'])+ }++ for conf in confidence_levels:+ # Conformal quantile+ q = np.quantile(scores, conf)++ result_row[f'lower_{int(conf*100)}'] = float(row['value'] - q)+ result_row[f'upper_{int(conf*100)}'] = float(row['value'] + q)++ result_rows.append(result_row)++ result = pl.DataFrame(result_rows) if result_rows else pl.DataFrame()++ return {+ 'success': True,+ 'method': 'conformal',+ 'calibration_size': calibration_size,+ 'confidence_levels': confidence_levels,+ 'data': result.to_dicts() if len(result) > 0 else [],+ 'shape': result.shape if len(result) > 0 else (0, 0)+ }+++# ============================================================================+# MONTE CARLO SIMULATION INTERVALS+# ============================================================================++def monte_carlo_intervals(+ y_train: pl.DataFrame,+ fh: int,+ n_simulations: int = 1000,+ model: str = 'random_walk',+ confidence_levels: List[float] = [0.80, 0.95],+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Generate prediction intervals using Monte Carlo simulation.++ Args:+ y_train: Training data+ fh: Forecast horizon+ n_simulations: Number of simulation paths+ model: 'random_walk', 'drift', or 'mean_revert'+ confidence_levels: Confidence levels+ freq: Data frequency+ """+ result_rows = []+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if len(values) < 20:+ continue++ # Estimate parameters from historical data+ returns = np.diff(values)+ mu = np.mean(returns)+ sigma = np.std(returns)+ last_value = values[-1]++ # Run simulations+ simulations = np.zeros((n_simulations, fh))++ for sim_idx in range(n_simulations):+ path = np.zeros(fh)+ current = last_value++ for h in range(fh):+ if model == 'random_walk':+ shock = np.random.normal(0, sigma)+ current = current + shock+ elif model == 'drift':+ shock = np.random.normal(mu, sigma)+ current = current + shock+ elif model == 'mean_revert':+ mean_level = np.mean(values)+ reversion_speed = 0.1+ shock = np.random.normal(0, sigma)+ current = current + reversion_speed * (mean_level - current) + shock++ path[h] = current++ simulations[sim_idx] = path++ # Calculate intervals+ delta = _get_time_delta(freq)++ for h in range(fh):+ sim_values = simulations[:, h]+ point_forecast = np.median(sim_values)++ row = {+ 'entity_id': entity_id,+ 'time': times[-1] + (delta * (h + 1)),+ 'forecast': float(point_forecast),+ 'horizon': h + 1+ }++ for conf in confidence_levels:+ alpha = 1 - conf+ lower = np.percentile(sim_values, alpha / 2 * 100)+ upper = np.percentile(sim_values, (1 - alpha / 2) * 100)++ row[f'lower_{int(conf*100)}'] = float(lower)+ row[f'upper_{int(conf*100)}'] = float(upper)++ result_rows.append(row)++ result = pl.DataFrame(result_rows) if result_rows else pl.DataFrame()++ return {+ 'success': True,+ 'method': 'monte_carlo',+ 'model': model,+ 'n_simulations': n_simulations,+ 'confidence_levels': confidence_levels,+ 'data': result.to_dicts() if len(result) > 0 else [],+ 'shape': result.shape if len(result) > 0 else (0, 0)+ }+++# ============================================================================+# HELPER FUNCTIONS+# ============================================================================++def _create_lag_features(values: np.ndarray, lags: int) -> Tuple[np.ndarray, np.ndarray]:+ """Create lag features for supervised learning."""+ n = len(values)+ X = []+ y = []++ for i in range(lags, n):+ X.append(values[i-lags:i])+ y.append(values[i])++ return np.array(X), np.array(y)+++def _get_time_delta(freq: str) -> timedelta:+ """Convert frequency string to timedelta."""+ freq_map = {+ '1d': timedelta(days=1),+ '1w': timedelta(weeks=1),+ '1h': timedelta(hours=1),+ '1mo': timedelta(days=30),+ }+ return freq_map.get(freq, timedelta(days=1))+++def main():+ """Test confidence interval methods."""+ print("Testing Confidence Intervals Module")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 6, 30),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.2 * i + np.random.randn() * 5 for i in range(n)]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Create mock forecast+ fh = 14+ last_time = dates[-1]+ delta = timedelta(days=1)+ last_value = values[-1]++ fc_rows = []+ for i in range(1, fh + 1):+ fc_rows.append({+ 'entity_id': 'A',+ 'time': last_time + (delta * i),+ 'value': last_value + 0.2 * i+ })++ forecast = pl.DataFrame(fc_rows)++ # Test residual-based intervals+ residual_result = residual_prediction_intervals(+ df, forecast, confidence_levels=[0.80, 0.95]+ )+ print(f"Residual intervals: {len(residual_result['data'])} forecasts")++ # Test conformal intervals+ conformal_result = conformal_prediction_intervals(+ df, forecast, calibration_size=30, confidence_levels=[0.80, 0.95]+ )+ print(f"Conformal intervals: {len(conformal_result['data'])} forecasts")++ # Test Monte Carlo intervals+ mc_result = monte_carlo_intervals(+ df, fh=14, n_simulations=500, model='drift', confidence_levels=[0.80, 0.95]+ )+ print(f"Monte Carlo intervals: {len(mc_result['data'])} forecasts")++ # Test quantile regression+ if SKLEARN_AVAILABLE:+ qr_result = quantile_prediction_intervals(+ df, fh=7, lags=7, quantiles=[0.10, 0.50, 0.90]+ )+ print(f"Quantile regression: {len(qr_result['data'])} forecasts")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/ensemble.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/ensemble.pynew file mode 100644index 000000000..b9efacf67--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/ensemble.py@@ -0,0 +1,604 @@+"""+Ensemble Forecasting Methods+============================++Provides ensemble forecasting capabilities:+- Simple averaging+- Weighted averaging (based on validation performance)+- Stacking with meta-learner+- Trimmed mean (excludes outliers)+- Median ensemble++Combines forecasts from multiple models for improved accuracy.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Callable+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')++# Import base forecasters+try:+ from forecasting import (+ forecast_linear_model, forecast_lasso, forecast_ridge,+ forecast_elasticnet, forecast_knn, forecast_lightgbm+ )+ BASE_FORECASTERS_AVAILABLE = True+except ImportError:+ BASE_FORECASTERS_AVAILABLE = False++try:+ from advanced_models import (+ forecast_naive, forecast_seasonal_naive, forecast_ses,+ forecast_holt, forecast_theta, forecast_xgboost+ )+ ADVANCED_FORECASTERS_AVAILABLE = True+except ImportError:+ ADVANCED_FORECASTERS_AVAILABLE = False+++# ============================================================================+# SIMPLE ENSEMBLE METHODS+# ============================================================================++def ensemble_mean(+ forecasts: List[Dict[str, Any]]+) -> Dict[str, Any]:+ """+ Simple mean ensemble - averages all forecasts.+ """+ if not forecasts:+ return {'success': False, 'error': 'No forecasts provided'}++ # Extract forecast values+ all_forecasts = []+ for fc in forecasts:+ if 'forecast' in fc:+ all_forecasts.append(fc['forecast'])++ if not all_forecasts:+ return {'success': False, 'error': 'No valid forecasts found'}++ # Convert to DataFrames and merge+ combined = _combine_forecasts(all_forecasts)++ if combined is None:+ return {'success': False, 'error': 'Failed to combine forecasts'}++ # Calculate mean+ result = combined.group_by(['entity_id', 'time']).agg([+ pl.col('value').mean().alias('value')+ ]).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'EnsembleMean',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'n_models': len(all_forecasts)+ }+++def ensemble_median(+ forecasts: List[Dict[str, Any]]+) -> Dict[str, Any]:+ """+ Median ensemble - takes median of all forecasts.+ More robust to outliers than mean.+ """+ if not forecasts:+ return {'success': False, 'error': 'No forecasts provided'}++ all_forecasts = [fc['forecast'] for fc in forecasts if 'forecast' in fc]++ if not all_forecasts:+ return {'success': False, 'error': 'No valid forecasts found'}++ combined = _combine_forecasts(all_forecasts)++ if combined is None:+ return {'success': False, 'error': 'Failed to combine forecasts'}++ # Calculate median+ result = combined.group_by(['entity_id', 'time']).agg([+ pl.col('value').median().alias('value')+ ]).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'EnsembleMedian',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'n_models': len(all_forecasts)+ }+++def ensemble_trimmed_mean(+ forecasts: List[Dict[str, Any]],+ trim_fraction: float = 0.1+) -> Dict[str, Any]:+ """+ Trimmed mean ensemble - excludes extreme values before averaging.+ """+ if not forecasts:+ return {'success': False, 'error': 'No forecasts provided'}++ all_forecasts = [fc['forecast'] for fc in forecasts if 'forecast' in fc]++ if len(all_forecasts) < 3:+ # Not enough to trim, fall back to mean+ return ensemble_mean(forecasts)++ combined = _combine_forecasts(all_forecasts)++ if combined is None:+ return {'success': False, 'error': 'Failed to combine forecasts'}++ # Custom trimmed mean aggregation+ def trimmed_mean(values: np.ndarray, trim: float) -> float:+ n = len(values)+ k = int(n * trim)+ if k == 0:+ return np.mean(values)+ sorted_vals = np.sort(values)+ return np.mean(sorted_vals[k:-k]) if k > 0 else np.mean(sorted_vals)++ # Group and calculate trimmed mean+ result_rows = []+ for (entity_id, time), group in combined.group_by(['entity_id', 'time']):+ values = group['value'].to_numpy()+ tm = trimmed_mean(values, trim_fraction)+ result_rows.append({+ 'entity_id': entity_id,+ 'time': time,+ 'value': float(tm)+ })++ result = pl.DataFrame(result_rows).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'EnsembleTrimmedMean',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'n_models': len(all_forecasts),+ 'trim_fraction': trim_fraction+ }+++# ============================================================================+# WEIGHTED ENSEMBLE+# ============================================================================++def ensemble_weighted(+ forecasts: List[Dict[str, Any]],+ weights: Optional[List[float]] = None,+ metric_scores: Optional[List[float]] = None+) -> Dict[str, Any]:+ """+ Weighted ensemble - weights forecasts by performance or custom weights.++ If metric_scores provided (e.g., MAE values), inverse-weights by error.+ If weights provided directly, uses those.+ Otherwise, uses equal weights.+ """+ if not forecasts:+ return {'success': False, 'error': 'No forecasts provided'}++ all_forecasts = [fc['forecast'] for fc in forecasts if 'forecast' in fc]++ if not all_forecasts:+ return {'success': False, 'error': 'No valid forecasts found'}++ n_models = len(all_forecasts)++ # Determine weights+ if weights is not None:+ if len(weights) != n_models:+ return {'success': False, 'error': 'Weights length must match number of models'}+ w = np.array(weights)+ elif metric_scores is not None:+ if len(metric_scores) != n_models:+ return {'success': False, 'error': 'Metric scores length must match number of models'}+ # Inverse weight by error (lower error = higher weight)+ scores = np.array(metric_scores)+ # Avoid division by zero+ scores = np.maximum(scores, 1e-10)+ w = 1.0 / scores+ else:+ w = np.ones(n_models)++ # Normalize weights+ w = w / w.sum()++ # Combine forecasts with weights+ combined_rows = []+ for i, fc in enumerate(all_forecasts):+ for row in fc:+ combined_rows.append({+ 'entity_id': row['entity_id'],+ 'time': row['time'],+ 'value': row['value'],+ 'weight': float(w[i]),+ 'model_idx': i+ })++ combined = pl.DataFrame(combined_rows)++ # Calculate weighted average+ result = combined.group_by(['entity_id', 'time']).agg([+ (pl.col('value') * pl.col('weight')).sum().alias('value')+ ]).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'EnsembleWeighted',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'n_models': n_models,+ 'weights': w.tolist()+ }+++# ============================================================================+# STACKING ENSEMBLE+# ============================================================================++def ensemble_stacking(+ y_train: pl.DataFrame,+ fh: int,+ base_models: List[str] = ['lasso', 'ridge', 'knn'],+ meta_model: str = 'ridge',+ freq: str = '1d',+ validation_size: int = 10+) -> Dict[str, Any]:+ """+ Stacking ensemble with meta-learner.++ 1. Split data into train and validation+ 2. Fit base models on train, predict validation+ 3. Train meta-learner on base model predictions+ 4. Generate final forecast using meta-learner+ """+ if not BASE_FORECASTERS_AVAILABLE:+ return {'success': False, 'error': 'Base forecasters not available'}++ entities = y_train['entity_id'].unique().to_list()+ result_rows = []++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')++ if len(entity_data) < validation_size + 10:+ # Not enough data for stacking+ continue++ # Split into train and validation+ train_data = entity_data.head(-validation_size)+ val_data = entity_data.tail(validation_size)++ # Prepare train for single entity+ train_single = train_data.clone()++ # Get base model predictions on validation set+ base_preds = []+ model_forecasters = _get_model_forecasters()++ for model_name in base_models:+ if model_name not in model_forecasters:+ continue++ try:+ forecast_result = model_forecasters[model_name](+ train_single, fh=validation_size, freq=freq+ )+ if 'forecast' in forecast_result:+ preds = [f['value'] for f in forecast_result['forecast']]+ base_preds.append(preds)+ except Exception:+ continue++ if len(base_preds) < 2:+ continue++ # Create meta-features+ X_meta = np.column_stack(base_preds)+ y_val = val_data['value'].to_numpy()++ # Fit meta-model (simple linear regression)+ from sklearn.linear_model import Ridge+ meta = Ridge(alpha=1.0)+ meta.fit(X_meta, y_val)++ # Now generate forecasts using all training data+ full_train = entity_data.clone()+ final_base_preds = []++ for model_name in base_models:+ if model_name not in model_forecasters:+ continue++ try:+ forecast_result = model_forecasters[model_name](+ full_train, fh=fh, freq=freq+ )+ if 'forecast' in forecast_result:+ preds = [f['value'] for f in forecast_result['forecast']]+ times = [f['time'] for f in forecast_result['forecast']]+ final_base_preds.append(preds)+ except Exception:+ continue++ if len(final_base_preds) != len(base_preds):+ continue++ # Apply meta-model+ X_final = np.column_stack(final_base_preds)+ final_preds = meta.predict(X_final)++ for i, pred in enumerate(final_preds):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': times[i],+ 'value': float(pred)+ })++ if not result_rows:+ return {'success': False, 'error': 'Stacking failed for all entities'}++ result = pl.DataFrame(result_rows).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'EnsembleStacking',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'base_models': base_models,+ 'meta_model': meta_model+ }+++# ============================================================================+# AUTO ENSEMBLE+# ============================================================================++def auto_ensemble(+ y_train: pl.DataFrame,+ fh: int,+ models: Optional[List[str]] = None,+ validation_size: int = 10,+ weighting: str = 'inverse_error', # 'equal', 'inverse_error', 'best_n'+ best_n: int = 3,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Automatically select and combine best performing models.++ 1. Run all models on validation set+ 2. Evaluate performance+ 3. Combine using specified weighting method+ """+ if models is None:+ models = ['naive', 'ses', 'lasso', 'ridge', 'knn']++ entities = y_train['entity_id'].unique().to_list()+ result_rows = []+ model_scores = {}++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')++ if len(entity_data) < validation_size + 10:+ continue++ train_data = entity_data.head(-validation_size)+ val_data = entity_data.tail(validation_size)+ y_val = val_data['value'].to_numpy()++ # Evaluate each model+ model_forecasters = _get_model_forecasters()+ model_performances = {}+ model_forecasts = {}++ for model_name in models:+ if model_name not in model_forecasters:+ continue++ try:+ forecast_result = model_forecasters[model_name](+ train_data, fh=validation_size, freq=freq+ )+ if 'forecast' in forecast_result:+ preds = np.array([f['value'] for f in forecast_result['forecast']])+ mae = np.mean(np.abs(y_val - preds))+ model_performances[model_name] = mae+ model_forecasts[model_name] = forecast_result+ except Exception:+ continue++ if not model_performances:+ continue++ # Select models based on weighting strategy+ if weighting == 'best_n':+ sorted_models = sorted(model_performances.items(), key=lambda x: x[1])+ selected_models = [m[0] for m in sorted_models[:best_n]]+ weights = np.ones(len(selected_models)) / len(selected_models)+ elif weighting == 'inverse_error':+ selected_models = list(model_performances.keys())+ errors = np.array([model_performances[m] for m in selected_models])+ weights = 1.0 / (errors + 1e-10)+ weights = weights / weights.sum()+ else: # equal+ selected_models = list(model_performances.keys())+ weights = np.ones(len(selected_models)) / len(selected_models)++ # Generate final forecasts+ full_forecasts = []+ for model_name in selected_models:+ try:+ forecast_result = model_forecasters[model_name](+ entity_data, fh=fh, freq=freq+ )+ if 'forecast' in forecast_result:+ full_forecasts.append(forecast_result['forecast'])+ except Exception:+ continue++ if not full_forecasts:+ continue++ # Combine with weights+ n_horizons = len(full_forecasts[0])+ for h in range(n_horizons):+ weighted_sum = 0.0+ times_h = full_forecasts[0][h]['time']++ for i, fc in enumerate(full_forecasts):+ if i < len(weights):+ weighted_sum += fc[h]['value'] * weights[i]++ result_rows.append({+ 'entity_id': entity_id,+ 'time': times_h,+ 'value': float(weighted_sum)+ })++ model_scores[entity_id] = model_performances++ if not result_rows:+ return {'success': False, 'error': 'Auto ensemble failed'}++ result = pl.DataFrame(result_rows).sort(['entity_id', 'time'])++ return {+ 'success': True,+ 'model_type': 'AutoEnsemble',+ 'forecast': result.to_dicts(),+ 'shape': result.shape,+ 'models_used': models,+ 'weighting': weighting,+ 'model_scores': model_scores+ }+++# ============================================================================+# HELPER FUNCTIONS+# ============================================================================++def _combine_forecasts(forecasts: List[List[Dict]]) -> Optional[pl.DataFrame]:+ """Combine multiple forecast lists into single DataFrame with model index."""+ if not forecasts:+ return None++ all_rows = []+ for i, fc in enumerate(forecasts):+ for row in fc:+ all_rows.append({+ 'entity_id': row['entity_id'],+ 'time': row['time'],+ 'value': row['value'],+ 'model_idx': i+ })++ if not all_rows:+ return None++ return pl.DataFrame(all_rows)+++def _get_model_forecasters() -> Dict[str, Callable]:+ """Get dictionary of available model forecasters."""+ forecasters = {}++ if BASE_FORECASTERS_AVAILABLE:+ forecasters.update({+ 'linear': forecast_linear_model,+ 'lasso': forecast_lasso,+ 'ridge': forecast_ridge,+ 'elasticnet': forecast_elasticnet,+ 'knn': forecast_knn,+ 'lightgbm': forecast_lightgbm,+ })++ if ADVANCED_FORECASTERS_AVAILABLE:+ forecasters.update({+ 'naive': forecast_naive,+ 'seasonal_naive': forecast_seasonal_naive,+ 'ses': forecast_ses,+ 'holt': forecast_holt,+ 'theta': forecast_theta,+ 'xgboost': forecast_xgboost,+ })++ return forecasters+++def main():+ """Test ensemble methods."""+ print("Testing Ensemble Forecasting Methods")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 3, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)+ values = [100 + 0.5 * i + 10 * np.sin(2 * np.pi * i / 7) + np.random.randn() * 3 for i in range(n)]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Create mock forecasts+ fh = 7+ last_time = dates[-1]+ delta = timedelta(days=1)++ mock_forecasts = []+ for model_shift in [0, 2, -1]: # Different biases+ fc = []+ for i in range(1, fh + 1):+ fc.append({+ 'entity_id': 'A',+ 'time': last_time + (delta * i),+ 'value': 150 + model_shift + np.random.randn()+ })+ mock_forecasts.append({'forecast': fc})++ # Test mean ensemble+ mean_result = ensemble_mean(mock_forecasts)+ print(f"Mean Ensemble: {mean_result['n_models']} models combined")++ # Test median ensemble+ median_result = ensemble_median(mock_forecasts)+ print(f"Median Ensemble: {median_result['n_models']} models combined")++ # Test trimmed mean+ trimmed_result = ensemble_trimmed_mean(mock_forecasts, trim_fraction=0.1)+ print(f"Trimmed Mean Ensemble: {trimmed_result.get('n_models', 0)} models combined")++ # Test weighted ensemble+ weights = [0.5, 0.3, 0.2]+ weighted_result = ensemble_weighted(mock_forecasts, weights=weights)+ print(f"Weighted Ensemble: weights = {weighted_result.get('weights', [])}")++ # Test auto ensemble+ auto_result = auto_ensemble(df, fh=fh, models=['naive', 'ses'], validation_size=10)+ print(f"Auto Ensemble: success = {auto_result['success']}")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/feature_importance.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/feature_importance.pynew file mode 100644index 000000000..62ca991eb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/feature_importance.py@@ -0,0 +1,540 @@+"""+Feature Importance Module+=========================++Provides feature importance analysis for time series models:+- Permutation importance+- SHAP values (if available)+- Model-specific importance (tree-based)+- Lag importance analysis+- Sensitivity analysis++Helps understand which features drive forecasts.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple, Callable+from datetime import datetime, timedelta+import warnings++warnings.filterwarnings('ignore')++# Try importing sklearn+try:+ from sklearn.inspection import permutation_importance+ from sklearn.linear_model import Ridge, Lasso+ from sklearn.ensemble import RandomForestRegressor+ SKLEARN_AVAILABLE = True+except ImportError:+ SKLEARN_AVAILABLE = False++# Try importing SHAP+try:+ import shap+ SHAP_AVAILABLE = True+except ImportError:+ SHAP_AVAILABLE = False+++# ============================================================================+# PERMUTATION IMPORTANCE+# ============================================================================++def calculate_permutation_importance(+ y_train: pl.DataFrame,+ n_lags: int = 10,+ n_repeats: int = 10,+ model_type: str = 'ridge'+) -> Dict[str, Any]:+ """+ Calculate permutation importance for lag features.++ Measures how much shuffling each feature degrades model performance.++ Args:+ y_train: Training panel data+ n_lags: Number of lag features+ n_repeats: Number of permutation repeats+ model_type: 'ridge', 'lasso', or 'rf'+ """+ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available'}++ results = {}+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ if len(values) < n_lags + 20:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ # Create lag features+ X, y = _create_lag_features(values, n_lags)++ # Split into train/test+ split_idx = int(len(X) * 0.8)+ X_train, X_test = X[:split_idx], X[split_idx:]+ y_train_arr, y_test = y[:split_idx], y[split_idx:]++ # Fit model+ if model_type == 'ridge':+ model = Ridge(alpha=1.0)+ elif model_type == 'lasso':+ model = Lasso(alpha=0.1)+ elif model_type == 'rf':+ model = RandomForestRegressor(n_estimators=50, random_state=42)+ else:+ model = Ridge(alpha=1.0)++ model.fit(X_train, y_train_arr)++ # Calculate permutation importance+ perm_result = permutation_importance(+ model, X_test, y_test,+ n_repeats=n_repeats,+ random_state=42+ )++ # Format results+ feature_names = [f'lag_{i+1}' for i in range(n_lags)]+ importance_mean = perm_result.importances_mean+ importance_std = perm_result.importances_std++ # Sort by importance+ sorted_idx = np.argsort(importance_mean)[::-1]++ results[entity_id] = {+ 'feature_names': [feature_names[i] for i in sorted_idx],+ 'importance_mean': importance_mean[sorted_idx].tolist(),+ 'importance_std': importance_std[sorted_idx].tolist(),+ 'model_type': model_type,+ 'baseline_score': float(model.score(X_test, y_test))+ }++ return {+ 'success': True,+ 'method': 'permutation',+ 'n_lags': n_lags,+ 'n_repeats': n_repeats,+ 'results': results+ }+++# ============================================================================+# MODEL-SPECIFIC IMPORTANCE+# ============================================================================++def calculate_model_importance(+ y_train: pl.DataFrame,+ n_lags: int = 10,+ model_type: str = 'ridge'+) -> Dict[str, Any]:+ """+ Calculate model-specific feature importance.++ For linear models: coefficient magnitudes+ For tree models: impurity-based importance++ Args:+ y_train: Training panel data+ n_lags: Number of lag features+ model_type: 'ridge', 'lasso', 'rf'+ """+ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available'}++ results = {}+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ if len(values) < n_lags + 20:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ # Create lag features+ X, y = _create_lag_features(values, n_lags)++ # Standardize for linear models+ X_mean = X.mean(axis=0)+ X_std = X.std(axis=0)+ X_std[X_std == 0] = 1+ X_scaled = (X - X_mean) / X_std++ # Fit model+ if model_type == 'ridge':+ model = Ridge(alpha=1.0)+ model.fit(X_scaled, y)+ importance = np.abs(model.coef_)+ elif model_type == 'lasso':+ model = Lasso(alpha=0.1)+ model.fit(X_scaled, y)+ importance = np.abs(model.coef_)+ elif model_type == 'rf':+ model = RandomForestRegressor(n_estimators=50, random_state=42)+ model.fit(X, y)+ importance = model.feature_importances_+ else:+ model = Ridge(alpha=1.0)+ model.fit(X_scaled, y)+ importance = np.abs(model.coef_)++ # Normalize importance+ if np.sum(importance) > 0:+ importance = importance / np.sum(importance)++ feature_names = [f'lag_{i+1}' for i in range(n_lags)]+ sorted_idx = np.argsort(importance)[::-1]++ results[entity_id] = {+ 'feature_names': [feature_names[i] for i in sorted_idx],+ 'importance': importance[sorted_idx].tolist(),+ 'model_type': model_type,+ 'coefficients': model.coef_.tolist() if hasattr(model, 'coef_') else None+ }++ return {+ 'success': True,+ 'method': 'model_specific',+ 'n_lags': n_lags,+ 'model_type': model_type,+ 'results': results+ }+++# ============================================================================+# SHAP VALUES+# ============================================================================++def calculate_shap_importance(+ y_train: pl.DataFrame,+ n_lags: int = 10,+ max_samples: int = 100+) -> Dict[str, Any]:+ """+ Calculate SHAP values for feature importance.++ SHAP provides consistent, game-theoretic feature attributions.++ Args:+ y_train: Training panel data+ n_lags: Number of lag features+ max_samples: Maximum samples for SHAP calculation+ """+ if not SHAP_AVAILABLE:+ return {'success': False, 'error': 'SHAP not available. Install with: pip install shap'}++ if not SKLEARN_AVAILABLE:+ return {'success': False, 'error': 'sklearn not available'}++ results = {}+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ if len(values) < n_lags + 20:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ # Create lag features+ X, y = _create_lag_features(values, n_lags)++ # Limit samples+ if len(X) > max_samples:+ indices = np.random.choice(len(X), max_samples, replace=False)+ X = X[indices]+ y = y[indices]++ # Fit model+ model = Ridge(alpha=1.0)+ model.fit(X, y)++ # Calculate SHAP values+ try:+ explainer = shap.LinearExplainer(model, X)+ shap_values = explainer.shap_values(X)++ # Mean absolute SHAP values per feature+ mean_shap = np.abs(shap_values).mean(axis=0)++ feature_names = [f'lag_{i+1}' for i in range(n_lags)]+ sorted_idx = np.argsort(mean_shap)[::-1]++ results[entity_id] = {+ 'feature_names': [feature_names[i] for i in sorted_idx],+ 'mean_shap': mean_shap[sorted_idx].tolist(),+ 'shap_values_sample': shap_values[:10].tolist() if len(shap_values) >= 10 else shap_values.tolist()+ }+ except Exception as e:+ results[entity_id] = {'error': str(e)}++ return {+ 'success': True,+ 'method': 'shap',+ 'n_lags': n_lags,+ 'results': results+ }+++# ============================================================================+# LAG IMPORTANCE ANALYSIS+# ============================================================================++def analyze_lag_importance(+ y_train: pl.DataFrame,+ max_lags: int = 20+) -> Dict[str, Any]:+ """+ Analyze importance of different lag values.++ Uses autocorrelation and partial autocorrelation to identify+ significant lags.++ Args:+ y_train: Training panel data+ max_lags: Maximum lag to analyze+ """+ results = {}+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ if len(values) < max_lags + 10:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ n = len(values)+ actual_max_lags = min(max_lags, n // 2 - 1)++ # Calculate ACF+ acf = np.zeros(actual_max_lags + 1)+ mean = np.mean(values)+ var = np.var(values)++ if var == 0:+ results[entity_id] = {'error': 'Zero variance'}+ continue++ for k in range(actual_max_lags + 1):+ acf[k] = np.sum((values[k:] - mean) * (values[:n-k] - mean)) / ((n - k) * var)++ # Calculate PACF (using Yule-Walker equations approximation)+ pacf = np.zeros(actual_max_lags + 1)+ pacf[0] = 1.0+ if actual_max_lags > 0:+ pacf[1] = acf[1]++ for k in range(2, actual_max_lags + 1):+ # Simple approximation+ phi = np.zeros(k + 1)+ phi[1] = acf[1]+ for j in range(2, k + 1):+ num = acf[j] - sum(phi[m] * acf[j - m] for m in range(1, j))+ den = 1 - sum(phi[m] * acf[m] for m in range(1, j))+ if den != 0:+ phi[j] = num / den+ pacf[k] = phi[k]++ # Significance threshold (95% confidence)+ significance_threshold = 1.96 / np.sqrt(n)++ # Find significant lags+ significant_lags = [+ i for i in range(1, actual_max_lags + 1)+ if abs(acf[i]) > significance_threshold or abs(pacf[i]) > significance_threshold+ ]++ results[entity_id] = {+ 'acf': acf.tolist(),+ 'pacf': pacf.tolist(),+ 'lags': list(range(actual_max_lags + 1)),+ 'significant_lags': significant_lags,+ 'significance_threshold': float(significance_threshold),+ 'recommended_lags': significant_lags[:5] if len(significant_lags) > 0 else [1, 2, 3]+ }++ return {+ 'success': True,+ 'method': 'lag_analysis',+ 'max_lags': max_lags,+ 'results': results+ }+++# ============================================================================+# SENSITIVITY ANALYSIS+# ============================================================================++def sensitivity_analysis(+ y_train: pl.DataFrame,+ forecaster: Callable,+ fh: int = 10,+ perturbation_pct: float = 0.05,+ n_perturbations: int = 20,+ freq: str = '1d'+) -> Dict[str, Any]:+ """+ Analyze forecast sensitivity to input perturbations.++ Measures how small changes in input affect forecasts.++ Args:+ y_train: Training panel data+ forecaster: Forecasting function+ fh: Forecast horizon+ perturbation_pct: Percentage perturbation+ n_perturbations: Number of perturbations+ freq: Data frequency+ """+ results = {}+ entities = y_train['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y_train.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ n = len(values)++ if n < 20:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ # Baseline forecast+ try:+ base_result = forecaster(entity_data, fh=fh, freq=freq)+ if 'forecast' not in base_result:+ results[entity_id] = {'error': 'Forecaster failed'}+ continue+ base_forecast = np.array([f['value'] for f in base_result['forecast']])+ except Exception as e:+ results[entity_id] = {'error': str(e)}+ continue++ # Perturb each recent point and measure impact+ sensitivity_by_point = []+ perturbation_size = perturbation_pct * np.std(values)++ for i in range(min(n_perturbations, n // 2)):+ point_idx = n - 1 - i # Start from most recent++ # Create perturbed data+ perturbed_values = values.copy()+ perturbed_values[point_idx] += perturbation_size++ perturbed_data = entity_data.clone()+ perturbed_data = perturbed_data.with_columns([+ pl.when(pl.arange(0, len(perturbed_data)) == point_idx)+ .then(pl.lit(perturbed_values[point_idx]))+ .otherwise(pl.col('value'))+ .alias('value')+ ])++ try:+ pert_result = forecaster(perturbed_data, fh=fh, freq=freq)+ if 'forecast' in pert_result:+ pert_forecast = np.array([f['value'] for f in pert_result['forecast']])+ forecast_change = np.mean(np.abs(pert_forecast - base_forecast))+ sensitivity = forecast_change / perturbation_size+ sensitivity_by_point.append({+ 'point_index': point_idx,+ 'recency': i + 1,+ 'sensitivity': float(sensitivity)+ })+ except Exception:+ continue++ if sensitivity_by_point:+ avg_sensitivity = np.mean([s['sensitivity'] for s in sensitivity_by_point])+ results[entity_id] = {+ 'sensitivity_by_point': sensitivity_by_point,+ 'average_sensitivity': float(avg_sensitivity),+ 'perturbation_size': float(perturbation_size)+ }+ else:+ results[entity_id] = {'error': 'Could not compute sensitivity'}++ return {+ 'success': True,+ 'method': 'sensitivity',+ 'perturbation_pct': perturbation_pct,+ 'results': results+ }+++# ============================================================================+# HELPER FUNCTIONS+# ============================================================================++def _create_lag_features(values: np.ndarray, lags: int) -> Tuple[np.ndarray, np.ndarray]:+ """Create lag features for supervised learning."""+ n = len(values)+ X = []+ y = []++ for i in range(lags, n):+ X.append(values[i-lags:i])+ y.append(values[i])++ return np.array(X), np.array(y)+++def main():+ """Test feature importance methods."""+ print("Testing Feature Importance Module")+ print("=" * 50)++ # Create sample data+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 12, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)++ # AR(3) process with known coefficients+ values = np.zeros(n)+ values[0:3] = np.random.randn(3) * 10 + 100++ for i in range(3, n):+ values[i] = 0.5 * values[i-1] + 0.3 * values[i-2] + 0.1 * values[i-3] + np.random.randn() * 2++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values.tolist()+ })++ # Test permutation importance+ if SKLEARN_AVAILABLE:+ perm_result = calculate_permutation_importance(df, n_lags=5, n_repeats=5)+ print(f"Permutation importance: {perm_result['results']['A']['feature_names'][:3]}")++ model_result = calculate_model_importance(df, n_lags=5, model_type='ridge')+ print(f"Model importance: {model_result['results']['A']['feature_names'][:3]}")++ # Test lag analysis+ lag_result = analyze_lag_importance(df, max_lags=10)+ print(f"Significant lags: {lag_result['results']['A']['significant_lags']}")++ # Test SHAP+ if SHAP_AVAILABLE:+ shap_result = calculate_shap_importance(df, n_lags=5, max_samples=50)+ print(f"SHAP importance: success = {shap_result['success']}")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.pyindex db10ade61..6e9afbe7f 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/functime_service.py@@ -82,6 +82,90 @@ if FUNCTIME_AVAILABLE:except ImportError as e:print(f"Warning: Could not import local modules: {e}", file=sys.stderr)+# Import advanced modules+try:+ from advanced_models import (+ naive_forecast, seasonal_naive_forecast, drift_forecast,+ ses_forecast, holt_forecast, theta_forecast,+ croston_forecast, xgboost_forecast, catboost_forecast+ )+ ADVANCED_MODELS_AVAILABLE = True+except ImportError as e:+ ADVANCED_MODELS_AVAILABLE = False+ print(f"Warning: Could not import advanced_models: {e}", file=sys.stderr)++try:+ from ensemble import (+ ensemble_mean, ensemble_median, ensemble_trimmed_mean,+ ensemble_weighted, ensemble_stacking, auto_ensemble+ )+ ENSEMBLE_AVAILABLE = True+except ImportError as e:+ ENSEMBLE_AVAILABLE = False+ print(f"Warning: Could not import ensemble: {e}", file=sys.stderr)++try:+ from anomaly_detection import (+ detect_zscore, detect_iqr, detect_grubbs,+ detect_isolation_forest, detect_lof,+ detect_residual_anomalies, detect_change_points+ )+ ANOMALY_AVAILABLE = True+except ImportError as e:+ ANOMALY_AVAILABLE = False+ print(f"Warning: Could not import anomaly_detection: {e}", file=sys.stderr)++try:+ from seasonality import (+ detect_seasonal_period, decompose_stl, decompose_classical,+ seasonally_adjust, calculate_seasonality_metrics+ )+ SEASONALITY_AVAILABLE = True+except ImportError as e:+ SEASONALITY_AVAILABLE = False+ print(f"Warning: Could not import seasonality: {e}", file=sys.stderr)++try:+ from confidence_intervals import (+ bootstrap_prediction_intervals, residual_prediction_intervals,+ quantile_prediction_intervals, conformal_prediction_intervals,+ monte_carlo_intervals+ )+ CONFIDENCE_AVAILABLE = True+except ImportError as e:+ CONFIDENCE_AVAILABLE = False+ print(f"Warning: Could not import confidence_intervals: {e}", file=sys.stderr)++try:+ from feature_importance import (+ calculate_permutation_importance, calculate_model_importance,+ calculate_shap_importance, analyze_lag_importance, sensitivity_analysis+ )+ FEATURE_IMPORTANCE_AVAILABLE = True+except ImportError as e:+ FEATURE_IMPORTANCE_AVAILABLE = False+ print(f"Warning: Could not import feature_importance: {e}", file=sys.stderr)++try:+ from advanced_cv import (+ blocked_time_series_cv, purged_kfold_cv, combinatorial_purged_cv,+ walk_forward_validation, nested_cv, get_cv_splits+ )+ ADVANCED_CV_AVAILABLE = True+except ImportError as e:+ ADVANCED_CV_AVAILABLE = False+ print(f"Warning: Could not import advanced_cv: {e}", file=sys.stderr)++try:+ from backtesting import (+ walk_forward_backtest, compare_models_backtest,+ rolling_origin_evaluation, performance_attribution, backtest_summary+ )+ BACKTESTING_AVAILABLE = True+except ImportError as e:+ BACKTESTING_AVAILABLE = False+ print(f"Warning: Could not import backtesting: {e}", file=sys.stderr)+def parse_panel_data_json(data_json: str) -> "pl.DataFrame":"""Parse JSON data into Polars DataFrame for functime panel data format"""@@ -232,6 +316,14 @@ def check_status() -> Dict[str, Any]:"polars_available": POLARS_AVAILABLE,"lightgbm_available": LIGHTGBM_AVAILABLE,"functime_cloud_available": FUNCTIME_CLOUD_AVAILABLE,+ "advanced_models_available": ADVANCED_MODELS_AVAILABLE,+ "ensemble_available": ENSEMBLE_AVAILABLE,+ "anomaly_available": ANOMALY_AVAILABLE,+ "seasonality_available": SEASONALITY_AVAILABLE,+ "confidence_available": CONFIDENCE_AVAILABLE,+ "feature_importance_available": FEATURE_IMPORTANCE_AVAILABLE,+ "advanced_cv_available": ADVANCED_CV_AVAILABLE,+ "backtesting_available": BACKTESTING_AVAILABLE,"message": "Time series forecasting ready (sklearn backend)" if FUNCTIME_AVAILABLE else "scikit-learn or polars not installed"}@@ -628,7 +720,8 @@ def full_forecast_pipeline(params: Dict[str, Any]) -> Dict[str, Any]:if preprocess_method and preprocess_method != 'none':preprocessing_info = {"method": preprocess_method, "note": "Preprocessing not applied - using raw data"}- # Simple train/test split by taking last test_size rows per entity+ # Train/test split: Hold out test_size rows per entity for evaluation+ # We train on earlier data, make predictions for the test period, and comparetrain_data = processed_datatest_data = None@@ -654,42 +747,53 @@ def full_forecast_pipeline(params: Dict[str, Any]) -> Dict[str, Any]:train_data = processed_dataprint(f"Warning: Could not split data: {e}", file=sys.stderr)- # Run forecast+ # Calculate evaluation metrics BEFORE generating the final forecast+ # We need to predict on the test period using the training data+ metrics = None+ if test_data is not None and len(test_data) > 0:+ try:+ # Get actual test values+ y_true_values = test_data['value'].to_numpy()++ # For evaluation, we predict for test_size periods from training data+ eval_forecast_result = run_forecast({+ 'data': serialize_to_json(train_data.to_dicts()),+ 'model': model_type,+ 'horizon': min(test_size, len(y_true_values)), # Match test size+ 'frequency': freq+ })++ if eval_forecast_result.get('success'):+ forecast_list = eval_forecast_result.get('forecast', [])+ if len(forecast_list) > 0:+ y_pred_values = np.array([f['value'] for f in forecast_list])++ if len(y_pred_values) > 0 and len(y_true_values) > 0:+ min_len = min(len(y_true_values), len(y_pred_values))+ y_true = y_true_values[:min_len]+ y_pred = y_pred_values[:min_len]++ mae = float(np.mean(np.abs(y_true - y_pred)))+ rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2)))+ # SMAPE+ smape = float(np.mean(2 * np.abs(y_true - y_pred) / (np.abs(y_true) + np.abs(y_pred) + 1e-8)) * 100)++ metrics = {+ 'mae': mae,+ 'rmse': rmse,+ 'smape': smape+ }+ except Exception as e:+ print(f"Warning: Could not calculate metrics: {e}", file=sys.stderr)++ # Now run forecast on FULL data for actual future predictionsforecast_result = run_forecast({- 'data': serialize_to_json(train_data.to_dicts()),+ 'data': serialize_to_json(processed_data.to_dicts()),'model': model_type,'horizon': fh,'frequency': freq})- # Calculate metrics if we have test data- metrics = None- if test_data is not None and len(test_data) > 0 and forecast_result.get('success'):- try:- forecast_list = forecast_result.get('forecast', [])- if len(forecast_list) > 0:- # Simple MAE/RMSE calculation- y_true_values = test_data['value'].to_numpy()- y_pred_values = np.array([f['value'] for f in forecast_list[:len(y_true_values)]])-- if len(y_pred_values) > 0 and len(y_true_values) > 0:- min_len = min(len(y_true_values), len(y_pred_values))- y_true = y_true_values[:min_len]- y_pred = y_pred_values[:min_len]-- mae = float(np.mean(np.abs(y_true - y_pred)))- rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2)))- # SMAPE- smape = float(np.mean(2 * np.abs(y_true - y_pred) / (np.abs(y_true) + np.abs(y_pred) + 1e-8)) * 100)-- metrics = {- 'mae': mae,- 'rmse': rmse,- 'smape': smape- }- except Exception as e:- print(f"Warning: Could not calculate metrics: {e}", file=sys.stderr)-return {"success": True,"model": model_type,@@ -711,6 +815,484 @@ def full_forecast_pipeline(params: Dict[str, Any]) -> Dict[str, Any]:return {"success": False, "error": str(e)}+# ============================================================================+# ADVANCED MODELS COMMAND HANDLERS+# ============================================================================++def run_advanced_forecast(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run advanced forecasting models (naive, SES, Holt, Theta, Croston, XGBoost, CatBoost)"""+ if not ADVANCED_MODELS_AVAILABLE:+ return {"success": False, "error": "Advanced models not available"}++ try:+ data = parse_panel_data_json(params['data'])+ model_type = params.get('model', 'naive')+ fh = params.get('horizon', 7)+ freq = params.get('frequency', '1d')++ model_params = params.get('model_params', {})++ if model_type == 'naive':+ result = naive_forecast(data, fh=fh, freq=freq)+ elif model_type == 'seasonal_naive':+ seasonal_period = model_params.get('seasonal_period', 7)+ result = seasonal_naive_forecast(data, fh=fh, seasonal_period=seasonal_period, freq=freq)+ elif model_type == 'drift':+ result = drift_forecast(data, fh=fh, freq=freq)+ elif model_type == 'ses':+ alpha = model_params.get('alpha')+ result = ses_forecast(data, fh=fh, alpha=alpha, freq=freq)+ elif model_type == 'holt':+ alpha = model_params.get('alpha')+ beta = model_params.get('beta')+ result = holt_forecast(data, fh=fh, alpha=alpha, beta=beta, freq=freq)+ elif model_type == 'theta':+ result = theta_forecast(data, fh=fh, freq=freq)+ elif model_type == 'croston':+ alpha = model_params.get('alpha', 0.1)+ result = croston_forecast(data, fh=fh, alpha=alpha, freq=freq)+ elif model_type == 'xgboost':+ n_lags = model_params.get('n_lags', 10)+ xgb_params = model_params.get('xgb_params', {})+ result = xgboost_forecast(data, fh=fh, n_lags=n_lags, xgb_params=xgb_params, freq=freq)+ elif model_type == 'catboost':+ n_lags = model_params.get('n_lags', 10)+ cat_params = model_params.get('cat_params', {})+ result = catboost_forecast(data, fh=fh, n_lags=n_lags, cat_params=cat_params, freq=freq)+ else:+ return {"success": False, "error": f"Unknown advanced model: {model_type}"}++ return result+ except Exception as e:+ import traceback+ return {"success": False, "error": str(e), "traceback": traceback.format_exc()}+++# ============================================================================+# ENSEMBLE COMMAND HANDLERS+# ============================================================================++def run_ensemble(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run ensemble forecasting"""+ if not ENSEMBLE_AVAILABLE:+ return {"success": False, "error": "Ensemble methods not available"}++ try:+ forecasts_json = params.get('forecasts', [])+ method = params.get('method', 'mean')++ # Parse forecasts - each should be a list of {entity_id, time, value}+ if isinstance(forecasts_json, str):+ forecasts_json = json.loads(forecasts_json)++ forecasts = [pl.DataFrame(fc) for fc in forecasts_json]++ if method == 'mean':+ result = ensemble_mean(forecasts)+ elif method == 'median':+ result = ensemble_median(forecasts)+ elif method == 'trimmed_mean':+ trim_pct = params.get('trim_pct', 0.1)+ result = ensemble_trimmed_mean(forecasts, trim_pct=trim_pct)+ elif method == 'weighted':+ weights = params.get('weights')+ result = ensemble_weighted(forecasts, weights=weights)+ elif method == 'stacking':+ y_train = parse_panel_data_json(params['y_train'])+ result = ensemble_stacking(forecasts, y_train)+ else:+ return {"success": False, "error": f"Unknown ensemble method: {method}"}++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++def run_auto_ensemble(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run automatic ensemble selection and combination"""+ if not ENSEMBLE_AVAILABLE:+ return {"success": False, "error": "Ensemble methods not available"}++ try:+ data = parse_panel_data_json(params['data'])+ fh = params.get('horizon', 7)+ freq = params.get('frequency', '1d')+ n_best = params.get('n_best', 3)++ result = auto_ensemble(data, fh=fh, freq=freq, n_best=n_best)+ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# ANOMALY DETECTION COMMAND HANDLERS+# ============================================================================++def run_anomaly_detection(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run anomaly detection on time series"""+ if not ANOMALY_AVAILABLE:+ return {"success": False, "error": "Anomaly detection not available"}++ try:+ data = parse_panel_data_json(params['data'])+ method = params.get('method', 'zscore')++ if method == 'zscore':+ threshold = params.get('threshold', 3.0)+ result = detect_zscore(data, threshold=threshold)+ elif method == 'iqr':+ multiplier = params.get('multiplier', 1.5)+ result = detect_iqr(data, k=multiplier)+ elif method == 'grubbs':+ alpha = params.get('alpha', 0.05)+ result = detect_grubbs(data, alpha=alpha)+ elif method == 'isolation_forest':+ contamination = params.get('contamination', 0.05)+ result = detect_isolation_forest(data, contamination=contamination)+ elif method == 'lof':+ n_neighbors = params.get('n_neighbors', 20)+ contamination = params.get('contamination', 0.05)+ result = detect_lof(data, n_neighbors=n_neighbors, contamination=contamination)+ elif method == 'residual':+ threshold = params.get('threshold', 3.0)+ result = detect_residual_anomalies(data, threshold=threshold)+ elif method == 'change_points':+ n_bkps = params.get('n_bkps', 5)+ result = detect_change_points(data, n_bkps=n_bkps)+ else:+ return {"success": False, "error": f"Unknown anomaly method: {method}"}++ # Restructure result to match frontend expectations+ # Frontend expects: { results: { entity_id: { anomalies: [...], n_anomalies, anomaly_rate } } }+ if result.get('success') and 'data' in result:+ # Group anomalies by entity_id+ all_data = result.get('data', [])+ anomalies_list = result.get('anomalies', [])++ # Group by entity_id+ entities_results = {}+ for item in all_data:+ entity_id = item.get('entity_id', 'default')+ if entity_id not in entities_results:+ entities_results[entity_id] = {+ 'anomalies': [],+ 'n_anomalies': 0,+ 'anomaly_rate': 0.0,+ 'total_points': 0+ }+ entities_results[entity_id]['total_points'] += 1+ if item.get('is_anomaly'):+ entities_results[entity_id]['anomalies'].append(item)+ entities_results[entity_id]['n_anomalies'] += 1++ # Calculate anomaly rate per entity+ for entity_id, entity_data in entities_results.items():+ if entity_data['total_points'] > 0:+ entity_data['anomaly_rate'] = entity_data['n_anomalies'] / entity_data['total_points']+ del entity_data['total_points'] # Remove temp field++ return {+ 'success': True,+ 'method': result.get('method', method),+ 'results': entities_results+ }++ return result+ except Exception as e:+ import traceback+ return {"success": False, "error": str(e), "traceback": traceback.format_exc()}+++# ============================================================================+# SEASONALITY COMMAND HANDLERS+# ============================================================================++def run_seasonality_analysis(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run seasonality analysis on time series"""+ if not SEASONALITY_AVAILABLE:+ return {"success": False, "error": "Seasonality analysis not available"}++ try:+ data = parse_panel_data_json(params['data'])+ # Support both 'operation' and 'analysis_type' parameter names+ operation = params.get('operation') or params.get('analysis_type', 'decompose')++ # Map analysis_type values to operation values+ operation_map = {+ 'decompose': 'decompose_stl',+ 'detect': 'detect_period',+ 'strength': 'metrics',+ 'adjust': 'adjust',+ }+ operation = operation_map.get(operation, operation)++ period = params.get('period')+ model_type = params.get('model_type', 'additive')++ if operation == 'detect_period':+ method = params.get('method', 'fft')+ max_period = params.get('max_period', 365)+ result = detect_seasonal_period(data, method=method, max_period=max_period)+ elif operation == 'decompose_stl':+ robust = params.get('robust', True)+ result = decompose_stl(data, period=period, robust=robust)+ elif operation == 'decompose_classical':+ result = decompose_classical(data, period=period, model=model_type)+ elif operation == 'adjust':+ method = params.get('method', 'stl')+ result = seasonally_adjust(data, period=period, method=method)+ elif operation == 'metrics':+ result = calculate_seasonality_metrics(data, period=period)+ else:+ return {"success": False, "error": f"Unknown seasonality operation: {operation}"}++ return result+ except Exception as e:+ import traceback+ return {"success": False, "error": str(e), "traceback": traceback.format_exc()}+++# ============================================================================+# CONFIDENCE INTERVALS COMMAND HANDLERS+# ============================================================================++def run_confidence_intervals(params: Dict[str, Any]) -> Dict[str, Any]:+ """Generate prediction/confidence intervals"""+ if not CONFIDENCE_AVAILABLE:+ return {"success": False, "error": "Confidence intervals not available"}++ try:+ method = params.get('method', 'monte_carlo')+ confidence_levels = params.get('confidence_levels', [0.80, 0.95])++ if method == 'bootstrap':+ data = parse_panel_data_json(params['data'])+ fh = params.get('horizon', 7)+ freq = params.get('frequency', '1d')+ n_bootstrap = params.get('n_bootstrap', 100)++ # Need a forecaster - create a simple one+ def simple_forecaster(y_train, fh, freq):+ last_value = y_train['value'].to_list()[-1]+ last_time = y_train['time'].to_list()[-1]+ delta = timedelta(days=1)+ forecast = []+ for i in range(1, fh + 1):+ forecast.append({+ 'entity_id': y_train['entity_id'].to_list()[0],+ 'time': last_time + (delta * i),+ 'value': last_value+ })+ return {'forecast': forecast}++ result = bootstrap_prediction_intervals(+ data, simple_forecaster, fh=fh,+ n_bootstrap=n_bootstrap, confidence_levels=confidence_levels, freq=freq+ )+ elif method == 'residual':+ data = parse_panel_data_json(params['data'])+ forecast = parse_panel_data_json(params['forecast'])+ y_validation = parse_panel_data_json(params['y_validation']) if 'y_validation' in params else None+ result = residual_prediction_intervals(data, forecast, y_validation, confidence_levels)+ elif method == 'quantile':+ data = parse_panel_data_json(params['data'])+ fh = params.get('horizon', 7)+ lags = params.get('lags', 10)+ quantiles = params.get('quantiles', [0.025, 0.10, 0.50, 0.90, 0.975])+ freq = params.get('frequency', '1d')+ result = quantile_prediction_intervals(data, fh=fh, lags=lags, quantiles=quantiles, freq=freq)+ elif method == 'conformal':+ data = parse_panel_data_json(params['data'])+ forecast = parse_panel_data_json(params['forecast'])+ calibration_size = params.get('calibration_size', 50)+ result = conformal_prediction_intervals(data, forecast, calibration_size, confidence_levels)+ elif method == 'monte_carlo':+ data = parse_panel_data_json(params['data'])+ fh = params.get('horizon', 7)+ n_simulations = params.get('n_simulations', 1000)+ model = params.get('model', 'random_walk')+ freq = params.get('frequency', '1d')+ result = monte_carlo_intervals(data, fh=fh, n_simulations=n_simulations, model=model,+ confidence_levels=confidence_levels, freq=freq)+ else:+ return {"success": False, "error": f"Unknown interval method: {method}"}++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# FEATURE IMPORTANCE COMMAND HANDLERS+# ============================================================================++def run_feature_importance(params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate feature importance for time series"""+ if not FEATURE_IMPORTANCE_AVAILABLE:+ return {"success": False, "error": "Feature importance not available"}++ try:+ data = parse_panel_data_json(params['data'])+ method = params.get('method', 'permutation')+ n_lags = params.get('n_lags', 10)++ if method == 'permutation':+ n_repeats = params.get('n_repeats', 10)+ model_type = params.get('model_type', 'ridge')+ result = calculate_permutation_importance(data, n_lags=n_lags, n_repeats=n_repeats, model_type=model_type)+ elif method == 'model':+ model_type = params.get('model_type', 'ridge')+ result = calculate_model_importance(data, n_lags=n_lags, model_type=model_type)+ elif method == 'shap':+ max_samples = params.get('max_samples', 100)+ result = calculate_shap_importance(data, n_lags=n_lags, max_samples=max_samples)+ elif method == 'lag_analysis':+ max_lags = params.get('max_lags', 20)+ result = analyze_lag_importance(data, max_lags=max_lags)+ elif method == 'sensitivity':+ fh = params.get('horizon', 10)+ perturbation_pct = params.get('perturbation_pct', 0.05)+ freq = params.get('frequency', '1d')++ # Need a forecaster for sensitivity+ def simple_forecaster(y_train, fh, freq):+ last_value = y_train['value'].to_list()[-1]+ last_time = y_train['time'].to_list()[-1]+ delta = timedelta(days=1)+ forecast = []+ for i in range(1, fh + 1):+ forecast.append({+ 'entity_id': y_train['entity_id'].to_list()[0],+ 'time': last_time + (delta * i),+ 'value': last_value+ })+ return {'forecast': forecast}++ result = sensitivity_analysis(data, simple_forecaster, fh=fh,+ perturbation_pct=perturbation_pct, freq=freq)+ else:+ return {"success": False, "error": f"Unknown importance method: {method}"}++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# ADVANCED CROSS-VALIDATION COMMAND HANDLERS+# ============================================================================++def run_advanced_cv(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run advanced cross-validation methods"""+ if not ADVANCED_CV_AVAILABLE:+ return {"success": False, "error": "Advanced CV not available"}++ try:+ data = parse_panel_data_json(params['data'])+ method = params.get('method', 'walk_forward')++ if method == 'blocked':+ n_splits = params.get('n_splits', 5)+ test_size = params.get('test_size', 1)+ gap = params.get('gap', 0)+ result = blocked_time_series_cv(data, n_splits=n_splits, test_size=test_size, gap=gap)+ elif method == 'purged':+ n_splits = params.get('n_splits', 5)+ embargo_pct = params.get('embargo_pct', 0.01)+ purge_pct = params.get('purge_pct', 0.01)+ result = purged_kfold_cv(data, n_splits=n_splits, embargo_pct=embargo_pct, purge_pct=purge_pct)+ elif method == 'combinatorial':+ n_test_splits = params.get('n_test_splits', 2)+ n_groups = params.get('n_groups', 6)+ embargo_pct = params.get('embargo_pct', 0.01)+ result = combinatorial_purged_cv(data, n_test_splits=n_test_splits,+ n_groups=n_groups, embargo_pct=embargo_pct)+ elif method == 'walk_forward':+ initial_train_size = params.get('initial_train_size', 100)+ test_size = params.get('test_size', 1)+ step_size = params.get('step_size', 1)+ anchored = params.get('anchored', False)+ result = walk_forward_validation(data, initial_train_size=initial_train_size,+ test_size=test_size, step_size=step_size, anchored=anchored)+ elif method == 'nested':+ outer_splits = params.get('outer_splits', 5)+ inner_splits = params.get('inner_splits', 3)+ test_size = params.get('test_size', 1)+ result = nested_cv(data, outer_splits=outer_splits, inner_splits=inner_splits, test_size=test_size)+ else:+ return {"success": False, "error": f"Unknown CV method: {method}"}++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}+++# ============================================================================+# BACKTESTING COMMAND HANDLERS+# ============================================================================++def run_backtest(params: Dict[str, Any]) -> Dict[str, Any]:+ """Run backtesting on time series"""+ if not BACKTESTING_AVAILABLE:+ return {"success": False, "error": "Backtesting not available"}++ try:+ data = parse_panel_data_json(params['data'])+ operation = params.get('operation', 'walk_forward')+ freq = params.get('frequency', '1d')++ # Create a simple forecaster+ def simple_forecaster(y_train, fh, freq):+ last_value = y_train['value'].to_list()[-1]+ last_time = y_train['time'].to_list()[-1]+ delta = timedelta(days=1)+ forecast = []+ for i in range(1, fh + 1):+ forecast.append({+ 'entity_id': y_train['entity_id'].to_list()[0],+ 'time': last_time + (delta * i),+ 'value': last_value+ })+ return {'forecast': forecast}++ if operation == 'walk_forward':+ initial_train_size = params.get('initial_train_size', 100)+ test_size = params.get('test_size', 1)+ step_size = params.get('step_size', 1)+ horizons = params.get('horizons')+ retrain = params.get('retrain', True)+ result = walk_forward_backtest(data, simple_forecaster, initial_train_size=initial_train_size,+ test_size=test_size, step_size=step_size,+ horizons=horizons, freq=freq, retrain=retrain)+ elif operation == 'compare_models':+ initial_train_size = params.get('initial_train_size', 100)+ test_size = params.get('test_size', 1)+ step_size = params.get('step_size', 5)+ # Use simple forecasters for comparison+ forecasters = {'naive': simple_forecaster}+ result = compare_models_backtest(data, forecasters, initial_train_size=initial_train_size,+ test_size=test_size, step_size=step_size, freq=freq)+ elif operation == 'rolling_origin':+ min_train_size = params.get('min_train_size', 50)+ max_train_size = params.get('max_train_size')+ test_size = params.get('test_size', 1)+ result = rolling_origin_evaluation(data, simple_forecaster, min_train_size=min_train_size,+ max_train_size=max_train_size, test_size=test_size, freq=freq)+ elif operation == 'attribution':+ backtest_results = params.get('backtest_results', {})+ result = performance_attribution(backtest_results)+ elif operation == 'summary':+ backtest_results = params.get('backtest_results', {})+ result = backtest_summary(backtest_results)+ else:+ return {"success": False, "error": f"Unknown backtest operation: {operation}"}++ return result+ except Exception as e:+ return {"success": False, "error": str(e)}++# ============================================================================# MAIN ENTRY POINT# ============================================================================@@ -724,6 +1306,23 @@ COMMANDS = {"add_features": add_features,"seasonal_period": get_seasonal_period,"full_pipeline": full_forecast_pipeline,+ # Advanced models+ "advanced_forecast": run_advanced_forecast,+ # Ensemble methods+ "ensemble": run_ensemble,+ "auto_ensemble": run_auto_ensemble,+ # Anomaly detection+ "anomaly_detection": run_anomaly_detection,+ # Seasonality analysis+ "seasonality": run_seasonality_analysis,+ # Confidence intervals+ "confidence_intervals": run_confidence_intervals,+ # Feature importance+ "feature_importance": run_feature_importance,+ # Advanced cross-validation+ "advanced_cv": run_advanced_cv,+ # Backtesting+ "backtest": run_backtest,}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/seasonality.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/seasonality.pynew file mode 100644index 000000000..460f4cfd2--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/functime_wrapper/seasonality.py@@ -0,0 +1,549 @@+"""+Seasonality Analysis Module+============================++Provides seasonal decomposition and analysis:+- STL decomposition (Seasonal-Trend-Loess)+- Classical decomposition+- Seasonal period detection+- Seasonal adjustment/deseasonalization+- Seasonality strength measurement++Essential for understanding time series patterns.+"""++import polars as pl+import numpy as np+from typing import Dict, List, Optional, Union, Any, Tuple+from datetime import datetime, timedelta+from scipy import signal+from scipy import fft+import warnings++warnings.filterwarnings('ignore')++# Try importing statsmodels for STL+try:+ from statsmodels.tsa.seasonal import STL, seasonal_decompose+ STATSMODELS_AVAILABLE = True+except ImportError:+ STATSMODELS_AVAILABLE = False+++# ============================================================================+# SEASONAL PERIOD DETECTION+# ============================================================================++def detect_seasonal_period(+ y: pl.DataFrame,+ method: str = 'fft',+ max_period: int = 365+) -> Dict[str, Any]:+ """+ Automatically detect the seasonal period of time series.++ Args:+ y: Panel data+ method: 'fft' (spectral), 'acf' (autocorrelation), or 'both'+ max_period: Maximum period to consider+ """+ results = {}+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ if len(values) < 10:+ results[entity_id] = {'period': None, 'strength': 0.0}+ continue++ periods = {}++ if method in ['fft', 'both']:+ fft_period, fft_strength = _detect_period_fft(values, max_period)+ periods['fft'] = {'period': fft_period, 'strength': fft_strength}++ if method in ['acf', 'both']:+ acf_period, acf_strength = _detect_period_acf(values, max_period)+ periods['acf'] = {'period': acf_period, 'strength': acf_strength}++ # Use the method with highest strength+ best_method = max(periods.items(), key=lambda x: x[1]['strength'])+ results[entity_id] = {+ 'period': best_method[1]['period'],+ 'strength': best_method[1]['strength'],+ 'method': best_method[0],+ 'all_methods': periods+ }++ return {+ 'success': True,+ 'method': method,+ 'max_period': max_period,+ 'results': results+ }+++def _detect_period_fft(values: np.ndarray, max_period: int) -> Tuple[Optional[int], float]:+ """Detect period using FFT (spectral analysis)."""+ n = len(values)++ # Detrend+ detrended = signal.detrend(values)++ # Apply FFT+ fft_result = np.abs(fft.fft(detrended))+ freqs = fft.fftfreq(n)++ # Find dominant frequency (excluding DC component)+ half_n = n // 2+ magnitudes = fft_result[1:half_n]+ frequencies = freqs[1:half_n]++ # Filter to valid periods+ valid_mask = (1.0 / np.abs(frequencies)) <= max_period+ if not np.any(valid_mask):+ return None, 0.0++ magnitudes = magnitudes[valid_mask]+ frequencies = frequencies[valid_mask]++ if len(magnitudes) == 0:+ return None, 0.0++ # Find peak+ peak_idx = np.argmax(magnitudes)+ peak_freq = frequencies[peak_idx]+ period = int(round(1.0 / abs(peak_freq))) if peak_freq != 0 else None++ # Calculate strength as ratio of peak to mean+ strength = float(magnitudes[peak_idx] / np.mean(magnitudes)) if np.mean(magnitudes) > 0 else 0.0++ return period, min(strength / 10, 1.0) # Normalize to 0-1+++def _detect_period_acf(values: np.ndarray, max_period: int) -> Tuple[Optional[int], float]:+ """Detect period using autocorrelation."""+ n = len(values)+ max_lag = min(max_period, n // 2)++ # Detrend+ detrended = signal.detrend(values)++ # Calculate ACF+ acf = np.correlate(detrended, detrended, mode='full')+ acf = acf[n-1:] # Keep positive lags only+ acf = acf / acf[0] # Normalize++ # Find peaks in ACF (excluding lag 0)+ acf_subset = acf[1:max_lag+1]++ if len(acf_subset) < 3:+ return None, 0.0++ # Find local maxima+ peaks, _ = signal.find_peaks(acf_subset, height=0.1)++ if len(peaks) == 0:+ return None, 0.0++ # First significant peak is likely the period+ period = int(peaks[0] + 1)+ strength = float(acf_subset[peaks[0]])++ return period, strength+++# ============================================================================+# SEASONAL DECOMPOSITION+# ============================================================================++def decompose_stl(+ y: pl.DataFrame,+ period: Optional[int] = None,+ robust: bool = True+) -> Dict[str, Any]:+ """+ STL (Seasonal-Trend-Loess) decomposition.++ Args:+ y: Panel data+ period: Seasonal period (auto-detected if None)+ robust: Use robust fitting (less sensitive to outliers)+ """+ if not STATSMODELS_AVAILABLE:+ return _fallback_decomposition(y, period)++ results = {}+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ # Auto-detect period if not provided+ if period is None:+ detected = detect_seasonal_period(+ entity_data.select(['entity_id', 'time', 'value']),+ method='fft'+ )+ period = detected['results'].get(entity_id, {}).get('period', 7)+ if period is None or period < 2:+ period = 7 # Default to weekly++ if len(values) < 2 * period:+ results[entity_id] = {+ 'error': 'Insufficient data for decomposition',+ 'trend': values.tolist(),+ 'seasonal': [0.0] * len(values),+ 'residual': [0.0] * len(values)+ }+ continue++ try:+ stl = STL(values, period=period, robust=robust)+ result = stl.fit()++ results[entity_id] = {+ 'trend': result.trend.tolist(),+ 'seasonal': result.seasonal.tolist(),+ 'residual': result.resid.tolist(),+ 'times': [str(t) for t in times],+ 'period': period,+ 'seasonal_strength': _calculate_seasonal_strength(result.seasonal, result.resid)+ }+ except Exception as e:+ results[entity_id] = {+ 'error': str(e),+ 'trend': values.tolist(),+ 'seasonal': [0.0] * len(values),+ 'residual': [0.0] * len(values)+ }++ return {+ 'success': True,+ 'method': 'stl',+ 'period': period,+ 'robust': robust,+ 'results': results+ }+++def decompose_classical(+ y: pl.DataFrame,+ period: Optional[int] = None,+ model: str = 'additive'+) -> Dict[str, Any]:+ """+ Classical seasonal decomposition (moving average based).++ Args:+ y: Panel data+ period: Seasonal period+ model: 'additive' or 'multiplicative'+ """+ if not STATSMODELS_AVAILABLE:+ return _fallback_decomposition(y, period)++ results = {}+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()++ if period is None:+ period = 7++ if len(values) < 2 * period:+ results[entity_id] = {'error': 'Insufficient data'}+ continue++ try:+ # For multiplicative, ensure positive values+ if model == 'multiplicative' and np.any(values <= 0):+ model = 'additive'++ result = seasonal_decompose(values, period=period, model=model)++ results[entity_id] = {+ 'trend': np.nan_to_num(result.trend, nan=0.0).tolist(),+ 'seasonal': np.nan_to_num(result.seasonal, nan=0.0).tolist(),+ 'residual': np.nan_to_num(result.resid, nan=0.0).tolist(),+ 'times': [str(t) for t in times],+ 'period': period,+ 'model': model+ }+ except Exception as e:+ results[entity_id] = {'error': str(e)}++ return {+ 'success': True,+ 'method': 'classical',+ 'period': period,+ 'model': model,+ 'results': results+ }+++def _fallback_decomposition(+ y: pl.DataFrame,+ period: Optional[int] = None+) -> Dict[str, Any]:+ """Simple decomposition without statsmodels."""+ if period is None:+ period = 7++ results = {}+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()+ times = entity_data['time'].to_list()+ n = len(values)++ # Simple moving average for trend+ if n >= period:+ trend = np.convolve(values, np.ones(period)/period, mode='same')+ else:+ trend = values.copy()++ # Seasonal: group by position in period+ detrended = values - trend+ seasonal = np.zeros(n)+ for i in range(period):+ indices = range(i, n, period)+ if len(indices) > 0:+ mean_seasonal = np.mean([detrended[j] for j in indices])+ for j in indices:+ seasonal[j] = mean_seasonal++ # Residual+ residual = values - trend - seasonal++ results[entity_id] = {+ 'trend': trend.tolist(),+ 'seasonal': seasonal.tolist(),+ 'residual': residual.tolist(),+ 'times': [str(t) for t in times],+ 'period': period+ }++ return {+ 'success': True,+ 'method': 'fallback',+ 'period': period,+ 'results': results+ }+++def _calculate_seasonal_strength(seasonal: np.ndarray, residual: np.ndarray) -> float:+ """Calculate strength of seasonality (0 to 1)."""+ var_seasonal = np.var(seasonal)+ var_residual = np.var(residual)+ total_var = var_seasonal + var_residual++ if total_var == 0:+ return 0.0++ return float(max(0, 1 - var_residual / total_var))+++# ============================================================================+# SEASONAL ADJUSTMENT+# ============================================================================++def seasonally_adjust(+ y: pl.DataFrame,+ period: Optional[int] = None,+ method: str = 'stl'+) -> Dict[str, Any]:+ """+ Remove seasonal component from time series (deseasonalize).++ Args:+ y: Panel data+ period: Seasonal period+ method: 'stl' or 'classical'+ """+ if method == 'stl':+ decomp = decompose_stl(y, period=period)+ else:+ decomp = decompose_classical(y, period=period)++ if not decomp['success']:+ return decomp++ result_rows = []+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ times = entity_data['time'].to_list()+ values = entity_data['value'].to_numpy()++ entity_result = decomp['results'].get(entity_id, {})+ if 'error' in entity_result:+ # Use original values if decomposition failed+ adjusted = values+ else:+ seasonal = np.array(entity_result['seasonal'])+ adjusted = values - seasonal++ for t, v, adj in zip(times, values, adjusted):+ result_rows.append({+ 'entity_id': entity_id,+ 'time': t,+ 'original': float(v),+ 'adjusted': float(adj)+ })++ result = pl.DataFrame(result_rows)++ return {+ 'success': True,+ 'method': f'seasonal_adjustment_{method}',+ 'data': result.to_dicts(),+ 'shape': result.shape+ }+++# ============================================================================+# SEASONALITY METRICS+# ============================================================================++def calculate_seasonality_metrics(+ y: pl.DataFrame,+ period: Optional[int] = None+) -> Dict[str, Any]:+ """+ Calculate comprehensive seasonality metrics.+ """+ # Detect period if not provided+ if period is None:+ detected = detect_seasonal_period(y, method='both')+ else:+ detected = {'results': {}}++ # Decompose+ decomp = decompose_stl(y, period=period)++ metrics = {}+ entities = y['entity_id'].unique().to_list()++ for entity_id in entities:+ entity_data = y.filter(pl.col('entity_id') == entity_id).sort('time')+ values = entity_data['value'].to_numpy()++ entity_decomp = decomp['results'].get(entity_id, {})+ detected_result = detected.get('results', {}).get(entity_id, {})++ if 'error' in entity_decomp:+ metrics[entity_id] = {'error': entity_decomp['error']}+ continue++ seasonal = np.array(entity_decomp['seasonal'])+ residual = np.array(entity_decomp['residual'])+ trend = np.array(entity_decomp['trend'])++ # Calculate metrics+ seasonal_strength = _calculate_seasonal_strength(seasonal, residual)+ trend_strength = _calculate_trend_strength(trend, residual)++ # Seasonal indices+ used_period = entity_decomp.get('period', period or 7)+ seasonal_indices = []+ for i in range(used_period):+ indices = range(i, len(seasonal), used_period)+ if len(indices) > 0:+ seasonal_indices.append(float(np.mean([seasonal[j] for j in indices])))++ metrics[entity_id] = {+ 'detected_period': detected_result.get('period'),+ 'used_period': used_period,+ 'seasonal_strength': seasonal_strength,+ 'trend_strength': trend_strength,+ 'seasonal_indices': seasonal_indices,+ 'is_seasonal': seasonal_strength > 0.3,+ 'is_trending': trend_strength > 0.3+ }++ return {+ 'success': True,+ 'metrics': metrics+ }+++def _calculate_trend_strength(trend: np.ndarray, residual: np.ndarray) -> float:+ """Calculate strength of trend (0 to 1)."""+ var_trend = np.var(np.diff(trend)) # Variance of trend changes+ var_residual = np.var(residual)+ total_var = var_trend + var_residual++ if total_var == 0:+ return 0.0++ return float(max(0, 1 - var_residual / total_var))+++def main():+ """Test seasonality analysis."""+ print("Testing Seasonality Analysis Module")+ print("=" * 50)++ # Create sample data with seasonality+ dates = pl.datetime_range(+ start=pl.datetime(2020, 1, 1),+ end=pl.datetime(2020, 12, 31),+ interval='1d',+ eager=True+ ).to_list()++ n = len(dates)+ np.random.seed(42)++ # Add weekly seasonality and trend+ values = [+ 100 + 0.1 * i + # Trend+ 10 * np.sin(2 * np.pi * i / 7) + # Weekly seasonality+ np.random.randn() * 2 # Noise+ for i in range(n)+ ]++ df = pl.DataFrame({+ 'entity_id': ['A'] * n,+ 'time': dates,+ 'value': values+ })++ # Test period detection+ period_result = detect_seasonal_period(df, method='both')+ print(f"Detected period: {period_result['results']['A'].get('period')}")+ print(f"Seasonality strength: {period_result['results']['A'].get('strength', 0):.3f}")++ # Test STL decomposition+ stl_result = decompose_stl(df, period=7)+ if 'A' in stl_result['results']:+ print(f"STL decomposition successful")+ print(f"Seasonal strength: {stl_result['results']['A'].get('seasonal_strength', 0):.3f}")++ # Test seasonal adjustment+ adj_result = seasonally_adjust(df, period=7)+ print(f"Seasonal adjustment: {adj_result['shape'][0]} rows")++ # Test seasonality metrics+ metrics = calculate_seasonality_metrics(df)+ if 'A' in metrics['metrics']:+ m = metrics['metrics']['A']+ print(f"Is seasonal: {m.get('is_seasonal')}")+ print(f"Is trending: {m.get('is_trending')}")++ print("\nAll tests: PASSED")+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rsindex 09153124a..53170631e 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/ffn_analytics.rs@@ -152,3 +152,46 @@ pub async fn ffn_full_analysis(let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;python_runtime::execute_python_script(&script_path, args)}++/// Portfolio optimization - calculate optimal weights using various methods+#[tauri::command]+pub async fn ffn_portfolio_optimization(+ app: tauri::AppHandle,+ prices_json: String,+ method: Option<String>,+ risk_free_rate: Option<f64>,+ weight_bounds: Option<Vec<f64>>,+) -> Result<String, String> {+ let bounds = weight_bounds.unwrap_or_else(|| vec![0.0, 1.0]);+ let params = serde_json::json!({+ "prices": prices_json,+ "method": method.unwrap_or_else(|| "erc".to_string()),+ "risk_free_rate": risk_free_rate.unwrap_or(0.0),+ "weight_bounds": bounds+ });++ let args = vec!["portfolio_optimization".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Benchmark comparison - compare portfolio against a benchmark+#[tauri::command]+pub async fn ffn_benchmark_comparison(+ app: tauri::AppHandle,+ prices_json: String,+ benchmark_prices_json: String,+ benchmark_name: Option<String>,+ risk_free_rate: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "prices": prices_json,+ "benchmark_prices": benchmark_prices_json,+ "benchmark_name": benchmark_name.unwrap_or_else(|| "Benchmark".to_string()),+ "risk_free_rate": risk_free_rate.unwrap_or(0.0)+ });++ let args = vec!["benchmark_comparison".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/ffn_wrapper/ffn_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rsnew file mode 100644index 000000000..998aa46fa--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/fortitudo_analytics.rs@@ -0,0 +1,303 @@+// Fortitudo.tech Analytics Commands - Portfolio risk analytics via PyO3+#![allow(dead_code)]+use crate::python_runtime;+use crate::utils::python::get_script_path;++// ============================================================================+// FORTITUDO ANALYTICS COMMANDS+// ============================================================================++/// Check fortitudo.tech library status and availability+#[tauri::command]+pub async fn fortitudo_check_status(app: tauri::AppHandle) -> Result<String, String> {+ let args = vec!["check_status".to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate comprehensive portfolio risk metrics (VaR, CVaR, volatility, Sharpe)+#[tauri::command]+pub async fn fortitudo_portfolio_metrics(+ app: tauri::AppHandle,+ returns_json: String,+ weights_json: String,+ alpha: Option<f64>,+ probabilities: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "weights": weights_json,+ "alpha": alpha.unwrap_or(0.05),+ "probabilities": probabilities+ });++ let args = vec!["portfolio_metrics".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate covariance and correlation matrices with statistical moments+#[tauri::command]+pub async fn fortitudo_covariance_analysis(+ app: tauri::AppHandle,+ returns_json: String,+ probabilities: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "probabilities": probabilities+ });++ let args = vec!["covariance_analysis".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate exponentially decaying probabilities for scenario weighting+#[tauri::command]+pub async fn fortitudo_exp_decay_weighting(+ app: tauri::AppHandle,+ returns_json: String,+ half_life: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "half_life": half_life.unwrap_or(252)+ });++ let args = vec!["exp_decay_weighting".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Price options using Black-Scholes model+#[tauri::command]+pub async fn fortitudo_option_pricing(+ app: tauri::AppHandle,+ spot_price: f64,+ strike: f64,+ volatility: f64,+ risk_free_rate: Option<f64>,+ dividend_yield: Option<f64>,+ time_to_maturity: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "spot_price": spot_price,+ "strike": strike,+ "volatility": volatility,+ "risk_free_rate": risk_free_rate.unwrap_or(0.05),+ "dividend_yield": dividend_yield.unwrap_or(0.0),+ "time_to_maturity": time_to_maturity.unwrap_or(1.0)+ });++ let args = vec!["option_pricing".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Generate option chain for multiple strikes+#[tauri::command]+pub async fn fortitudo_option_chain(+ app: tauri::AppHandle,+ spot_price: f64,+ volatility: f64,+ strikes: Option<Vec<f64>>,+ risk_free_rate: Option<f64>,+ dividend_yield: Option<f64>,+ time_to_maturity: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "spot_price": spot_price,+ "volatility": volatility,+ "strikes": strikes,+ "risk_free_rate": risk_free_rate.unwrap_or(0.05),+ "dividend_yield": dividend_yield.unwrap_or(0.0),+ "time_to_maturity": time_to_maturity.unwrap_or(1.0)+ });++ let args = vec!["option_chain".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Apply entropy pooling for scenario probability adjustment+#[tauri::command]+pub async fn fortitudo_entropy_pooling(+ app: tauri::AppHandle,+ n_scenarios: i32,+ max_probability: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "n_scenarios": n_scenarios,+ "max_probability": max_probability+ });++ let args = vec!["entropy_pooling".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate exposure stacking portfolio from sample portfolios+#[tauri::command]+pub async fn fortitudo_exposure_stacking(+ app: tauri::AppHandle,+ sample_portfolios_json: String,+ n_partitions: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "sample_portfolios": sample_portfolios_json,+ "n_partitions": n_partitions.unwrap_or(4)+ });++ let args = vec!["exposure_stacking".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Full portfolio risk analysis combining all metrics+#[tauri::command]+pub async fn fortitudo_full_analysis(+ app: tauri::AppHandle,+ returns_json: String,+ weights_json: String,+ alpha: Option<f64>,+ half_life: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "weights": weights_json,+ "alpha": alpha.unwrap_or(0.05),+ "half_life": half_life.unwrap_or(252)+ });++ let args = vec!["full_analysis".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate option Greeks (Delta, Gamma, Vega, Theta, Rho)+#[tauri::command]+pub async fn fortitudo_option_greeks(+ app: tauri::AppHandle,+ spot_price: f64,+ strike: f64,+ volatility: f64,+ risk_free_rate: Option<f64>,+ dividend_yield: Option<f64>,+ time_to_maturity: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "spot_price": spot_price,+ "strike": strike,+ "volatility": volatility,+ "risk_free_rate": risk_free_rate.unwrap_or(0.05),+ "dividend_yield": dividend_yield.unwrap_or(0.0),+ "time_to_maturity": time_to_maturity.unwrap_or(1.0)+ });++ let args = vec!["option_greeks".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Mean-Variance portfolio optimization+#[tauri::command]+pub async fn fortitudo_optimize_mean_variance(+ app: tauri::AppHandle,+ returns_json: String,+ objective: Option<String>,+ long_only: Option<bool>,+ max_weight: Option<f64>,+ min_weight: Option<f64>,+ risk_free_rate: Option<f64>,+ target_return: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "objective": objective.unwrap_or_else(|| "min_variance".to_string()),+ "long_only": long_only.unwrap_or(true),+ "max_weight": max_weight,+ "min_weight": min_weight,+ "risk_free_rate": risk_free_rate.unwrap_or(0.0),+ "target_return": target_return+ });++ let args = vec!["optimize_mean_variance".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Mean-CVaR portfolio optimization+#[tauri::command]+pub async fn fortitudo_optimize_mean_cvar(+ app: tauri::AppHandle,+ returns_json: String,+ objective: Option<String>,+ alpha: Option<f64>,+ long_only: Option<bool>,+ max_weight: Option<f64>,+ min_weight: Option<f64>,+ risk_free_rate: Option<f64>,+ target_return: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "objective": objective.unwrap_or_else(|| "min_cvar".to_string()),+ "alpha": alpha.unwrap_or(0.05),+ "long_only": long_only.unwrap_or(true),+ "max_weight": max_weight,+ "min_weight": min_weight,+ "risk_free_rate": risk_free_rate.unwrap_or(0.0),+ "target_return": target_return+ });++ let args = vec!["optimize_mean_cvar".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Generate Mean-Variance efficient frontier+#[tauri::command]+pub async fn fortitudo_efficient_frontier_mv(+ app: tauri::AppHandle,+ returns_json: String,+ n_points: Option<i32>,+ long_only: Option<bool>,+ max_weight: Option<f64>,+ risk_free_rate: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "n_points": n_points.unwrap_or(20),+ "long_only": long_only.unwrap_or(true),+ "max_weight": max_weight,+ "risk_free_rate": risk_free_rate.unwrap_or(0.0)+ });++ let args = vec!["efficient_frontier_mv".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Generate Mean-CVaR efficient frontier+#[tauri::command]+pub async fn fortitudo_efficient_frontier_cvar(+ app: tauri::AppHandle,+ returns_json: String,+ n_points: Option<i32>,+ alpha: Option<f64>,+ long_only: Option<bool>,+ max_weight: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "returns": returns_json,+ "n_points": n_points.unwrap_or(20),+ "alpha": alpha.unwrap_or(0.05),+ "long_only": long_only.unwrap_or(true),+ "max_weight": max_weight+ });++ let args = vec!["efficient_frontier_cvar".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/fortitudo_tech_wrapper/fortitudo_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rsindex f2bb65e0b..637995b57 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/functime_analytics.rs@@ -184,3 +184,237 @@ pub async fn functime_full_pipeline(let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;python_runtime::execute_python_script(&script_path, args)}++// ============================================================================+// ADVANCED FUNCTIME COMMANDS+// ============================================================================++/// Advanced forecasting with additional models (naive, ses, holt, theta, croston, xgboost, catboost)+#[tauri::command]+pub async fn functime_advanced_forecast(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ horizon: Option<i32>,+ frequency: Option<String>,+ seasonal_period: Option<i32>,+ alpha: Option<f64>,+ beta: Option<f64>,+ theta: Option<f64>,+ lags: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "naive".to_string()),+ "horizon": horizon.unwrap_or(7),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string()),+ "seasonal_period": seasonal_period.unwrap_or(7),+ "alpha": alpha.unwrap_or(0.3),+ "beta": beta.unwrap_or(0.1),+ "theta": theta.unwrap_or(2.0),+ "lags": lags.unwrap_or(10)+ });++ let args = vec!["advanced_forecast".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Ensemble forecasting combining multiple models+#[tauri::command]+pub async fn functime_ensemble(+ app: tauri::AppHandle,+ data_json: String,+ models: Option<Vec<String>>,+ weights: Option<Vec<f64>>,+ horizon: Option<i32>,+ frequency: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "models": models.unwrap_or_else(|| vec!["naive".to_string(), "ses".to_string(), "linear".to_string()]),+ "weights": weights,+ "horizon": horizon.unwrap_or(7),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string())+ });++ let args = vec!["ensemble".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Automatic ensemble with weight optimization+#[tauri::command]+pub async fn functime_auto_ensemble(+ app: tauri::AppHandle,+ data_json: String,+ horizon: Option<i32>,+ frequency: Option<String>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "horizon": horizon.unwrap_or(7),+ "frequency": frequency.unwrap_or_else(|| "1d".to_string())+ });++ let args = vec!["auto_ensemble".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Anomaly detection in time series+#[tauri::command]+pub async fn functime_anomaly_detection(+ app: tauri::AppHandle,+ data_json: String,+ method: Option<String>,+ threshold: Option<f64>,+ window_size: Option<i32>,+ contamination: Option<f64>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "method": method.unwrap_or_else(|| "zscore".to_string()),+ "threshold": threshold.unwrap_or(3.0),+ "window_size": window_size.unwrap_or(10),+ "contamination": contamination.unwrap_or(0.1)+ });++ let args = vec!["anomaly_detection".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Seasonality analysis (decomposition, strength, detection)+#[tauri::command]+pub async fn functime_seasonality(+ app: tauri::AppHandle,+ data_json: String,+ // Accept both parameter naming conventions from frontend+ operation: Option<String>,+ analysis_type: Option<String>,+ period: Option<i32>,+ method: Option<String>,+ max_period: Option<i32>,+ robust: Option<bool>,+ model: Option<String>,+ model_type: Option<String>,+) -> Result<String, String> {+ // Use 'operation' if provided, fall back to 'analysis_type', then default+ let op = operation+ .or(analysis_type)+ .unwrap_or_else(|| "decompose".to_string());++ // Use 'model' if provided, fall back to 'model_type', then default+ let model_val = model+ .or(model_type)+ .unwrap_or_else(|| "additive".to_string());++ let params = serde_json::json!({+ "data": data_json,+ "operation": op,+ "period": period,+ "method": method.unwrap_or_else(|| "fft".to_string()),+ "max_period": max_period.unwrap_or(365),+ "robust": robust.unwrap_or(true),+ "model_type": model_val+ });++ let args = vec!["seasonality".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Calculate confidence intervals for forecasts+#[tauri::command]+pub async fn functime_confidence_intervals(+ app: tauri::AppHandle,+ data_json: String,+ method: Option<String>,+ confidence_level: Option<f64>,+ horizon: Option<i32>,+ n_bootstrap: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "method": method.unwrap_or_else(|| "bootstrap".to_string()),+ "confidence_level": confidence_level.unwrap_or(0.95),+ "horizon": horizon.unwrap_or(7),+ "n_bootstrap": n_bootstrap.unwrap_or(100)+ });++ let args = vec!["confidence_intervals".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Feature importance analysis for ML models+#[tauri::command]+pub async fn functime_feature_importance(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ method: Option<String>,+ lags: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "lightgbm".to_string()),+ "method": method.unwrap_or_else(|| "shap".to_string()),+ "lags": lags.unwrap_or(10)+ });++ let args = vec!["feature_importance".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Advanced cross-validation with model evaluation+#[tauri::command]+pub async fn functime_advanced_cv(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ cv_method: Option<String>,+ n_splits: Option<i32>,+ horizon: Option<i32>,+ gap: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "linear".to_string()),+ "cv_method": cv_method.unwrap_or_else(|| "expanding".to_string()),+ "n_splits": n_splits.unwrap_or(5),+ "horizon": horizon.unwrap_or(7),+ "gap": gap.unwrap_or(0)+ });++ let args = vec!["advanced_cv".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}++/// Strategy backtesting for forecasting models+#[tauri::command]+pub async fn functime_backtest(+ app: tauri::AppHandle,+ data_json: String,+ model: Option<String>,+ strategy: Option<String>,+ initial_capital: Option<f64>,+ horizon: Option<i32>,+ refit_frequency: Option<i32>,+) -> Result<String, String> {+ let params = serde_json::json!({+ "data": data_json,+ "model": model.unwrap_or_else(|| "linear".to_string()),+ "strategy": strategy.unwrap_or_else(|| "long_only".to_string()),+ "initial_capital": initial_capital.unwrap_or(10000.0),+ "horizon": horizon.unwrap_or(7),+ "refit_frequency": refit_frequency.unwrap_or(30)+ });++ let args = vec!["backtest".to_string(), params.to_string()];+ let script_path = get_script_path(&app, "Analytics/functime_wrapper/functime_service.py")?;+ python_runtime::execute_python_script(&script_path, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 6904b0192..94bc5ff26 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -113,6 +113,9 @@ pub mod ai_quant_lab;// FFN Analytics - Portfolio Performance Analysispub mod ffn_analytics;+// Fortitudo.tech Analytics - Portfolio Risk Analytics+pub mod fortitudo_analytics;+// Functime Analytics - Time Series Forecastingpub mod functime_analytics;diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 86208cc21..7b69f2c66 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1646,6 +1646,23 @@ pub fn run() {commands::ffn_analytics::ffn_compare_assets,commands::ffn_analytics::ffn_risk_metrics,commands::ffn_analytics::ffn_full_analysis,+ commands::ffn_analytics::ffn_portfolio_optimization,+ commands::ffn_analytics::ffn_benchmark_comparison,+ // Fortitudo.tech Analytics - Portfolio Risk Analytics Commands+ commands::fortitudo_analytics::fortitudo_check_status,+ commands::fortitudo_analytics::fortitudo_portfolio_metrics,+ commands::fortitudo_analytics::fortitudo_covariance_analysis,+ commands::fortitudo_analytics::fortitudo_exp_decay_weighting,+ commands::fortitudo_analytics::fortitudo_option_pricing,+ commands::fortitudo_analytics::fortitudo_option_chain,+ commands::fortitudo_analytics::fortitudo_option_greeks,+ commands::fortitudo_analytics::fortitudo_entropy_pooling,+ commands::fortitudo_analytics::fortitudo_exposure_stacking,+ commands::fortitudo_analytics::fortitudo_full_analysis,+ commands::fortitudo_analytics::fortitudo_optimize_mean_variance,+ commands::fortitudo_analytics::fortitudo_optimize_mean_cvar,+ commands::fortitudo_analytics::fortitudo_efficient_frontier_mv,+ commands::fortitudo_analytics::fortitudo_efficient_frontier_cvar,// Functime Analytics - Time Series Forecasting Commandscommands::functime_analytics::functime_check_status,commands::functime_analytics::functime_forecast,@@ -1655,6 +1672,16 @@ pub fn run() {commands::functime_analytics::functime_add_features,commands::functime_analytics::functime_seasonal_period,commands::functime_analytics::functime_full_pipeline,+ // Advanced Functime Commands+ commands::functime_analytics::functime_advanced_forecast,+ commands::functime_analytics::functime_ensemble,+ commands::functime_analytics::functime_auto_ensemble,+ commands::functime_analytics::functime_anomaly_detection,+ commands::functime_analytics::functime_seasonality,+ commands::functime_analytics::functime_confidence_intervals,+ commands::functime_analytics::functime_feature_importance,+ commands::functime_analytics::functime_advanced_cv,+ commands::functime_analytics::functime_backtest,// High-Performance OrderBook Processing Commandscommands::orderbook::merge_orderbook,commands::orderbook::update_orderbook_snapshot,diff --git a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsxindex d270be113..922c732a9 100644--- a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx+++ b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx@@ -157,11 +157,11 @@ export const PolymarketCredentialsPanel: React.FC = () => {const generateAPICredentials = async (address: string) => {try {- // Import ethers dynamically- const { ethers } = await import('ethers');+ // Import ethers dynamically (v6 API)+ const { BrowserProvider } = await import('ethers');- const provider = new ethers.providers.Web3Provider(window.ethereum as any);- const signer = provider.getSigner();+ const provider = new BrowserProvider(window.ethereum as any);+ const signer = await provider.getSigner();// EIP-712 domain and types for Polymarketconst domain = {@@ -185,8 +185,8 @@ export const PolymarketCredentialsPanel: React.FC = () => {message: 'Please sign the message in MetaMask...'});- // Request signature from user- const signature = await signer._signTypedData(domain, types, value);+ // Request signature from user (v6 API uses signTypedData)+ const signature = await signer.signTypedData(domain, types, value);setTestResult({success: true,diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsxindex fa83c0ac0..924118ae2 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/AIQuantLabTab.tsx@@ -34,6 +34,7 @@ import { BacktestingPanel } from './BacktestingPanel';import { LiveSignalsPanel } from './LiveSignalsPanel';import { FFNAnalyticsPanel } from './FFNAnalyticsPanel';import { FunctimePanel } from './FunctimePanel';+import { FortitudoPanel } from './FortitudoPanel';import { StatusBar } from './StatusBar';// Bloomberg Professional Color Palette - Consistent across all tabs@@ -55,7 +56,7 @@ const BLOOMBERG = {MUTED: '#4A4A4A'};-type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'ffn_analytics' | 'functime';+type ViewMode = 'factor_discovery' | 'model_library' | 'backtesting' | 'live_signals' | 'ffn_analytics' | 'functime' | 'fortitudo';export default function AIQuantLabTab() {// State@@ -198,7 +199,8 @@ export default function AIQuantLabTab() {{ id: 'backtesting', label: 'BACKTESTING', icon: BarChart3, description: 'Strategy validation & analysis' },{ id: 'live_signals', label: 'LIVE SIGNALS', icon: Activity, description: 'Real-time predictions' },{ id: 'ffn_analytics', label: 'FFN ANALYTICS', icon: TrendingUp, description: 'Portfolio performance & risk metrics' },- { id: 'functime', label: 'FUNCTIME', icon: Zap, description: 'ML time series forecasting' }+ { id: 'functime', label: 'FUNCTIME', icon: Zap, description: 'ML time series forecasting' },+ { id: 'fortitudo', label: 'FORTITUDO', icon: Database, description: 'VaR, CVaR, option pricing, entropy pooling' }];const bothInitialized = qlibStatus.initialized && rdAgentStatus.initialized;@@ -320,11 +322,13 @@ export default function AIQuantLabTab() {{/* Main Content Area */}<div className="flex-1 overflow-hidden relative">- {/* FFN Analytics and Functime are always available - independent of Qlib/RDAgent */}+ {/* FFN Analytics, Functime, and Fortitudo are always available - independent of Qlib/RDAgent */}{activeView === 'ffn_analytics' ? (<FFNAnalyticsPanel />) : activeView === 'functime' ? (<FunctimePanel />+ ) : activeView === 'fortitudo' ? (+ <FortitudoPanel />) : !bothAvailable ? (<InstallationGuide />) : !bothInitialized ? (diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsxindex 8e133d8b9..49462045e 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx@@ -2,9 +2,20 @@* FFN Analytics Panel - Portfolio Performance Analysis* Bloomberg Professional Design* Integrated with FFN library via PyO3+ *+ * Features:+ * - Multiple data sources (Manual, Portfolio, Symbol)+ * - Performance metrics analysis+ * - Drawdown analysis+ * - Risk metrics+ * - Monthly returns heatmap+ * - Rolling metrics charts+ * - Asset comparison with correlation matrix+ * - Portfolio optimization (ERC, Inv Vol, Mean-Var, Equal Weight)+ * - Benchmark comparison (Alpha, Beta, Tracking Error, Information Ratio, Capture Ratios)*/-import React, { useState, useEffect } from 'react';+import React, { useState, useEffect, useCallback } from 'react';import {TrendingUp,TrendingDown,@@ -21,9 +32,20 @@ import {Percent,DollarSign,Clock,- Target+ Target,+ Database,+ Briefcase,+ Search,+ Grid,+ Table,+ Layers,+ Scale,+ Sliders,+ GitCompare} from 'lucide-react';-import { ffnService, type PerformanceMetrics, type DrawdownInfo, type FFNConfig } from '@/services/aiQuantLab/ffnService';+import { ffnService, type PerformanceMetrics, type DrawdownInfo, type FFNConfig, type MonthlyReturnsResponse, type RollingMetricsResponse, type AssetComparisonResponse, type PortfolioOptimizationResponse, type BenchmarkComparisonResponse } from '@/services/aiQuantLab/ffnService';+import { portfolioService, type Portfolio } from '@/services/portfolioService';+import { yfinanceService } from '@/services/yfinanceService';// Bloomberg Professional Color Paletteconst BLOOMBERG = {@@ -68,6 +90,15 @@ const SAMPLE_PRICES = {'2023-01-31': 113.8};+// Data source types+type DataSourceType = 'manual' | 'portfolio' | 'symbol';++// Analysis mode types+type AnalysisMode = 'performance' | 'comparison' | 'monthly' | 'rolling' | 'optimize' | 'benchmark';++// Optimization method types+type OptimizationMethod = 'erc' | 'inv_vol' | 'mean_var' | 'equal';+interface AnalysisResult {performance?: PerformanceMetrics;drawdowns?: {@@ -81,6 +112,14 @@ interface AnalysisResult {var_95?: number;cvar_95?: number;};+ monthlyReturns?: Record<string, Record<string, number | null>>;+ rollingMetrics?: {+ rolling_sharpe?: Record<string, number>;+ rolling_volatility?: Record<string, number>;+ };+ comparison?: AssetComparisonResponse;+ optimization?: PortfolioOptimizationResponse;+ benchmark?: BenchmarkComparisonResponse;}export function FFNAnalyticsPanel() {@@ -89,20 +128,48 @@ export function FFNAnalyticsPanel() {const [error, setError] = useState<string | null>(null);const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);const [priceInput, setPriceInput] = useState(JSON.stringify(SAMPLE_PRICES, null, 2));++ // Data source configuration+ const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');+ const [symbolInput, setSymbolInput] = useState('AAPL');+ const [symbolsInput, setSymbolsInput] = useState('AAPL,MSFT,GOOGL'); // For comparison+ const [historicalDays, setHistoricalDays] = useState(365);+ const [priceDataLoading, setPriceDataLoading] = useState(false);++ // Analysis mode+ const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('performance');++ // Portfolio optimization settings+ const [optimizationMethod, setOptimizationMethod] = useState<OptimizationMethod>('erc');++ // Benchmark comparison settings+ const [benchmarkSymbol, setBenchmarkSymbol] = useState('SPY');++ // Configconst [config, setConfig] = useState<FFNConfig>({risk_free_rate: 0.02,annualization_factor: 252,drawdown_threshold: 0.05});+const [expandedSections, setExpandedSections] = useState({performance: true,drawdowns: true,- risk: true+ risk: true,+ monthly: true,+ rolling: true,+ comparison: true,+ optimization: true,+ benchmark: true,+ dataSource: true});- // Check FFN availability on mount+ // Check FFN availability and load portfolios on mountuseEffect(() => {checkFFNStatus();+ loadPortfolios();}, []);const checkFFNStatus = async () => {@@ -118,6 +185,126 @@ export function FFNAnalyticsPanel() {}};+ const loadPortfolios = async () => {+ try {+ const portfolioList = await portfolioService.getPortfolios();+ setPortfolios(portfolioList);+ if (portfolioList.length > 0) {+ setSelectedPortfolioId(portfolioList[0].id);+ }+ } catch (err) {+ console.error('Failed to load portfolios:', err);+ }+ };++ // Fetch data based on source type+ const fetchData = useCallback(async () => {+ setPriceDataLoading(true);+ setError(null);++ try {+ if (dataSourceType === 'portfolio' && selectedPortfolioId) {+ const summary = await portfolioService.getPortfolioSummary(selectedPortfolioId);+ if (!summary || !summary.holdings || summary.holdings.length === 0) {+ setError('Portfolio has no holdings');+ return;+ }++ // Fetch historical data for all holdings+ const priceData: Record<string, Record<string, number>> = {};+ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - historicalDays);++ for (const holding of summary.holdings) {+ try {+ const data = await yfinanceService.getHistoricalData(+ holding.symbol,+ startDate.toISOString().split('T')[0],+ endDate.toISOString().split('T')[0]+ );+ if (data && data.length > 0) {+ priceData[holding.symbol] = {};+ data.forEach(point => {+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];+ priceData[holding.symbol][dateStr] = point.adj_close || point.close;+ });+ }+ } catch (err) {+ console.error(`Failed to fetch data for ${holding.symbol}:`, err);+ }+ }++ if (Object.keys(priceData).length > 0) {+ setPriceInput(JSON.stringify(priceData, null, 2));+ } else {+ setError('Failed to fetch historical data for portfolio');+ }+ } else if (dataSourceType === 'symbol') {+ // Handle single symbol or multiple symbols based on analysis mode+ const symbols = (analysisMode === 'comparison' || analysisMode === 'optimize')+ ? symbolsInput.split(',').map(s => s.trim()).filter(Boolean)+ : [symbolInput];++ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - historicalDays);++ if (symbols.length === 1) {+ // Single symbol - simple format+ const data = await yfinanceService.getHistoricalData(+ symbols[0],+ startDate.toISOString().split('T')[0],+ endDate.toISOString().split('T')[0]+ );++ if (data && data.length > 0) {+ const priceData: Record<string, number> = {};+ data.forEach(point => {+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];+ priceData[dateStr] = point.adj_close || point.close;+ });+ setPriceInput(JSON.stringify(priceData, null, 2));+ } else {+ setError(`No data available for ${symbols[0]}`);+ }+ } else {+ // Multiple symbols - multi-asset format+ const priceData: Record<string, Record<string, number>> = {};++ for (const symbol of symbols) {+ try {+ const data = await yfinanceService.getHistoricalData(+ symbol,+ startDate.toISOString().split('T')[0],+ endDate.toISOString().split('T')[0]+ );+ if (data && data.length > 0) {+ priceData[symbol] = {};+ data.forEach(point => {+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];+ priceData[symbol][dateStr] = point.adj_close || point.close;+ });+ }+ } catch (err) {+ console.error(`Failed to fetch data for ${symbol}:`, err);+ }+ }++ if (Object.keys(priceData).length > 0) {+ setPriceInput(JSON.stringify(priceData, null, 2));+ } else {+ setError('Failed to fetch data for any symbols');+ }+ }+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to load data');+ } finally {+ setPriceDataLoading(false);+ }+ }, [dataSourceType, selectedPortfolioId, symbolInput, symbolsInput, historicalDays, analysisMode]);+const runAnalysis = async () => {setIsLoading(true);setError(null);@@ -125,28 +312,118 @@ export function FFNAnalyticsPanel() {try {const prices = JSON.parse(priceInput);- // Run full analysis- const result = await ffnService.fullAnalysis(prices, config);+ if (analysisMode === 'performance') {+ // Run full analysis+ const result = await ffnService.fullAnalysis(prices, config);+ if (!result.success) {+ setError(result.error || 'Analysis failed');+ return;+ }- if (!result.success) {- setError(result.error || 'Analysis failed');- return;- }+ // Get additional risk metrics+ const riskResult = await ffnService.riskMetrics(prices, config.risk_free_rate);++ setAnalysisResult({+ performance: result.performance as PerformanceMetrics,+ drawdowns: result.drawdowns,+ riskMetrics: riskResult.success ? {+ ulcer_index: riskResult.ulcer_index,+ skewness: riskResult.skewness,+ kurtosis: riskResult.kurtosis,+ var_95: riskResult.var_95,+ cvar_95: riskResult.cvar_95+ } : undefined+ });+ } else if (analysisMode === 'monthly') {+ // Monthly returns analysis+ const result = await ffnService.monthlyReturns(prices);+ if (!result.success) {+ setError(result.error || 'Monthly returns analysis failed');+ return;+ }++ setAnalysisResult({+ monthlyReturns: result.monthly_returns+ });+ } else if (analysisMode === 'rolling') {+ // Rolling metrics analysis+ const result = await ffnService.calculateRollingMetrics(prices, 63, ['sharpe', 'volatility']);+ if (!result.success) {+ setError(result.error || 'Rolling metrics analysis failed');+ return;+ }++ setAnalysisResult({+ rollingMetrics: result.metrics+ });+ } else if (analysisMode === 'comparison') {+ // Asset comparison+ const result = await ffnService.compareAssets(prices, undefined, config.risk_free_rate);+ if (!result.success) {+ setError(result.error || 'Asset comparison failed');+ return;+ }- // Get additional risk metrics- const riskResult = await ffnService.riskMetrics(prices, config.risk_free_rate);-- setAnalysisResult({- performance: result.performance as PerformanceMetrics,- drawdowns: result.drawdowns,- riskMetrics: riskResult.success ? {- ulcer_index: riskResult.ulcer_index,- skewness: riskResult.skewness,- kurtosis: riskResult.kurtosis,- var_95: riskResult.var_95,- cvar_95: riskResult.cvar_95- } : undefined- });+ setAnalysisResult({+ comparison: result+ });+ } else if (analysisMode === 'optimize') {+ // Portfolio optimization+ const result = await ffnService.portfolioOptimization(+ prices,+ optimizationMethod,+ config.risk_free_rate,+ [0, 1]+ );+ if (!result.success) {+ setError(result.error || 'Portfolio optimization failed');+ return;+ }++ setAnalysisResult({+ optimization: result+ });+ } else if (analysisMode === 'benchmark') {+ // Benchmark comparison+ // Fetch benchmark data+ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - historicalDays);++ const benchmarkData = await yfinanceService.getHistoricalData(+ benchmarkSymbol,+ startDate.toISOString().split('T')[0],+ endDate.toISOString().split('T')[0]+ );++ if (!benchmarkData || benchmarkData.length === 0) {+ setError(`No data available for benchmark ${benchmarkSymbol}`);+ return;+ }++ // Convert to price format+ const benchmarkPrices: Record<string, number> = {};+ benchmarkData.forEach(point => {+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];+ benchmarkPrices[dateStr] = point.adj_close || point.close;+ });++ const result = await ffnService.benchmarkComparison(+ prices,+ benchmarkPrices,+ benchmarkSymbol,+ config.risk_free_rate+ );++ if (!result.success) {+ setError(result.error || 'Benchmark comparison failed');+ return;+ }++ setAnalysisResult({+ benchmark: result+ });+ }} catch (err) {setError(err instanceof Error ? err.message : 'Analysis failed');} finally {@@ -174,6 +451,16 @@ export function FFNAnalyticsPanel() {return value > 0 ? BLOOMBERG.GREEN : value < 0 ? BLOOMBERG.RED : BLOOMBERG.WHITE;};+ const getHeatmapColor = (value: number | null): string => {+ if (value === null || value === undefined) return BLOOMBERG.PANEL_BG;+ if (value > 0.05) return '#00D66F';+ if (value > 0.02) return '#00A050';+ if (value > 0) return '#006030';+ if (value > -0.02) return '#603000';+ if (value > -0.05) return '#A05000';+ return '#FF3B3B';+ };+// Loading/Error statesif (isFFNAvailable === null) {return (@@ -214,79 +501,390 @@ export function FFNAnalyticsPanel() {<div className="flex h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>{/* Left Panel - Input */}<div- className="w-80 flex flex-col border-r"+ className="w-80 flex flex-col border-r overflow-auto"style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}>- {/* Input Header */}+ {/* Data Source Section */}<div- className="px-4 py-3 border-b flex items-center gap-2"- style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderColor: BLOOMBERG.BORDER }}+ className="rounded overflow-hidden m-2"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}>- <LineChart size={16} color={BLOOMBERG.ORANGE} />- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>- Price Data Input- </span>+ <button+ onClick={() => toggleSection('dataSource')}+ className="w-full px-3 py-2 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Database size={14} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Data Source+ </span>+ </div>+ {expandedSections.dataSource ? (+ <ChevronUp size={14} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={14} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.dataSource && (+ <div className="p-3 space-y-3">+ {/* Data source type buttons */}+ <div className="flex gap-1">+ <button+ onClick={() => setDataSourceType('manual')}+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono"+ style={{+ backgroundColor: dataSourceType === 'manual' ? BLOOMBERG.ORANGE : 'transparent',+ color: dataSourceType === 'manual' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ Manual+ </button>+ <button+ onClick={() => setDataSourceType('portfolio')}+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: dataSourceType === 'portfolio' ? BLOOMBERG.ORANGE : 'transparent',+ color: dataSourceType === 'portfolio' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Briefcase size={12} />+ Portfolio+ </button>+ <button+ onClick={() => setDataSourceType('symbol')}+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: dataSourceType === 'symbol' ? BLOOMBERG.ORANGE : 'transparent',+ color: dataSourceType === 'symbol' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Search size={12} />+ Symbol+ </button>+ </div>++ {/* Portfolio selector */}+ {dataSourceType === 'portfolio' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ SELECT PORTFOLIO+ </label>+ <select+ value={selectedPortfolioId}+ onChange={(e) => setSelectedPortfolioId(e.target.value)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ {portfolios.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ )}++ {/* Symbol input */}+ {dataSourceType === 'symbol' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ {(analysisMode === 'comparison' || analysisMode === 'optimize') ? 'SYMBOLS (comma-separated)' : 'SYMBOL'}+ </label>+ <input+ type="text"+ value={(analysisMode === 'comparison' || analysisMode === 'optimize') ? symbolsInput : symbolInput}+ onChange={(e) => (analysisMode === 'comparison' || analysisMode === 'optimize')+ ? setSymbolsInput(e.target.value.toUpperCase())+ : setSymbolInput(e.target.value.toUpperCase())+ }+ placeholder={(analysisMode === 'comparison' || analysisMode === 'optimize') ? "AAPL,MSFT,GOOGL" : "AAPL"}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ )}++ {/* Historical days */}+ {dataSourceType !== 'manual' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ HISTORICAL DAYS+ </label>+ <input+ type="number"+ value={historicalDays}+ onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ )}++ {/* Fetch data button */}+ {dataSourceType !== 'manual' && (+ <button+ onClick={fetchData}+ disabled={priceDataLoading}+ className="w-full py-2 rounded text-xs font-bold uppercase flex items-center justify-center gap-2"+ style={{+ backgroundColor: BLOOMBERG.CYAN,+ color: BLOOMBERG.DARK_BG,+ opacity: priceDataLoading ? 0.5 : 1+ }}+ >+ {priceDataLoading ? (+ <>+ <RefreshCw size={12} className="animate-spin" />+ Loading...+ </>+ ) : (+ <>+ <Database size={12} />+ Fetch Data+ </>+ )}+ </button>+ )}+ </div>+ )}</div>- {/* Price Input */}- <div className="flex-1 p-4 overflow-auto">+ {/* Analysis Mode */}+ <div className="px-2 py-2"><label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>- PRICE DATA (JSON)+ ANALYSIS MODE</label>- <textarea- value={priceInput}- onChange={(e) => setPriceInput(e.target.value)}- className="w-full h-48 p-3 rounded text-xs font-mono resize-none"- style={{- backgroundColor: BLOOMBERG.DARK_BG,- color: BLOOMBERG.WHITE,- border: `1px solid ${BLOOMBERG.BORDER}`- }}- placeholder='{"2023-01-01": 100, "2023-01-02": 101, ...}'- />-- {/* Config Options */}- <div className="mt-4 space-y-3">- <div>- <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>- RISK-FREE RATE- </label>- <input- type="number"- step="0.01"- value={config.risk_free_rate}- onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) || 0 })}- className="w-full p-2 rounded text-xs font-mono"+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => setAnalysisMode('performance')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'performance' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'performance' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Activity size={12} />+ Performance+ </button>+ <button+ onClick={() => setAnalysisMode('monthly')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'monthly' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'monthly' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Calendar size={12} />+ Monthly+ </button>+ <button+ onClick={() => setAnalysisMode('rolling')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'rolling' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'rolling' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <LineChart size={12} />+ Rolling+ </button>+ <button+ onClick={() => setAnalysisMode('comparison')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'comparison' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'comparison' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Layers size={12} />+ Compare+ </button>+ <button+ onClick={() => setAnalysisMode('optimize')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'optimize' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'optimize' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <Scale size={12} />+ Optimize+ </button>+ <button+ onClick={() => setAnalysisMode('benchmark')}+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"+ style={{+ backgroundColor: analysisMode === 'benchmark' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'benchmark' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <GitCompare size={12} />+ Benchmark+ </button>+ </div>+ </div>++ {/* Optimization Method Selector */}+ {analysisMode === 'optimize' && (+ <div className="px-2 py-2">+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ OPTIMIZATION METHOD+ </label>+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => setOptimizationMethod('erc')}+ className="px-2 py-1.5 rounded text-xs font-mono"style={{- backgroundColor: BLOOMBERG.DARK_BG,- color: BLOOMBERG.WHITE,+ backgroundColor: optimizationMethod === 'erc' ? BLOOMBERG.CYAN : 'transparent',+ color: optimizationMethod === 'erc' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,border: `1px solid ${BLOOMBERG.BORDER}`}}- />- </div>-- <div>- <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>- DRAWDOWN THRESHOLD- </label>- <input- type="number"- step="0.01"- value={config.drawdown_threshold}- onChange={(e) => setConfig({ ...config, drawdown_threshold: parseFloat(e.target.value) || 0.05 })}- className="w-full p-2 rounded text-xs font-mono"+ >+ ERC+ </button>+ <button+ onClick={() => setOptimizationMethod('inv_vol')}+ className="px-2 py-1.5 rounded text-xs font-mono"+ style={{+ backgroundColor: optimizationMethod === 'inv_vol' ? BLOOMBERG.CYAN : 'transparent',+ color: optimizationMethod === 'inv_vol' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ Inv Vol+ </button>+ <button+ onClick={() => setOptimizationMethod('mean_var')}+ className="px-2 py-1.5 rounded text-xs font-mono"style={{- backgroundColor: BLOOMBERG.DARK_BG,- color: BLOOMBERG.WHITE,+ backgroundColor: optimizationMethod === 'mean_var' ? BLOOMBERG.CYAN : 'transparent',+ color: optimizationMethod === 'mean_var' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,border: `1px solid ${BLOOMBERG.BORDER}`}}- />+ >+ Mean-Var+ </button>+ <button+ onClick={() => setOptimizationMethod('equal')}+ className="px-2 py-1.5 rounded text-xs font-mono"+ style={{+ backgroundColor: optimizationMethod === 'equal' ? BLOOMBERG.CYAN : 'transparent',+ color: optimizationMethod === 'equal' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ Equal Wt+ </button></div></div>+ )}++ {/* Benchmark Symbol Input */}+ {analysisMode === 'benchmark' && (+ <div className="px-2 py-2">+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ BENCHMARK SYMBOL+ </label>+ <input+ type="text"+ value={benchmarkSymbol}+ onChange={(e) => setBenchmarkSymbol(e.target.value.toUpperCase())}+ placeholder="SPY"+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ <p className="text-xs font-mono mt-1" style={{ color: BLOOMBERG.MUTED }}>+ Common: SPY, QQQ, IWM, DIA+ </p>+ </div>+ )}++ {/* Price Input (for manual mode) */}+ {dataSourceType === 'manual' && (+ <div className="flex-1 p-2 overflow-auto">+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ PRICE DATA (JSON)+ </label>+ <textarea+ value={priceInput}+ onChange={(e) => setPriceInput(e.target.value)}+ className="w-full h-48 p-3 rounded text-xs font-mono resize-none"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ placeholder='{"2023-01-01": 100, "2023-01-02": 101, ...}'+ />+ </div>+ )}++ {/* Config Options */}+ <div className="p-2 space-y-3">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ RISK-FREE RATE+ </label>+ <input+ type="number"+ step="0.01"+ value={config.risk_free_rate}+ onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) || 0 })}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>++ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ DRAWDOWN THRESHOLD+ </label>+ <input+ type="number"+ step="0.01"+ value={config.drawdown_threshold}+ onChange={(e) => setConfig({ ...config, drawdown_threshold: parseFloat(e.target.value) || 0.05 })}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div></div>{/* Run Button */}- <div className="p-4 border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <div className="p-2 border-t" style={{ borderColor: BLOOMBERG.BORDER }}><buttononClick={runAnalysis}disabled={isLoading}@@ -325,7 +923,12 @@ export function FFNAnalyticsPanel() {<div className="text-center"><BarChart2 size={64} color={BLOOMBERG.MUTED} className="mx-auto mb-4" /><p className="text-sm font-mono" style={{ color: BLOOMBERG.GRAY }}>- Enter price data and click "Run Analysis" to see results+ {analysisMode === 'performance' && 'Enter price data and click "Run Analysis" to see performance metrics'}+ {analysisMode === 'monthly' && 'Click "Run Analysis" to see monthly returns heatmap'}+ {analysisMode === 'rolling' && 'Click "Run Analysis" to see rolling performance metrics'}+ {analysisMode === 'comparison' && 'Enter multiple symbols and click "Run Analysis" to compare assets'}+ {analysisMode === 'optimize' && 'Enter multiple symbols and click "Run Analysis" to optimize portfolio weights'}+ {analysisMode === 'benchmark' && 'Enter portfolio data and benchmark symbol, then click "Run Analysis" to compare against benchmark'}</p></div></div>@@ -334,218 +937,819 @@ export function FFNAnalyticsPanel() {{analysisResult && (<div className="space-y-4">{/* Performance Metrics Section */}- <div- className="rounded overflow-hidden"- style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}- >- <button- onClick={() => toggleSection('performance')}- className="w-full px-4 py-3 flex items-center justify-between"- style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ {analysisResult.performance && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}>- <div className="flex items-center gap-2">- <TrendingUp size={16} color={BLOOMBERG.GREEN} />- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>- Performance Metrics- </span>- </div>- {expandedSections.performance ? (- <ChevronUp size={16} color={BLOOMBERG.GRAY} />- ) : (- <ChevronDown size={16} color={BLOOMBERG.GRAY} />- )}- </button>+ <button+ onClick={() => toggleSection('performance')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <TrendingUp size={16} color={BLOOMBERG.GREEN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Performance Metrics+ </span>+ </div>+ {expandedSections.performance ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>- {expandedSections.performance && analysisResult.performance && (- <div className="p-4 grid grid-cols-3 gap-4">- <MetricCard- label="Total Return"- value={formatPercent(analysisResult.performance.total_return)}- color={getValueColor(analysisResult.performance.total_return)}- icon={<Percent size={14} />}- />- <MetricCard- label="CAGR"- value={formatPercent(analysisResult.performance.cagr)}- color={getValueColor(analysisResult.performance.cagr)}- icon={<TrendingUp size={14} />}- />- <MetricCard- label="Sharpe Ratio"- value={formatRatio(analysisResult.performance.sharpe_ratio)}- color={getValueColor(analysisResult.performance.sharpe_ratio)}- icon={<Target size={14} />}- />- <MetricCard- label="Sortino Ratio"- value={formatRatio(analysisResult.performance.sortino_ratio)}- color={getValueColor(analysisResult.performance.sortino_ratio)}- icon={<Target size={14} />}- />- <MetricCard- label="Volatility"- value={formatPercent(analysisResult.performance.volatility)}- color={BLOOMBERG.YELLOW}- icon={<Activity size={14} />}- />- <MetricCard- label="Calmar Ratio"- value={formatRatio(analysisResult.performance.calmar_ratio)}- color={getValueColor(analysisResult.performance.calmar_ratio)}- icon={<BarChart2 size={14} />}- />- <MetricCard- label="Best Day"- value={formatPercent(analysisResult.performance.best_day)}- color={BLOOMBERG.GREEN}- icon={<TrendingUp size={14} />}- />- <MetricCard- label="Worst Day"- value={formatPercent(analysisResult.performance.worst_day)}- color={BLOOMBERG.RED}- icon={<TrendingDown size={14} />}- />- <MetricCard- label="Daily Mean"- value={formatPercent(analysisResult.performance.daily_mean, 4)}- color={getValueColor(analysisResult.performance.daily_mean)}- icon={<LineChart size={14} />}- />- </div>- )}- </div>+ {expandedSections.performance && (+ <div className="p-4 grid grid-cols-3 gap-4">+ <MetricCard+ label="Total Return"+ value={formatPercent(analysisResult.performance.total_return)}+ color={getValueColor(analysisResult.performance.total_return)}+ icon={<Percent size={14} />}+ />+ <MetricCard+ label="CAGR"+ value={formatPercent(analysisResult.performance.cagr)}+ color={getValueColor(analysisResult.performance.cagr)}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Sharpe Ratio"+ value={formatRatio(analysisResult.performance.sharpe_ratio)}+ color={getValueColor(analysisResult.performance.sharpe_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Sortino Ratio"+ value={formatRatio(analysisResult.performance.sortino_ratio)}+ color={getValueColor(analysisResult.performance.sortino_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Volatility"+ value={formatPercent(analysisResult.performance.volatility)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Calmar Ratio"+ value={formatRatio(analysisResult.performance.calmar_ratio)}+ color={getValueColor(analysisResult.performance.calmar_ratio)}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="Best Day"+ value={formatPercent(analysisResult.performance.best_day)}+ color={BLOOMBERG.GREEN}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Worst Day"+ value={formatPercent(analysisResult.performance.worst_day)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ <MetricCard+ label="Daily Mean"+ value={formatPercent(analysisResult.performance.daily_mean, 4)}+ color={getValueColor(analysisResult.performance.daily_mean)}+ icon={<LineChart size={14} />}+ />+ </div>+ )}+ </div>+ )}{/* Drawdowns Section */}- <div- className="rounded overflow-hidden"- style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}- >- <button- onClick={() => toggleSection('drawdowns')}- className="w-full px-4 py-3 flex items-center justify-between"- style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ {analysisResult.drawdowns && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}>- <div className="flex items-center gap-2">- <TrendingDown size={16} color={BLOOMBERG.RED} />- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>- Drawdown Analysis- </span>- </div>- {expandedSections.drawdowns ? (- <ChevronUp size={16} color={BLOOMBERG.GRAY} />- ) : (- <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ <button+ onClick={() => toggleSection('drawdowns')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <TrendingDown size={16} color={BLOOMBERG.RED} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Drawdown Analysis+ </span>+ </div>+ {expandedSections.drawdowns ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.drawdowns && (+ <div className="p-4">+ <div className="mb-4">+ <MetricCard+ label="Max Drawdown"+ value={formatPercent(analysisResult.drawdowns.max_drawdown)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ large+ />+ </div>++ {analysisResult.drawdowns.top_drawdowns && analysisResult.drawdowns.top_drawdowns.length > 0 && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ TOP DRAWDOWN PERIODS+ </h4>+ <div className="space-y-2">+ {analysisResult.drawdowns.top_drawdowns.map((dd, idx) => (+ <div+ key={idx}+ className="p-3 rounded flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex items-center gap-3">+ <span+ className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"+ style={{ backgroundColor: BLOOMBERG.RED, color: BLOOMBERG.WHITE }}+ >+ {idx + 1}+ </span>+ <div>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ {dd.start} → {dd.end}+ </span>+ </div>+ </div>+ <span className="text-sm font-bold" style={{ color: BLOOMBERG.RED }}>+ {formatPercent(dd.drawdown)}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>)}- </button>+ </div>+ )}++ {/* Risk Metrics Section */}+ {analysisResult.riskMetrics && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('risk')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <AlertCircle size={16} color={BLOOMBERG.YELLOW} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Risk Metrics+ </span>+ </div>+ {expandedSections.risk ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>- {expandedSections.drawdowns && analysisResult.drawdowns && (- <div className="p-4">- <div className="mb-4">+ {expandedSections.risk && (+ <div className="p-4 grid grid-cols-3 gap-4">+ <MetricCard+ label="Ulcer Index"+ value={formatRatio(analysisResult.riskMetrics.ulcer_index, 4)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Skewness"+ value={formatRatio(analysisResult.riskMetrics.skewness)}+ color={BLOOMBERG.CYAN}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="Kurtosis"+ value={formatRatio(analysisResult.riskMetrics.kurtosis)}+ color={BLOOMBERG.CYAN}+ icon={<BarChart2 size={14} />}+ /><MetricCard- label="Max Drawdown"- value={formatPercent(analysisResult.drawdowns.max_drawdown)}+ label="VaR (95%)"+ value={formatPercent(analysisResult.riskMetrics.var_95)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ <MetricCard+ label="CVaR (95%)"+ value={formatPercent(analysisResult.riskMetrics.cvar_95)}color={BLOOMBERG.RED}icon={<TrendingDown size={14} />}- large/></div>+ )}+ </div>+ )}- {analysisResult.drawdowns.top_drawdowns && analysisResult.drawdowns.top_drawdowns.length > 0 && (- <div>- <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>- TOP DRAWDOWN PERIODS- </h4>- <div className="space-y-2">- {analysisResult.drawdowns.top_drawdowns.map((dd, idx) => (- <div- key={idx}- className="p-3 rounded flex items-center justify-between"- style={{ backgroundColor: BLOOMBERG.DARK_BG }}- >- <div className="flex items-center gap-3">- <span- className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"- style={{ backgroundColor: BLOOMBERG.RED, color: BLOOMBERG.WHITE }}- >- {idx + 1}- </span>- <div>- <span className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>- {dd.start} → {dd.end}- </span>- </div>- </div>- <span className="text-sm font-bold" style={{ color: BLOOMBERG.RED }}>- {formatPercent(dd.drawdown)}- </span>+ {/* Monthly Returns Heatmap */}+ {analysisResult.monthlyReturns && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('monthly')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Calendar size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Monthly Returns Heatmap+ </span>+ </div>+ {expandedSections.monthly ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.monthly && (+ <div className="p-4 overflow-auto">+ <div className="min-w-[600px]">+ {/* Month headers */}+ <div className="flex">+ <div className="w-16 text-xs font-mono text-center" style={{ color: BLOOMBERG.GRAY }}>+ Year+ </div>+ {['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].map(m => (+ <div key={m} className="flex-1 text-xs font-mono text-center" style={{ color: BLOOMBERG.GRAY }}>+ {m}</div>))}</div>+ {/* Year rows */}+ {Object.entries(analysisResult.monthlyReturns).sort().map(([year, months]) => (+ <div key={year} className="flex mt-1">+ <div className="w-16 text-xs font-mono text-center py-2" style={{ color: BLOOMBERG.WHITE }}>+ {year}+ </div>+ {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(m => {+ const value = months[String(m)] ?? null;+ return (+ <div+ key={m}+ className="flex-1 text-xs font-mono text-center py-2 mx-0.5 rounded"+ style={{+ backgroundColor: getHeatmapColor(value),+ color: BLOOMBERG.WHITE+ }}+ title={value !== null ? `${(value * 100).toFixed(2)}%` : 'N/A'}+ >+ {value !== null ? `${(value * 100).toFixed(1)}` : '-'}+ </div>+ );+ })}+ </div>+ ))}</div>+ </div>+ )}+ </div>+ )}++ {/* Rolling Metrics */}+ {analysisResult.rollingMetrics && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('rolling')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <LineChart size={16} color={BLOOMBERG.PURPLE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Rolling Metrics (63-Day)+ </span>+ </div>+ {expandedSections.rolling ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />)}- </div>- )}- </div>+ </button>- {/* Risk Metrics Section */}- <div- className="rounded overflow-hidden"- style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}- >- <button- onClick={() => toggleSection('risk')}- className="w-full px-4 py-3 flex items-center justify-between"- style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ {expandedSections.rolling && (+ <div className="p-4">+ {analysisResult.rollingMetrics.rolling_sharpe && (+ <div className="mb-4">+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ ROLLING SHARPE RATIO+ </h4>+ <div className="h-32 flex items-end gap-px">+ {Object.values(analysisResult.rollingMetrics.rolling_sharpe).slice(-50).map((value, idx) => {+ const height = Math.min(100, Math.max(10, ((value + 2) / 4) * 100));+ return (+ <div+ key={idx}+ className="flex-1 rounded-t"+ style={{+ height: `${height}%`,+ backgroundColor: value > 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}+ />+ );+ })}+ </div>+ </div>+ )}+ {analysisResult.rollingMetrics.rolling_volatility && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ ROLLING VOLATILITY+ </h4>+ <div className="h-32 flex items-end gap-px">+ {Object.values(analysisResult.rollingMetrics.rolling_volatility).slice(-50).map((value, idx) => {+ const height = Math.min(100, Math.max(10, (value / 0.5) * 100));+ return (+ <div+ key={idx}+ className="flex-1 rounded-t"+ style={{+ height: `${height}%`,+ backgroundColor: BLOOMBERG.YELLOW+ }}+ />+ );+ })}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ )}++ {/* Asset Comparison */}+ {analysisResult.comparison && analysisResult.comparison.success && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}>- <div className="flex items-center gap-2">- <AlertCircle size={16} color={BLOOMBERG.YELLOW} />- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>- Risk Metrics- </span>- </div>- {expandedSections.risk ? (- <ChevronUp size={16} color={BLOOMBERG.GRAY} />- ) : (- <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ <button+ onClick={() => toggleSection('comparison')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Layers size={16} color={BLOOMBERG.BLUE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Asset Comparison+ </span>+ </div>+ {expandedSections.comparison ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.comparison && (+ <div className="p-4 space-y-4">+ {/* Correlation Matrix */}+ {analysisResult.comparison.correlation_matrix && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ CORRELATION MATRIX+ </h4>+ <div className="overflow-auto">+ <table className="w-full text-xs font-mono">+ <thead>+ <tr>+ <th className="p-2" style={{ color: BLOOMBERG.GRAY }}></th>+ {Object.keys(analysisResult.comparison.correlation_matrix).map(symbol => (+ <th key={symbol} className="p-2" style={{ color: BLOOMBERG.WHITE }}>+ {symbol}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {Object.entries(analysisResult.comparison.correlation_matrix).map(([symbol, correlations]) => (+ <tr key={symbol}>+ <td className="p-2" style={{ color: BLOOMBERG.WHITE }}>{symbol}</td>+ {Object.entries(correlations).map(([otherSymbol, corr]) => (+ <td+ key={otherSymbol}+ className="p-2 text-center rounded"+ style={{+ backgroundColor: `rgba(0, 136, 255, ${Math.abs(corr)})`,+ color: BLOOMBERG.WHITE+ }}+ >+ {corr.toFixed(2)}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}++ {/* Asset Stats Comparison */}+ {analysisResult.comparison.asset_stats && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ PERFORMANCE COMPARISON+ </h4>+ <div className="overflow-auto">+ <table className="w-full text-xs font-mono">+ <thead>+ <tr>+ <th className="p-2 text-left" style={{ color: BLOOMBERG.GRAY }}>Asset</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Return</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Vol</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Sharpe</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>MaxDD</th>+ </tr>+ </thead>+ <tbody>+ {Object.entries(analysisResult.comparison.asset_stats).map(([symbol, stats]) => (+ <tr key={symbol} className="border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <td className="p-2" style={{ color: BLOOMBERG.WHITE }}>{symbol}</td>+ <td className="p-2 text-right" style={{ color: getValueColor(stats.total_return) }}>+ {formatPercent(stats.total_return)}+ </td>+ <td className="p-2 text-right" style={{ color: BLOOMBERG.YELLOW }}>+ {formatPercent(stats.volatility)}+ </td>+ <td className="p-2 text-right" style={{ color: getValueColor(stats.sharpe_ratio) }}>+ {formatRatio(stats.sharpe_ratio)}+ </td>+ <td className="p-2 text-right" style={{ color: BLOOMBERG.RED }}>+ {formatPercent(stats.max_drawdown)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ </div>)}- </button>+ </div>+ )}- {expandedSections.risk && analysisResult.riskMetrics && (- <div className="p-4 grid grid-cols-3 gap-4">- <MetricCard- label="Ulcer Index"- value={formatRatio(analysisResult.riskMetrics.ulcer_index, 4)}- color={BLOOMBERG.YELLOW}- icon={<Activity size={14} />}- />- <MetricCard- label="Skewness"- value={formatRatio(analysisResult.riskMetrics.skewness)}- color={BLOOMBERG.CYAN}- icon={<BarChart2 size={14} />}- />- <MetricCard- label="Kurtosis"- value={formatRatio(analysisResult.riskMetrics.kurtosis)}- color={BLOOMBERG.CYAN}- icon={<BarChart2 size={14} />}- />- <MetricCard- label="VaR (95%)"- value={formatPercent(analysisResult.riskMetrics.var_95)}- color={BLOOMBERG.RED}- icon={<TrendingDown size={14} />}- />- <MetricCard- label="CVaR (95%)"- value={formatPercent(analysisResult.riskMetrics.cvar_95)}- color={BLOOMBERG.RED}- icon={<TrendingDown size={14} />}- />- </div>- )}- </div>+ {/* Portfolio Optimization Results */}+ {analysisResult.optimization && analysisResult.optimization.success && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('optimization')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Scale size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Portfolio Optimization - {analysisResult.optimization.method}+ </span>+ </div>+ {expandedSections.optimization ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.optimization && (+ <div className="p-4 space-y-4">+ {/* Optimal Weights */}+ {analysisResult.optimization.weights && (+ <div>+ <h4 className="text-xs font-mono mb-3" style={{ color: BLOOMBERG.GRAY }}>+ OPTIMAL WEIGHTS+ </h4>+ <div className="space-y-2">+ {Object.entries(analysisResult.optimization.weights)+ .sort(([, a], [, b]) => b - a)+ .map(([symbol, weight]) => (+ <div key={symbol} className="flex items-center gap-3">+ <span className="w-16 text-xs font-mono font-bold" style={{ color: BLOOMBERG.WHITE }}>+ {symbol}+ </span>+ <div className="flex-1 h-6 rounded overflow-hidden" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div+ className="h-full rounded"+ style={{+ width: `${weight * 100}%`,+ backgroundColor: BLOOMBERG.CYAN+ }}+ />+ </div>+ <span className="w-16 text-right text-xs font-mono font-bold" style={{ color: BLOOMBERG.CYAN }}>+ {formatPercent(weight)}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Portfolio Stats */}+ {analysisResult.optimization.portfolio_stats && (+ <div>+ <h4 className="text-xs font-mono mb-3" style={{ color: BLOOMBERG.GRAY }}>+ OPTIMIZED PORTFOLIO METRICS+ </h4>+ <div className="grid grid-cols-3 gap-3">+ <MetricCard+ label="Expected Return"+ value={formatPercent(analysisResult.optimization.portfolio_stats.total_return)}+ color={getValueColor(analysisResult.optimization.portfolio_stats.total_return)}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="CAGR"+ value={formatPercent(analysisResult.optimization.portfolio_stats.cagr)}+ color={getValueColor(analysisResult.optimization.portfolio_stats.cagr)}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Volatility"+ value={formatPercent(analysisResult.optimization.portfolio_stats.volatility)}+ color={BLOOMBERG.YELLOW}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Sharpe Ratio"+ value={formatRatio(analysisResult.optimization.portfolio_stats.sharpe_ratio)}+ color={getValueColor(analysisResult.optimization.portfolio_stats.sharpe_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Sortino Ratio"+ value={formatRatio(analysisResult.optimization.portfolio_stats.sortino_ratio)}+ color={getValueColor(analysisResult.optimization.portfolio_stats.sortino_ratio)}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Max Drawdown"+ value={formatPercent(analysisResult.optimization.portfolio_stats.max_drawdown)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ </div>+ </div>+ )}++ {/* Asset Contributions */}+ {analysisResult.optimization.asset_contributions && (+ <div>+ <h4 className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ ASSET CONTRIBUTIONS+ </h4>+ <div className="overflow-auto">+ <table className="w-full text-xs font-mono">+ <thead>+ <tr>+ <th className="p-2 text-left" style={{ color: BLOOMBERG.GRAY }}>Asset</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Weight</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Vol</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Return</th>+ <th className="p-2 text-right" style={{ color: BLOOMBERG.GRAY }}>Risk Contrib</th>+ </tr>+ </thead>+ <tbody>+ {Object.entries(analysisResult.optimization.asset_contributions).map(([symbol, contrib]) => (+ <tr key={symbol} className="border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <td className="p-2" style={{ color: BLOOMBERG.WHITE }}>{symbol}</td>+ <td className="p-2 text-right" style={{ color: BLOOMBERG.CYAN }}>+ {formatPercent(contrib.weight)}+ </td>+ <td className="p-2 text-right" style={{ color: BLOOMBERG.YELLOW }}>+ {formatPercent(contrib.volatility)}+ </td>+ <td className="p-2 text-right" style={{ color: getValueColor(contrib.return) }}>+ {formatPercent(contrib.return)}+ </td>+ <td className="p-2 text-right" style={{ color: BLOOMBERG.PURPLE }}>+ {formatPercent(contrib.risk_contribution)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ )}++ {/* Benchmark Comparison Results */}+ {analysisResult.benchmark && analysisResult.benchmark.success && (+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('benchmark')}+ className="w-full px-4 py-3 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <GitCompare size={16} color={BLOOMBERG.PURPLE} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Benchmark Comparison - {analysisResult.benchmark.benchmark_name || 'Benchmark'}+ </span>+ </div>+ {expandedSections.benchmark ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.benchmark && (+ <div className="p-4 space-y-4">+ {/* Side by Side Performance Comparison */}+ <div className="grid grid-cols-2 gap-4">+ {/* Portfolio Stats */}+ <div>+ <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: BLOOMBERG.CYAN }}>+ <Briefcase size={14} />+ PORTFOLIO+ </h4>+ <div className="space-y-2">+ {analysisResult.benchmark.portfolio_stats && (+ <>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Total Return</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.total_return) }}>+ {formatPercent(analysisResult.benchmark.portfolio_stats.total_return)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>CAGR</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.cagr) }}>+ {formatPercent(analysisResult.benchmark.portfolio_stats.cagr)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Volatility</span>+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.YELLOW }}>+ {formatPercent(analysisResult.benchmark.portfolio_stats.volatility)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Sharpe Ratio</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.sharpe_ratio) }}>+ {formatRatio(analysisResult.benchmark.portfolio_stats.sharpe_ratio)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Max Drawdown</span>+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.RED }}>+ {formatPercent(analysisResult.benchmark.portfolio_stats.max_drawdown)}+ </span>+ </div>+ </>+ )}+ </div>+ </div>++ {/* Benchmark Stats */}+ <div>+ <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: BLOOMBERG.ORANGE }}>+ <Target size={14} />+ {analysisResult.benchmark.benchmark_name || 'BENCHMARK'}+ </h4>+ <div className="space-y-2">+ {analysisResult.benchmark.benchmark_stats && (+ <>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Total Return</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.total_return) }}>+ {formatPercent(analysisResult.benchmark.benchmark_stats.total_return)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>CAGR</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.cagr) }}>+ {formatPercent(analysisResult.benchmark.benchmark_stats.cagr)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Volatility</span>+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.YELLOW }}>+ {formatPercent(analysisResult.benchmark.benchmark_stats.volatility)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Sharpe Ratio</span>+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.sharpe_ratio) }}>+ {formatRatio(analysisResult.benchmark.benchmark_stats.sharpe_ratio)}+ </span>+ </div>+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Max Drawdown</span>+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.RED }}>+ {formatPercent(analysisResult.benchmark.benchmark_stats.max_drawdown)}+ </span>+ </div>+ </>+ )}+ </div>+ </div>+ </div>++ {/* Relative Metrics */}+ {analysisResult.benchmark.relative_metrics && (+ <div>+ <h4 className="text-xs font-mono mb-3" style={{ color: BLOOMBERG.GRAY }}>+ RELATIVE METRICS+ </h4>+ <div className="grid grid-cols-4 gap-3">+ <MetricCard+ label="Alpha"+ value={formatPercent(analysisResult.benchmark.relative_metrics.alpha)}+ color={getValueColor(analysisResult.benchmark.relative_metrics.alpha)}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Beta"+ value={formatRatio(analysisResult.benchmark.relative_metrics.beta)}+ color={BLOOMBERG.CYAN}+ icon={<Activity size={14} />}+ />+ <MetricCard+ label="Correlation"+ value={formatRatio(analysisResult.benchmark.relative_metrics.correlation)}+ color={BLOOMBERG.BLUE}+ icon={<LineChart size={14} />}+ />+ <MetricCard+ label="Tracking Error"+ value={formatPercent(analysisResult.benchmark.relative_metrics.tracking_error)}+ color={BLOOMBERG.YELLOW}+ icon={<Target size={14} />}+ />+ <MetricCard+ label="Info Ratio"+ value={formatRatio(analysisResult.benchmark.relative_metrics.information_ratio)}+ color={getValueColor(analysisResult.benchmark.relative_metrics.information_ratio)}+ icon={<BarChart2 size={14} />}+ />+ <MetricCard+ label="Up Capture"+ value={formatPercent(analysisResult.benchmark.relative_metrics.up_capture)}+ color={BLOOMBERG.GREEN}+ icon={<TrendingUp size={14} />}+ />+ <MetricCard+ label="Down Capture"+ value={formatPercent(analysisResult.benchmark.relative_metrics.down_capture)}+ color={BLOOMBERG.RED}+ icon={<TrendingDown size={14} />}+ />+ </div>+ </div>+ )}++ {/* Date Range Info */}+ {analysisResult.benchmark.date_range && (+ <div className="flex items-center justify-between p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="flex items-center gap-2">+ <Calendar size={14} color={BLOOMBERG.GRAY} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ {analysisResult.benchmark.date_range.start} to {analysisResult.benchmark.date_range.end}+ </span>+ </div>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.MUTED }}>+ {analysisResult.benchmark.date_range.data_points} data points+ </span>+ </div>+ )}+ </div>+ )}+ </div>+ )}</div>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsxnew file mode 100644index 000000000..c12c24ace--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx@@ -0,0 +1,2032 @@+/**+ * Fortitudo.tech Analytics Panel - Portfolio Risk Analytics+ * Bloomberg Professional Design+ * Integrated with fortitudo.tech library via PyO3+ */++import React, { useState, useEffect, useMemo } from 'react';+import {+ Shield,+ TrendingUp,+ TrendingDown,+ Activity,+ BarChart2,+ RefreshCw,+ AlertCircle,+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ Play,+ Settings,+ Target,+ Percent,+ DollarSign,+ Layers,+ Grid,+ PieChart as PieChartIcon+} from 'lucide-react';+import {+ ScatterChart,+ Scatter,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+ Line,+ ComposedChart,+ ReferenceLine,+ Cell,+ PieChart,+ Pie,+ Legend+} from 'recharts';+import {+ fortitudoService,+ type PortfolioMetrics,+ type FullAnalysisResponse,+ type OptionGreeksResponse,+ type OptimizationResult,+ type EfficientFrontierResponse,+ type OptimizationObjective+} from '@/services/aiQuantLab/fortitudoService';+import {+ portfolioFortitudoService,+ type PortfolioReturnsData+} from '@/services/aiQuantLab/portfolioFortitudoService';+import { type Portfolio, type PortfolioSummary } from '@/services/portfolioService';+import { Briefcase, Database } from 'lucide-react';++// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};++// Sample portfolio data for demonstration+const SAMPLE_RETURNS = {+ 'Stocks': Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [+ new Date(2024, 0, i + 1).toISOString().split('T')[0],+ 0.0003 + (Math.random() - 0.5) * 0.02+ ])+ ),+ 'Bonds': Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [+ new Date(2024, 0, i + 1).toISOString().split('T')[0],+ 0.0001 + (Math.random() - 0.5) * 0.005+ ])+ ),+ 'Commodities': Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [+ new Date(2024, 0, i + 1).toISOString().split('T')[0],+ 0.0002 + (Math.random() - 0.5) * 0.015+ ])+ ),+ 'Cash': Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [+ new Date(2024, 0, i + 1).toISOString().split('T')[0],+ 0.0001 + (Math.random() - 0.5) * 0.001+ ])+ )+};++const SAMPLE_WEIGHTS = [0.4, 0.3, 0.2, 0.1];++type AnalysisMode = 'portfolio' | 'options' | 'entropy' | 'optimization';++interface AnalysisResult {+ metrics_equal_weight?: PortfolioMetrics;+ metrics_exp_decay?: PortfolioMetrics;+ n_scenarios?: number;+ n_assets?: number;+ assets?: string[];+ half_life?: number;+ alpha?: number;+}++export function FortitudoPanel() {+ const [isFortitudoAvailable, setIsFortitudoAvailable] = useState<boolean | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);+ const [activeMode, setActiveMode] = useState<AnalysisMode>('portfolio');++ // Portfolio config+ const [weights, setWeights] = useState('[0.4, 0.3, 0.2, 0.1]');+ const [alpha, setAlpha] = useState(0.05);+ const [halfLife, setHalfLife] = useState(252);++ // Option pricing config+ const [spotPrice, setSpotPrice] = useState(100);+ const [strike, setStrike] = useState(100);+ const [volatility, setVolatility] = useState(0.25);+ const [riskFreeRate, setRiskFreeRate] = useState(0.05);+ const [dividendYield, setDividendYield] = useState(0.02);+ const [timeToMaturity, setTimeToMaturity] = useState(1.0);+ const [optionResult, setOptionResult] = useState<any>(null);+ const [greeksResult, setGreeksResult] = useState<OptionGreeksResponse | null>(null);++ // Entropy pooling config+ const [nScenarios, setNScenarios] = useState(100);+ const [maxProbability, setMaxProbability] = useState(0.05);+ const [entropyResult, setEntropyResult] = useState<any>(null);++ // Optimization config+ const [optimizationObjective, setOptimizationObjective] = useState<OptimizationObjective>('min_variance');+ const [optimizationType, setOptimizationType] = useState<'mv' | 'cvar'>('mv');+ const [optLongOnly, setOptLongOnly] = useState(true);+ const [optMaxWeight, setOptMaxWeight] = useState(0.5);+ const [optMinWeight, setOptMinWeight] = useState(0.0);+ const [optTargetReturn, setOptTargetReturn] = useState(0.08);+ const [optAlpha, setOptAlpha] = useState(0.05);+ const [optimizationResult, setOptimizationResult] = useState<OptimizationResult | null>(null);+ const [frontierResult, setFrontierResult] = useState<EfficientFrontierResponse | null>(null);+ const [nFrontierPoints, setNFrontierPoints] = useState(20);+ const [selectedFrontierIndex, setSelectedFrontierIndex] = useState<number | null>(null);++ const [expandedSections, setExpandedSections] = useState({+ config: true,+ metrics: true,+ comparison: true,+ matrix: false+ });++ // User portfolio integration+ const [userPortfolios, setUserPortfolios] = useState<Portfolio[]>([]);+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string | null>(null);+ const [selectedPortfolioSummary, setSelectedPortfolioSummary] = useState<PortfolioSummary | null>(null);+ const [portfolioReturnsData, setPortfolioReturnsData] = useState<PortfolioReturnsData | null>(null);+ const [dataSource, setDataSource] = useState<'sample' | 'portfolio'>('sample');+ const [isLoadingPortfolio, setIsLoadingPortfolio] = useState(false);+ const [historicalDays, setHistoricalDays] = useState(252);++ // Check fortitudo availability on mount+ useEffect(() => {+ checkFortitudoStatus();+ loadUserPortfolios();+ }, []);++ // Load portfolio summary and returns when selected+ useEffect(() => {+ if (selectedPortfolioId && dataSource === 'portfolio') {+ loadPortfolioData(selectedPortfolioId);+ }+ }, [selectedPortfolioId, dataSource]);++ const loadUserPortfolios = async () => {+ try {+ const portfolios = await portfolioFortitudoService.getAvailablePortfolios();+ setUserPortfolios(portfolios);+ } catch (err) {+ console.error('[FortitudoPanel] Failed to load portfolios:', err);+ }+ };++ const loadPortfolioData = async (portfolioId: string) => {+ setIsLoadingPortfolio(true);+ setError(null);+ try {+ const summary = await portfolioFortitudoService.getPortfolioSummary(portfolioId);+ setSelectedPortfolioSummary(summary);++ if (summary && summary.holdings.length > 0) {+ const returns = await portfolioFortitudoService.fetchHistoricalReturns(summary.holdings, historicalDays);+ setPortfolioReturnsData(returns);++ // Auto-update weights from portfolio+ if (returns) {+ setWeights(JSON.stringify(Object.values(returns.weights).map(w => Math.round(w * 1000) / 1000)));+ }+ }+ } catch (err) {+ setError(`Failed to load portfolio data: ${err}`);+ } finally {+ setIsLoadingPortfolio(false);+ }+ };++ const checkFortitudoStatus = async () => {+ try {+ const status = await fortitudoService.checkStatus();+ setIsFortitudoAvailable(status.available);+ if (!status.available) {+ setError('Fortitudo.tech library not installed. Run: pip install fortitudo.tech cvxopt');+ }+ } catch (err) {+ setIsFortitudoAvailable(false);+ setError('Failed to check fortitudo.tech status');+ }+ };++ const runPortfolioAnalysis = async () => {+ setIsLoading(true);+ setError(null);++ try {+ let returnsData: Record<string, Record<string, number>>;+ let weightsArray: number[];++ if (dataSource === 'portfolio' && portfolioReturnsData) {+ // Use user portfolio data+ returnsData = portfolioReturnsData.returns;+ weightsArray = Object.values(portfolioReturnsData.weights);+ } else {+ // Use sample data+ returnsData = SAMPLE_RETURNS;+ weightsArray = JSON.parse(weights);+ }++ const result = await fortitudoService.fullAnalysis(+ returnsData,+ weightsArray,+ alpha,+ halfLife+ );++ if (result.success && result.analysis) {+ // Add asset names from portfolio data if available+ if (dataSource === 'portfolio' && portfolioReturnsData) {+ result.analysis.assets = portfolioReturnsData.assets;+ }+ setAnalysisResult(result.analysis);+ } else {+ setError(result.error || 'Analysis failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const runOptionPricing = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const result = await fortitudoService.optionPricing(+ spotPrice,+ strike,+ volatility,+ riskFreeRate,+ dividendYield,+ timeToMaturity+ );++ if (result.success) {+ setOptionResult(result);+ } else {+ setError(result.error || 'Option pricing failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const runOptionGreeks = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const result = await fortitudoService.optionGreeks(+ spotPrice,+ strike,+ volatility,+ riskFreeRate,+ dividendYield,+ timeToMaturity+ );++ if (result.success) {+ setGreeksResult(result);+ } else {+ setError(result.error || 'Greeks calculation failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const runEntropyPooling = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const result = await fortitudoService.entropyPooling(nScenarios, maxProbability);++ if (result.success) {+ setEntropyResult(result);+ } else {+ setError(result.error || 'Entropy pooling failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const runOptimization = async () => {+ setIsLoading(true);+ setError(null);++ try {+ // Use portfolio data if available, otherwise sample data+ const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)+ ? portfolioReturnsData.returns+ : SAMPLE_RETURNS;++ let result: OptimizationResult;++ if (optimizationType === 'mv') {+ result = await fortitudoService.optimizeMeanVariance(+ returnsData,+ optimizationObjective,+ optLongOnly,+ optMaxWeight,+ optMinWeight,+ riskFreeRate,+ optimizationObjective === 'target_return' ? optTargetReturn : undefined+ );+ } else {+ result = await fortitudoService.optimizeMeanCVaR(+ returnsData,+ optimizationObjective === 'min_variance' ? 'min_cvar' : optimizationObjective,+ optAlpha,+ optLongOnly,+ optMaxWeight,+ optMinWeight,+ riskFreeRate,+ optimizationObjective === 'target_return' ? optTargetReturn : undefined+ );+ }++ // Add asset names from portfolio if available+ if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {+ result.assets = portfolioReturnsData.assets;+ }++ if (result.success) {+ setOptimizationResult(result);+ } else {+ setError(result.error || 'Optimization failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const runEfficientFrontier = async () => {+ setIsLoading(true);+ setError(null);++ try {+ // Use portfolio data if available, otherwise sample data+ const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)+ ? portfolioReturnsData.returns+ : SAMPLE_RETURNS;++ let result: EfficientFrontierResponse;++ if (optimizationType === 'mv') {+ result = await fortitudoService.efficientFrontierMV(+ returnsData,+ nFrontierPoints,+ optLongOnly,+ optMaxWeight,+ riskFreeRate+ );+ } else {+ result = await fortitudoService.efficientFrontierCVaR(+ returnsData,+ nFrontierPoints,+ optAlpha,+ optLongOnly,+ optMaxWeight+ );+ }++ // Add asset names from portfolio if available+ if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {+ result.assets = portfolioReturnsData.assets;+ }++ if (result.success) {+ setFrontierResult(result);+ setSelectedFrontierIndex(null); // Reset selection on new data+ } else {+ setError(result.error || 'Efficient frontier generation failed');+ }+ } catch (err) {+ setError(String(err));+ } finally {+ setIsLoading(false);+ }+ };++ const toggleSection = (section: keyof typeof expandedSections) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ };++ const formatPercent = (value: number | null | undefined) => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${(value * 100).toFixed(2)}%`;+ };++ const formatRatio = (value: number | null | undefined) => {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(3);+ };++ // Helper to normalize weights from object or array to array with asset names+ const normalizeWeights = (+ weights: number[] | Record<string, number> | undefined,+ assets: string[] | undefined+ ): { asset: string; weight: number }[] => {+ if (!weights) return [];++ if (Array.isArray(weights)) {+ return weights.map((w, idx) => ({+ asset: assets?.[idx] || `Asset ${idx + 1}`,+ weight: w+ }));+ } else {+ // weights is an object {assetName: weight}+ return Object.entries(weights).map(([asset, weight]) => ({+ asset,+ weight: weight as number+ }));+ }+ };++ // Render unavailable state+ if (isFortitudoAvailable === false) {+ return (+ <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="max-w-lg text-center">+ <AlertCircle size={64} color={BLOOMBERG.RED} className="mx-auto mb-6" />+ <h2 className="text-2xl font-bold uppercase tracking-wide mb-4" style={{ color: BLOOMBERG.WHITE }}>+ FORTITUDO.TECH NOT INSTALLED+ </h2>+ <p className="text-sm font-mono mb-6" style={{ color: BLOOMBERG.GRAY }}>+ Install the library to enable portfolio risk analytics:+ </p>+ <code+ className="block p-4 rounded text-sm font-mono mb-6"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, color: BLOOMBERG.ORANGE }}+ >+ pip install fortitudo.tech cvxopt+ </code>+ <button+ onClick={checkFortitudoStatus}+ className="px-6 py-2 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors inline-flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ <RefreshCw size={16} />+ RETRY+ </button>+ </div>+ </div>+ );+ }++ // Loading state+ if (isFortitudoAvailable === null) {+ return (+ <div className="flex items-center justify-center h-full" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <RefreshCw size={48} color={BLOOMBERG.ORANGE} className="animate-spin" />+ </div>+ );+ }++ return (+ <div className="h-full overflow-auto" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="p-4 space-y-4">+ {/* Header */}+ <div+ className="flex items-center justify-between p-3 rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <div className="flex items-center gap-3">+ <div className="p-2 rounded" style={{ backgroundColor: BLOOMBERG.ORANGE }}>+ <Shield size={20} color={BLOOMBERG.DARK_BG} />+ </div>+ <div>+ <h2 className="font-bold text-sm uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ FORTITUDO.TECH RISK ANALYTICS+ </h2>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ VaR, CVaR, Option Pricing, Entropy Pooling+ </p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <CheckCircle2 size={16} color={BLOOMBERG.GREEN} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GREEN }}>READY</span>+ </div>+ </div>++ {/* Mode Selector */}+ <div+ className="flex rounded border overflow-hidden"+ style={{ borderColor: BLOOMBERG.BORDER }}+ >+ {[+ { id: 'portfolio', label: 'PORTFOLIO RISK', icon: Shield },+ { id: 'options', label: 'OPTION PRICING', icon: DollarSign },+ { id: 'optimization', label: 'OPTIMIZATION', icon: Target },+ { id: 'entropy', label: 'ENTROPY', icon: Layers }+ ].map(mode => (+ <button+ key={mode.id}+ onClick={() => setActiveMode(mode.id as AnalysisMode)}+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-xs font-semibold uppercase tracking-wide transition-all"+ style={{+ backgroundColor: activeMode === mode.id ? BLOOMBERG.ORANGE : BLOOMBERG.PANEL_BG,+ color: activeMode === mode.id ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ <mode.icon size={14} />+ {mode.label}+ </button>+ ))}+ </div>++ {/* Data Source Selector */}+ <div+ className="p-3 rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <Database size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ DATA SOURCE+ </span>+ </div>+ <div className="flex items-center gap-2">+ <div className="flex rounded border overflow-hidden" style={{ borderColor: BLOOMBERG.BORDER }}>+ <button+ onClick={() => setDataSource('sample')}+ className="px-3 py-1.5 text-xs font-bold uppercase transition-all"+ style={{+ backgroundColor: dataSource === 'sample' ? BLOOMBERG.ORANGE : BLOOMBERG.DARK_BG,+ color: dataSource === 'sample' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ SAMPLE DATA+ </button>+ <button+ onClick={() => setDataSource('portfolio')}+ className="px-3 py-1.5 text-xs font-bold uppercase transition-all flex items-center gap-1"+ style={{+ backgroundColor: dataSource === 'portfolio' ? BLOOMBERG.CYAN : BLOOMBERG.DARK_BG,+ color: dataSource === 'portfolio' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ <Briefcase size={12} />+ MY PORTFOLIOS+ </button>+ </div>+ </div>+ </div>++ {/* Portfolio Selector (shown when portfolio data source is selected) */}+ {dataSource === 'portfolio' && (+ <div className="mt-3 pt-3 border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <div className="grid grid-cols-3 gap-4">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ SELECT PORTFOLIO+ </label>+ <select+ value={selectedPortfolioId || ''}+ onChange={e => setSelectedPortfolioId(e.target.value || null)}+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ >+ <option value="">-- Select Portfolio --</option>+ {userPortfolios.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ HISTORICAL DAYS+ </label>+ <input+ type="number"+ value={historicalDays}+ onChange={e => setHistoricalDays(parseInt(e.target.value))}+ min="30"+ max="1000"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div className="flex items-end">+ <button+ onClick={() => selectedPortfolioId && loadPortfolioData(selectedPortfolioId)}+ disabled={!selectedPortfolioId || isLoadingPortfolio}+ className="px-4 py-2 rounded font-bold uppercase tracking-wide text-xs hover:bg-opacity-90 transition-colors flex items-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.CYAN, color: BLOOMBERG.DARK_BG }}+ >+ {isLoadingPortfolio ? (+ <RefreshCw size={14} className="animate-spin" />+ ) : (+ <RefreshCw size={14} />+ )}+ LOAD DATA+ </button>+ </div>+ </div>++ {/* Portfolio Summary */}+ {selectedPortfolioSummary && portfolioReturnsData && (+ <div className="mt-3 p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="flex items-center gap-6 text-xs font-mono">+ <span style={{ color: BLOOMBERG.GRAY }}>+ Portfolio: <span style={{ color: BLOOMBERG.WHITE }}>{selectedPortfolioSummary.portfolio.name}</span>+ </span>+ <span style={{ color: BLOOMBERG.GRAY }}>+ Holdings: <span style={{ color: BLOOMBERG.CYAN }}>{selectedPortfolioSummary.holdings.length}</span>+ </span>+ <span style={{ color: BLOOMBERG.GRAY }}>+ Data Points: <span style={{ color: BLOOMBERG.CYAN }}>{portfolioReturnsData.nScenarios}</span>+ </span>+ <span style={{ color: BLOOMBERG.GRAY }}>+ Period: <span style={{ color: BLOOMBERG.WHITE }}>{portfolioReturnsData.startDate} to {portfolioReturnsData.endDate}</span>+ </span>+ </div>+ <div className="mt-2 flex flex-wrap gap-2">+ {portfolioReturnsData.assets.map((asset, idx) => (+ <span+ key={asset}+ className="px-2 py-0.5 rounded text-xs font-mono"+ style={{ backgroundColor: BLOOMBERG.BORDER, color: BLOOMBERG.WHITE }}+ >+ {asset}: {(portfolioReturnsData.weights[asset] * 100).toFixed(1)}%+ </span>+ ))}+ </div>+ </div>+ )}++ {/* No portfolios message */}+ {userPortfolios.length === 0 && (+ <div className="mt-3 p-3 rounded text-center" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ No portfolios found. Create a portfolio in the Portfolio tab first.+ </p>+ </div>+ )}+ </div>+ )}+ </div>++ {/* Error Display */}+ {error && (+ <div+ className="flex items-start gap-3 p-3 rounded border"+ style={{ backgroundColor: '#1a0000', borderColor: BLOOMBERG.RED }}+ >+ <AlertCircle size={18} color={BLOOMBERG.RED} className="flex-shrink-0 mt-0.5" />+ <div>+ <p className="text-sm font-bold" style={{ color: BLOOMBERG.RED }}>Error</p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>{error}</p>+ </div>+ </div>+ )}++ {/* Portfolio Risk Mode */}+ {activeMode === 'portfolio' && (+ <>+ {/* Configuration */}+ <div+ className="rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <button+ onClick={() => toggleSection('config')}+ className="w-full flex items-center justify-between p-3"+ >+ <div className="flex items-center gap-2">+ <Settings size={16} color={BLOOMBERG.ORANGE} />+ <span className="text-sm font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ CONFIGURATION+ </span>+ </div>+ {expandedSections.config ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.config && (+ <div className="p-4 border-t space-y-4" style={{ borderColor: BLOOMBERG.BORDER }}>+ <div className="grid grid-cols-3 gap-4">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ PORTFOLIO WEIGHTS+ </label>+ <input+ type="text"+ value={weights}+ onChange={e => setWeights(e.target.value)}+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ ALPHA (VaR/CVaR)+ </label>+ <input+ type="number"+ value={alpha}+ onChange={e => setAlpha(parseFloat(e.target.value))}+ step="0.01"+ min="0.01"+ max="0.50"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ HALF-LIFE (DAYS)+ </label>+ <input+ type="number"+ value={halfLife}+ onChange={e => setHalfLife(parseInt(e.target.value))}+ min="20"+ max="504"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ </div>++ <button+ onClick={runPortfolioAnalysis}+ disabled={isLoading}+ className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <Play size={16} />+ )}+ RUN PORTFOLIO ANALYSIS+ </button>+ </div>+ )}+ </div>++ {/* Results */}+ {analysisResult && (+ <>+ {/* Metrics Comparison */}+ <div+ className="rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <button+ onClick={() => toggleSection('metrics')}+ className="w-full flex items-center justify-between p-3"+ >+ <div className="flex items-center gap-2">+ <BarChart2 size={16} color={BLOOMBERG.CYAN} />+ <span className="text-sm font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ RISK METRICS+ </span>+ </div>+ {expandedSections.metrics ? (+ <ChevronUp size={16} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={16} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.metrics && (+ <div className="p-4 border-t" style={{ borderColor: BLOOMBERG.BORDER }}>+ <div className="grid grid-cols-2 gap-6">+ {/* Equal Weight Metrics */}+ <div>+ <h3 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.ORANGE }}>+ EQUAL WEIGHT SCENARIOS+ </h3>+ {analysisResult.metrics_equal_weight && (+ <div className="space-y-2">+ <MetricRow+ label="Expected Return"+ value={formatPercent(analysisResult.metrics_equal_weight.expected_return)}+ positive={analysisResult.metrics_equal_weight.expected_return > 0}+ />+ <MetricRow+ label="Volatility"+ value={formatPercent(analysisResult.metrics_equal_weight.volatility)}+ />+ <MetricRow+ label={`VaR (${(1 - alpha) * 100}%)`}+ value={formatPercent(analysisResult.metrics_equal_weight.var)}+ negative+ />+ <MetricRow+ label={`CVaR (${(1 - alpha) * 100}%)`}+ value={formatPercent(analysisResult.metrics_equal_weight.cvar)}+ negative+ />+ <MetricRow+ label="Sharpe Ratio"+ value={formatRatio(analysisResult.metrics_equal_weight.sharpe_ratio)}+ positive={analysisResult.metrics_equal_weight.sharpe_ratio > 0}+ />+ </div>+ )}+ </div>++ {/* Exp Decay Metrics */}+ <div>+ <h3 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.CYAN }}>+ EXP DECAY WEIGHTED ({halfLife}d)+ </h3>+ {analysisResult.metrics_exp_decay && (+ <div className="space-y-2">+ <MetricRow+ label="Expected Return"+ value={formatPercent(analysisResult.metrics_exp_decay.expected_return)}+ positive={analysisResult.metrics_exp_decay.expected_return > 0}+ />+ <MetricRow+ label="Volatility"+ value={formatPercent(analysisResult.metrics_exp_decay.volatility)}+ />+ <MetricRow+ label={`VaR (${(1 - alpha) * 100}%)`}+ value={formatPercent(analysisResult.metrics_exp_decay.var)}+ negative+ />+ <MetricRow+ label={`CVaR (${(1 - alpha) * 100}%)`}+ value={formatPercent(analysisResult.metrics_exp_decay.cvar)}+ negative+ />+ <MetricRow+ label="Sharpe Ratio"+ value={formatRatio(analysisResult.metrics_exp_decay.sharpe_ratio)}+ positive={analysisResult.metrics_exp_decay.sharpe_ratio > 0}+ />+ </div>+ )}+ </div>+ </div>++ {/* Summary */}+ <div+ className="mt-4 p-3 rounded"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex items-center gap-6 text-xs font-mono">+ <span style={{ color: BLOOMBERG.GRAY }}>+ Scenarios: <span style={{ color: BLOOMBERG.WHITE }}>{analysisResult.n_scenarios}</span>+ </span>+ <span style={{ color: BLOOMBERG.GRAY }}>+ Assets: <span style={{ color: BLOOMBERG.WHITE }}>{analysisResult.n_assets}</span>+ </span>+ <span style={{ color: BLOOMBERG.GRAY }}>+ Alpha: <span style={{ color: BLOOMBERG.WHITE }}>{alpha}</span>+ </span>+ </div>+ </div>+ </div>+ )}+ </div>+ </>+ )}+ </>+ )}++ {/* Option Pricing Mode */}+ {activeMode === 'options' && (+ <div+ className="rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <div className="p-4 space-y-4">+ <div className="grid grid-cols-6 gap-4">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ SPOT PRICE+ </label>+ <input+ type="number"+ value={spotPrice}+ onChange={e => setSpotPrice(parseFloat(e.target.value))}+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ STRIKE+ </label>+ <input+ type="number"+ value={strike}+ onChange={e => setStrike(parseFloat(e.target.value))}+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ VOLATILITY+ </label>+ <input+ type="number"+ value={volatility}+ onChange={e => setVolatility(parseFloat(e.target.value))}+ step="0.01"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ RISK-FREE RATE+ </label>+ <input+ type="number"+ value={riskFreeRate}+ onChange={e => setRiskFreeRate(parseFloat(e.target.value))}+ step="0.01"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ DIV YIELD+ </label>+ <input+ type="number"+ value={dividendYield}+ onChange={e => setDividendYield(parseFloat(e.target.value))}+ step="0.01"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ TIME (YEARS)+ </label>+ <input+ type="number"+ value={timeToMaturity}+ onChange={e => setTimeToMaturity(parseFloat(e.target.value))}+ step="0.1"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ </div>++ <div className="grid grid-cols-2 gap-4">+ <button+ onClick={runOptionPricing}+ disabled={isLoading}+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <DollarSign size={16} />+ )}+ PRICE OPTIONS+ </button>+ <button+ onClick={runOptionGreeks}+ disabled={isLoading}+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.CYAN, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <Activity size={16} />+ )}+ CALCULATE GREEKS+ </button>+ </div>++ {/* Option Results */}+ {optionResult && optionResult.success && (+ <div className="grid grid-cols-4 gap-4 mt-4">+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>FORWARD</p>+ <p className="text-lg font-bold" style={{ color: BLOOMBERG.WHITE }}>+ ${optionResult.forward_price?.toFixed(2)}+ </p>+ </div>+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>CALL PRICE</p>+ <p className="text-lg font-bold" style={{ color: BLOOMBERG.GREEN }}>+ ${optionResult.call_price?.toFixed(4)}+ </p>+ </div>+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>PUT PRICE</p>+ <p className="text-lg font-bold" style={{ color: BLOOMBERG.RED }}>+ ${optionResult.put_price?.toFixed(4)}+ </p>+ </div>+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>STRADDLE</p>+ <p className="text-lg font-bold" style={{ color: BLOOMBERG.CYAN }}>+ ${optionResult.straddle?.straddle_price?.toFixed(4)}+ </p>+ </div>+ </div>+ )}++ {/* Greeks Results */}+ {greeksResult && greeksResult.success && (+ <div className="mt-4 p-4 rounded border" style={{ backgroundColor: BLOOMBERG.DARK_BG, borderColor: BLOOMBERG.BORDER }}>+ <h3 className="text-sm font-bold uppercase mb-4" style={{ color: BLOOMBERG.CYAN }}>+ OPTION GREEKS+ </h3>+ <div className="grid grid-cols-2 gap-6">+ {/* Call Greeks */}+ <div>+ <h4 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.GREEN }}>+ CALL OPTION+ </h4>+ <div className="space-y-2">+ <GreekRow label="Delta (Δ)" value={greeksResult.call?.delta} description="Price sensitivity" />+ <GreekRow label="Gamma (Γ)" value={greeksResult.call?.gamma} description="Delta sensitivity" />+ <GreekRow label="Vega (ν)" value={greeksResult.call?.vega} description="Volatility sensitivity" />+ <GreekRow label="Theta (Θ)" value={greeksResult.call?.theta} description="Time decay (daily)" />+ <GreekRow label="Rho (ρ)" value={greeksResult.call?.rho} description="Rate sensitivity" />+ </div>+ </div>+ {/* Put Greeks */}+ <div>+ <h4 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.RED }}>+ PUT OPTION+ </h4>+ <div className="space-y-2">+ <GreekRow label="Delta (Δ)" value={greeksResult.put?.delta} description="Price sensitivity" />+ <GreekRow label="Gamma (Γ)" value={greeksResult.put?.gamma} description="Delta sensitivity" />+ <GreekRow label="Vega (ν)" value={greeksResult.put?.vega} description="Volatility sensitivity" />+ <GreekRow label="Theta (Θ)" value={greeksResult.put?.theta} description="Time decay (daily)" />+ <GreekRow label="Rho (ρ)" value={greeksResult.put?.rho} description="Rate sensitivity" />+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ )}++ {/* Portfolio Optimization Mode */}+ {activeMode === 'optimization' && (+ <div+ className="rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <div className="p-4 space-y-4">+ {/* Optimization Type Toggle */}+ <div className="flex rounded border overflow-hidden" style={{ borderColor: BLOOMBERG.BORDER }}>+ <button+ onClick={() => setOptimizationType('mv')}+ className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"+ style={{+ backgroundColor: optimizationType === 'mv' ? BLOOMBERG.ORANGE : BLOOMBERG.DARK_BG,+ color: optimizationType === 'mv' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ MEAN-VARIANCE+ </button>+ <button+ onClick={() => setOptimizationType('cvar')}+ className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"+ style={{+ backgroundColor: optimizationType === 'cvar' ? BLOOMBERG.CYAN : BLOOMBERG.DARK_BG,+ color: optimizationType === 'cvar' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ MEAN-CVaR+ </button>+ </div>++ {/* Configuration */}+ <div className="grid grid-cols-4 gap-4">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ OBJECTIVE+ </label>+ <select+ value={optimizationObjective}+ onChange={e => setOptimizationObjective(e.target.value as OptimizationObjective)}+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ >+ <option value="min_variance">{optimizationType === 'mv' ? 'Min Variance' : 'Min CVaR'}</option>+ <option value="max_sharpe">Max Sharpe</option>+ <option value="target_return">Target Return</option>+ </select>+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ MAX WEIGHT+ </label>+ <input+ type="number"+ value={optMaxWeight}+ onChange={e => setOptMaxWeight(parseFloat(e.target.value))}+ step="0.05"+ min="0.1"+ max="1.0"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ {optimizationObjective === 'target_return' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ TARGET RETURN+ </label>+ <input+ type="number"+ value={optTargetReturn}+ onChange={e => setOptTargetReturn(parseFloat(e.target.value))}+ step="0.01"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ )}+ {optimizationType === 'cvar' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ CVaR ALPHA+ </label>+ <input+ type="number"+ value={optAlpha}+ onChange={e => setOptAlpha(parseFloat(e.target.value))}+ step="0.01"+ min="0.01"+ max="0.50"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ )}+ <div className="flex items-end">+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={optLongOnly}+ onChange={e => setOptLongOnly(e.target.checked)}+ className="w-4 h-4"+ />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>LONG ONLY</span>+ </label>+ </div>+ </div>++ {/* Buttons */}+ <div className="grid grid-cols-2 gap-4">+ <button+ onClick={runOptimization}+ disabled={isLoading}+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <Target size={16} />+ )}+ OPTIMIZE PORTFOLIO+ </button>+ <button+ onClick={runEfficientFrontier}+ disabled={isLoading}+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.CYAN, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <TrendingUp size={16} />+ )}+ EFFICIENT FRONTIER+ </button>+ </div>++ {/* Optimization Result */}+ {optimizationResult && optimizationResult.success && (() => {+ const normalizedWeights = normalizeWeights(optimizationResult.weights, optimizationResult.assets);+ const PIE_COLORS = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW, BLOOMBERG.BLUE, BLOOMBERG.RED];+ return (+ <div className="p-4 rounded border" style={{ backgroundColor: BLOOMBERG.DARK_BG, borderColor: BLOOMBERG.BORDER }}>+ <h3 className="text-sm font-bold uppercase mb-4" style={{ color: BLOOMBERG.ORANGE }}>+ OPTIMAL PORTFOLIO+ </h3>+ <div className="grid grid-cols-3 gap-6">+ {/* Pie Chart */}+ <div>+ <h4 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.CYAN }}>+ ALLOCATION+ </h4>+ <div style={{ height: 180 }}>+ <ResponsiveContainer width="100%" height="100%">+ <PieChart>+ <Pie+ data={normalizedWeights+ .filter(item => item.weight > 0.001)+ .map((item, idx) => ({+ name: item.asset,+ value: Math.round(item.weight * 1000) / 10,+ weight: item.weight,+ fill: PIE_COLORS[idx % PIE_COLORS.length]+ }))}+ cx="50%"+ cy="50%"+ innerRadius={35}+ outerRadius={60}+ paddingAngle={2}+ dataKey="value"+ stroke={BLOOMBERG.DARK_BG}+ strokeWidth={2}+ >+ {normalizedWeights+ .filter(item => item.weight > 0.001)+ .map((_, idx) => (+ <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />+ ))}+ </Pie>+ <Tooltip+ contentStyle={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: 4,+ padding: '6px 10px'+ }}+ formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}+ labelStyle={{ color: BLOOMBERG.WHITE, fontWeight: 'bold', fontSize: 11 }}+ itemStyle={{ color: BLOOMBERG.GRAY, fontSize: 10 }}+ />+ </PieChart>+ </ResponsiveContainer>+ </div>+ {/* Pie Legend */}+ <div className="mt-2 space-y-1">+ {normalizedWeights+ .filter(item => item.weight > 0.001)+ .map((item, idx) => (+ <div key={idx} className="flex items-center gap-2">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>{item.asset}</span>+ <span className="text-xs font-mono font-bold ml-auto" style={{ color: BLOOMBERG.WHITE }}>+ {(item.weight * 100).toFixed(1)}%+ </span>+ </div>+ ))}+ </div>+ </div>+ {/* Weight Bars */}+ <div>+ <h4 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.CYAN }}>+ WEIGHTS+ </h4>+ <div className="space-y-2">+ {normalizedWeights.map((item, i) => (+ <div key={i} className="flex items-center justify-between">+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ {item.asset}+ </span>+ <div className="flex items-center gap-2">+ <div+ className="h-2 rounded"+ style={{+ width: `${Math.max(item.weight * 100, 5)}px`,+ backgroundColor: item.weight > 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}+ />+ <span className="text-sm font-mono font-bold" style={{ color: BLOOMBERG.WHITE }}>+ {(item.weight * 100).toFixed(1)}%+ </span>+ </div>+ </div>+ ))}+ </div>+ </div>+ {/* Metrics */}+ <div>+ <h4 className="text-xs font-bold uppercase mb-3" style={{ color: BLOOMBERG.CYAN }}>+ METRICS+ </h4>+ <div className="space-y-2">+ <MetricRow+ label="Expected Return"+ value={formatPercent(optimizationResult.expected_return)}+ positive={(optimizationResult.expected_return ?? 0) > 0}+ />+ <MetricRow+ label="Volatility"+ value={formatPercent(optimizationResult.volatility)}+ />+ <MetricRow+ label="Sharpe Ratio"+ value={formatRatio(optimizationResult.sharpe_ratio)}+ positive={(optimizationResult.sharpe_ratio ?? 0) > 0}+ />+ {optimizationResult.cvar !== undefined && (+ <MetricRow+ label="CVaR"+ value={formatPercent(optimizationResult.cvar)}+ negative+ />+ )}+ </div>+ {/* Optimization Info */}+ <div className="mt-4 p-2 rounded" style={{ backgroundColor: BLOOMBERG.PANEL_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Type: <span style={{ color: optimizationType === 'mv' ? BLOOMBERG.ORANGE : BLOOMBERG.CYAN }}>+ {optimizationType === 'mv' ? 'Mean-Variance' : 'Mean-CVaR'}+ </span>+ </p>+ <p className="text-xs font-mono mt-1" style={{ color: BLOOMBERG.GRAY }}>+ Objective: <span style={{ color: BLOOMBERG.WHITE }}>{optimizationObjective.replace('_', ' ').toUpperCase()}</span>+ </p>+ <p className="text-xs font-mono mt-1" style={{ color: BLOOMBERG.GRAY }}>+ Constraints: <span style={{ color: BLOOMBERG.WHITE }}>{optLongOnly ? 'Long Only' : 'Allow Short'}</span>+ </p>+ </div>+ </div>+ </div>+ </div>+ );+ })()}++ {/* Efficient Frontier Result */}+ {frontierResult && frontierResult.success && frontierResult.frontier && (+ <div className="p-4 rounded border" style={{ backgroundColor: BLOOMBERG.DARK_BG, borderColor: BLOOMBERG.BORDER }}>+ <h3 className="text-sm font-bold uppercase mb-4" style={{ color: BLOOMBERG.CYAN }}>+ EFFICIENT FRONTIER ({frontierResult.frontier.length} POINTS)+ </h3>++ {/* Chart Visualization */}+ <div className="mb-4" style={{ height: 300 }}>+ <ResponsiveContainer width="100%" height="100%">+ <ComposedChart+ margin={{ top: 20, right: 30, left: 20, bottom: 20 }}+ >+ <CartesianGrid+ strokeDasharray="3 3"+ stroke={BLOOMBERG.BORDER}+ vertical={true}+ />+ <XAxis+ type="number"+ dataKey="risk"+ name={optimizationType === 'mv' ? 'Volatility' : 'CVaR'}+ domain={['auto', 'auto']}+ tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}+ stroke={BLOOMBERG.GRAY}+ tick={{ fill: BLOOMBERG.GRAY, fontSize: 10 }}+ label={{+ value: optimizationType === 'mv' ? 'VOLATILITY (%)' : 'CVaR (%)',+ position: 'bottom',+ fill: BLOOMBERG.GRAY,+ fontSize: 10,+ offset: 0+ }}+ />+ <YAxis+ type="number"+ dataKey="return"+ name="Expected Return"+ domain={['auto', 'auto']}+ tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}+ stroke={BLOOMBERG.GRAY}+ tick={{ fill: BLOOMBERG.GRAY, fontSize: 10 }}+ label={{+ value: 'EXPECTED RETURN (%)',+ angle: -90,+ position: 'insideLeft',+ fill: BLOOMBERG.GRAY,+ fontSize: 10+ }}+ />+ <Tooltip+ contentStyle={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: 4,+ padding: '8px 12px'+ }}+ formatter={(value: number, name: string) => {+ if (name === 'return') return [`${(value * 100).toFixed(2)}%`, 'Return'];+ if (name === 'risk') return [`${(value * 100).toFixed(2)}%`, optimizationType === 'mv' ? 'Volatility' : 'CVaR'];+ if (name === 'sharpe') return [value.toFixed(3), 'Sharpe'];+ return [value, name];+ }}+ labelStyle={{ color: BLOOMBERG.WHITE }}+ itemStyle={{ color: BLOOMBERG.GRAY }}+ />+ {/* Frontier Line */}+ <Line+ data={frontierResult.frontier.map((point, idx) => ({+ risk: point.volatility ?? point.cvar ?? 0,+ return: point.expected_return,+ sharpe: point.sharpe_ratio ?? 0,+ index: idx+ }))}+ type="monotone"+ dataKey="return"+ stroke={BLOOMBERG.CYAN}+ strokeWidth={2}+ dot={false}+ />+ {/* Frontier Points */}+ <Scatter+ data={frontierResult.frontier.map((point, idx) => ({+ risk: point.volatility ?? point.cvar ?? 0,+ return: point.expected_return,+ sharpe: point.sharpe_ratio ?? 0,+ index: idx,+ isMaxSharpe: point.sharpe_ratio === Math.max(...frontierResult.frontier!.map(p => p.sharpe_ratio ?? 0))+ }))}+ fill={BLOOMBERG.ORANGE}+ onClick={(data: any) => {+ if (data && typeof data.index === 'number') {+ setSelectedFrontierIndex(data.index);+ }+ }}+ cursor="pointer"+ >+ {frontierResult.frontier.map((point, idx) => {+ const maxSharpe = Math.max(...frontierResult.frontier!.map(p => p.sharpe_ratio ?? 0));+ const isMaxSharpe = point.sharpe_ratio === maxSharpe;+ const isMinRisk = idx === 0;+ const isSelected = selectedFrontierIndex === idx;+ return (+ <Cell+ key={idx}+ fill={isSelected ? BLOOMBERG.YELLOW : isMaxSharpe ? BLOOMBERG.GREEN : isMinRisk ? BLOOMBERG.ORANGE : BLOOMBERG.CYAN}+ stroke={isSelected ? BLOOMBERG.WHITE : 'none'}+ strokeWidth={isSelected ? 2 : 0}+ r={isSelected ? 8 : isMaxSharpe || isMinRisk ? 6 : 4}+ />+ );+ })}+ </Scatter>+ </ComposedChart>+ </ResponsiveContainer>+ </div>++ {/* Legend */}+ <div className="flex items-center justify-center gap-6 mb-4">+ <div className="flex items-center gap-2">+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: BLOOMBERG.ORANGE }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>MIN RISK</span>+ </div>+ <div className="flex items-center gap-2">+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: BLOOMBERG.GREEN }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>MAX SHARPE</span>+ </div>+ <div className="flex items-center gap-2">+ <div className="w-3 h-3 rounded-full" style={{ backgroundColor: BLOOMBERG.CYAN }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>FRONTIER</span>+ </div>+ {selectedFrontierIndex !== null && (+ <div className="flex items-center gap-2">+ <div className="w-3 h-3 rounded-full border-2" style={{ backgroundColor: BLOOMBERG.YELLOW, borderColor: BLOOMBERG.WHITE }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.YELLOW }}>SELECTED</span>+ </div>+ )}+ </div>++ {/* Selected Portfolio Details */}+ {selectedFrontierIndex !== null && frontierResult.frontier[selectedFrontierIndex] && (+ <div+ className="mb-4 p-4 rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.YELLOW }}+ >+ <div className="flex items-center justify-between mb-3">+ <h4 className="text-sm font-bold uppercase" style={{ color: BLOOMBERG.YELLOW }}>+ SELECTED PORTFOLIO (#{selectedFrontierIndex + 1})+ </h4>+ <button+ onClick={() => setSelectedFrontierIndex(null)}+ className="text-xs font-mono px-2 py-1 rounded hover:bg-opacity-80"+ style={{ backgroundColor: BLOOMBERG.BORDER, color: BLOOMBERG.GRAY }}+ >+ CLEAR+ </button>+ </div>+ <div className="grid grid-cols-3 gap-6">+ {/* Pie Chart */}+ <div>+ <h5 className="text-xs font-bold uppercase mb-2" style={{ color: BLOOMBERG.CYAN }}>+ ALLOCATION+ </h5>+ <div style={{ height: 180 }}>+ <ResponsiveContainer width="100%" height="100%">+ <PieChart>+ <Pie+ data={(() => {+ const selectedPoint = frontierResult.frontier[selectedFrontierIndex];+ const weights = selectedPoint.weights;+ const PIE_COLORS = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW, BLOOMBERG.BLUE, BLOOMBERG.RED];+ if (typeof weights === 'object' && !Array.isArray(weights)) {+ return Object.entries(weights)+ .filter(([_, w]) => (w as number) > 0.001)+ .map(([asset, weight], idx) => ({+ name: asset,+ value: Math.round((weight as number) * 1000) / 10,+ fill: PIE_COLORS[idx % PIE_COLORS.length]+ }));+ } else if (Array.isArray(weights)) {+ return weights+ .filter(w => w > 0.001)+ .map((w, idx) => ({+ name: `Asset ${idx + 1}`,+ value: Math.round(w * 1000) / 10,+ fill: PIE_COLORS[idx % PIE_COLORS.length]+ }));+ }+ return [];+ })()}+ cx="50%"+ cy="50%"+ innerRadius={35}+ outerRadius={60}+ paddingAngle={2}+ dataKey="value"+ stroke={BLOOMBERG.DARK_BG}+ strokeWidth={2}+ >+ {(() => {+ const selectedPoint = frontierResult.frontier[selectedFrontierIndex];+ const weights = selectedPoint.weights;+ const PIE_COLORS = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW, BLOOMBERG.BLUE, BLOOMBERG.RED];+ if (typeof weights === 'object' && !Array.isArray(weights)) {+ return Object.entries(weights)+ .filter(([_, w]) => (w as number) > 0.001)+ .map(([asset, _], idx) => (+ <Cell key={asset} fill={PIE_COLORS[idx % PIE_COLORS.length]} />+ ));+ } else if (Array.isArray(weights)) {+ return weights+ .filter(w => w > 0.001)+ .map((_, idx) => (+ <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />+ ));+ }+ return null;+ })()}+ </Pie>+ <Tooltip+ contentStyle={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: 4,+ padding: '6px 10px'+ }}+ formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}+ labelStyle={{ color: BLOOMBERG.WHITE, fontWeight: 'bold', fontSize: 11 }}+ itemStyle={{ color: BLOOMBERG.GRAY, fontSize: 10 }}+ />+ </PieChart>+ </ResponsiveContainer>+ </div>+ {/* Pie Legend */}+ <div className="mt-2 space-y-1">+ {(() => {+ const selectedPoint = frontierResult.frontier[selectedFrontierIndex];+ const weights = selectedPoint.weights;+ const PIE_COLORS = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW, BLOOMBERG.BLUE, BLOOMBERG.RED];+ if (typeof weights === 'object' && !Array.isArray(weights)) {+ return Object.entries(weights)+ .filter(([_, w]) => (w as number) > 0.001)+ .map(([asset, weight], idx) => (+ <div key={asset} className="flex items-center gap-2">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>{asset}</span>+ <span className="text-xs font-mono font-bold ml-auto" style={{ color: BLOOMBERG.WHITE }}>+ {((weight as number) * 100).toFixed(1)}%+ </span>+ </div>+ ));+ } else if (Array.isArray(weights)) {+ return weights+ .filter(w => w > 0.001)+ .map((w, idx) => (+ <div key={idx} className="flex items-center gap-2">+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Asset {idx + 1}</span>+ <span className="text-xs font-mono font-bold ml-auto" style={{ color: BLOOMBERG.WHITE }}>+ {(w * 100).toFixed(1)}%+ </span>+ </div>+ ));+ }+ return null;+ })()}+ </div>+ </div>+ {/* Weight Bars */}+ <div>+ <h5 className="text-xs font-bold uppercase mb-2" style={{ color: BLOOMBERG.CYAN }}>+ WEIGHTS+ </h5>+ <div className="space-y-1">+ {(() => {+ const selectedPoint = frontierResult.frontier[selectedFrontierIndex];+ const weights = selectedPoint.weights;+ if (typeof weights === 'object' && !Array.isArray(weights)) {+ return Object.entries(weights).map(([asset, weight]) => (+ <div key={asset} className="flex items-center justify-between">+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ {asset}+ </span>+ <div className="flex items-center gap-2">+ <div+ className="h-2 rounded"+ style={{+ width: `${Math.max((weight as number) * 80, 3)}px`,+ backgroundColor: (weight as number) > 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}+ />+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.WHITE }}>+ {((weight as number) * 100).toFixed(1)}%+ </span>+ </div>+ </div>+ ));+ } else if (Array.isArray(weights)) {+ return weights.map((w, i) => (+ <div key={i} className="flex items-center justify-between">+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Asset {i + 1}+ </span>+ <div className="flex items-center gap-2">+ <div+ className="h-2 rounded"+ style={{+ width: `${Math.max(w * 80, 3)}px`,+ backgroundColor: w > 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}+ />+ <span className="text-xs font-mono font-bold" style={{ color: BLOOMBERG.WHITE }}>+ {(w * 100).toFixed(1)}%+ </span>+ </div>+ </div>+ ));+ }+ return null;+ })()}+ </div>+ </div>+ {/* Metrics */}+ <div>+ <h5 className="text-xs font-bold uppercase mb-2" style={{ color: BLOOMBERG.CYAN }}>+ METRICS+ </h5>+ <div className="space-y-1">+ <div className="flex items-center justify-between py-1 border-b" style={{ borderColor: BLOOMBERG.BORDER }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Expected Return</span>+ <span className="text-sm font-mono font-bold" style={{ color: BLOOMBERG.GREEN }}>+ {(frontierResult.frontier[selectedFrontierIndex].expected_return * 100).toFixed(2)}%+ </span>+ </div>+ <div className="flex items-center justify-between py-1 border-b" style={{ borderColor: BLOOMBERG.BORDER }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ {optimizationType === 'mv' ? 'Volatility' : 'CVaR'}+ </span>+ <span className="text-sm font-mono font-bold" style={{ color: BLOOMBERG.RED }}>+ {((frontierResult.frontier[selectedFrontierIndex].volatility ?? frontierResult.frontier[selectedFrontierIndex].cvar ?? 0) * 100).toFixed(2)}%+ </span>+ </div>+ <div className="flex items-center justify-between py-1">+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>Sharpe Ratio</span>+ <span className="text-sm font-mono font-bold" style={{ color: BLOOMBERG.WHITE }}>+ {frontierResult.frontier[selectedFrontierIndex].sharpe_ratio?.toFixed(3) ?? 'N/A'}+ </span>+ </div>+ </div>+ {/* Position on Frontier */}+ <div className="mt-4 p-2 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Position: <span style={{ color: BLOOMBERG.YELLOW }}>{selectedFrontierIndex + 1}</span> of {frontierResult.frontier.length}+ </p>+ <p className="text-xs font-mono mt-1" style={{ color: BLOOMBERG.GRAY }}>+ {selectedFrontierIndex === 0 ? (+ <span style={{ color: BLOOMBERG.ORANGE }}>Minimum Risk Portfolio</span>+ ) : selectedFrontierIndex === frontierResult.frontier.length - 1 ? (+ <span style={{ color: BLOOMBERG.CYAN }}>Maximum Return Portfolio</span>+ ) : frontierResult.frontier[selectedFrontierIndex].sharpe_ratio === Math.max(...frontierResult.frontier.map(p => p.sharpe_ratio ?? 0)) ? (+ <span style={{ color: BLOOMBERG.GREEN }}>Maximum Sharpe Portfolio</span>+ ) : (+ <span style={{ color: BLOOMBERG.MUTED }}>Intermediate Portfolio</span>+ )}+ </p>+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Summary Stats */}+ <div className="grid grid-cols-3 gap-4 p-3 rounded" style={{ backgroundColor: BLOOMBERG.PANEL_BG }}>+ <div className="text-center">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>MIN RISK</p>+ <p className="text-sm font-bold" style={{ color: BLOOMBERG.ORANGE }}>+ {((frontierResult.frontier[0]?.volatility ?? frontierResult.frontier[0]?.cvar ?? 0) * 100).toFixed(2)}%+ </p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.MUTED }}>+ Return: {(frontierResult.frontier[0]?.expected_return * 100).toFixed(2)}%+ </p>+ </div>+ <div className="text-center">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>MAX SHARPE</p>+ {(() => {+ const maxSharpePoint = frontierResult.frontier.reduce((max, p) =>+ (p.sharpe_ratio ?? 0) > (max.sharpe_ratio ?? 0) ? p : max+ );+ return (+ <>+ <p className="text-sm font-bold" style={{ color: BLOOMBERG.GREEN }}>+ {maxSharpePoint.sharpe_ratio?.toFixed(3) ?? 'N/A'}+ </p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.MUTED }}>+ Return: {(maxSharpePoint.expected_return * 100).toFixed(2)}%+ </p>+ </>+ );+ })()}+ </div>+ <div className="text-center">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>MAX RETURN</p>+ <p className="text-sm font-bold" style={{ color: BLOOMBERG.CYAN }}>+ {(frontierResult.frontier[frontierResult.frontier.length - 1]?.expected_return * 100).toFixed(2)}%+ </p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.MUTED }}>+ Risk: {((frontierResult.frontier[frontierResult.frontier.length - 1]?.volatility ?? frontierResult.frontier[frontierResult.frontier.length - 1]?.cvar ?? 0) * 100).toFixed(2)}%+ </p>+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ )}++ {/* Entropy Pooling Mode */}+ {activeMode === 'entropy' && (+ <div+ className="rounded border"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, borderColor: BLOOMBERG.BORDER }}+ >+ <div className="p-4 space-y-4">+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ NUMBER OF SCENARIOS+ </label>+ <input+ type="number"+ value={nScenarios}+ onChange={e => setNScenarios(parseInt(e.target.value))}+ min="10"+ max="10000"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ MAX PROBABILITY (%)+ </label>+ <input+ type="number"+ value={maxProbability * 100}+ onChange={e => setMaxProbability(parseFloat(e.target.value) / 100)}+ step="0.5"+ min="0.5"+ max="100"+ className="w-full px-3 py-2 rounded text-sm font-mono border"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.BORDER,+ color: BLOOMBERG.WHITE+ }}+ />+ </div>+ </div>++ <button+ onClick={runEntropyPooling}+ disabled={isLoading}+ className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"+ style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}+ >+ {isLoading ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <Layers size={16} />+ )}+ APPLY ENTROPY POOLING+ </button>++ {/* Entropy Results */}+ {entropyResult && entropyResult.success && (+ <div className="grid grid-cols-2 gap-4 mt-4">+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>PRIOR</p>+ <div className="space-y-1">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ Effective Scenarios: {entropyResult.effective_scenarios_prior?.toFixed(1)}+ </p>+ </div>+ </div>+ <div className="p-3 rounded" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <p className="text-xs font-mono mb-2" style={{ color: BLOOMBERG.CYAN }}>POSTERIOR</p>+ <div className="space-y-1">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ Effective Scenarios: {entropyResult.effective_scenarios_posterior?.toFixed(1)}+ </p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ Max Prob: {(entropyResult.max_probability * 100).toFixed(2)}%+ </p>+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.WHITE }}>+ Min Prob: {(entropyResult.min_probability * 100).toFixed(4)}%+ </p>+ </div>+ </div>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ );+}++// Metric Row Component+function MetricRow({+ label,+ value,+ positive,+ negative+}: {+ label: string;+ value: string;+ positive?: boolean;+ negative?: boolean;+}) {+ let valueColor = BLOOMBERG.WHITE;+ if (positive) valueColor = BLOOMBERG.GREEN;+ if (negative) valueColor = BLOOMBERG.RED;++ return (+ <div className="flex items-center justify-between py-1.5 border-b" style={{ borderColor: BLOOMBERG.BORDER }}>+ <span className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>{label}</span>+ <span className="text-sm font-mono font-semibold" style={{ color: valueColor }}>{value}</span>+ </div>+ );+}++// Greek Row Component for displaying option Greeks+function GreekRow({+ label,+ value,+ description+}: {+ label: string;+ value: number | undefined;+ description: string;+}) {+ const formatGreek = (val: number | undefined) => {+ if (val === undefined || val === null || isNaN(val)) return 'N/A';+ return val.toFixed(4);+ };++ const getValueColor = (val: number | undefined) => {+ if (val === undefined || val === null || isNaN(val)) return BLOOMBERG.GRAY;+ if (val > 0) return BLOOMBERG.GREEN;+ if (val < 0) return BLOOMBERG.RED;+ return BLOOMBERG.WHITE;+ };++ return (+ <div className="flex items-center justify-between py-1.5 border-b" style={{ borderColor: BLOOMBERG.BORDER }}>+ <div>+ <span className="text-xs font-mono font-semibold" style={{ color: BLOOMBERG.WHITE }}>{label}</span>+ <span className="text-xs font-mono ml-2" style={{ color: BLOOMBERG.MUTED }}>{description}</span>+ </div>+ <span className="text-sm font-mono font-bold" style={{ color: getValueColor(value) }}>+ {formatGreek(value)}+ </span>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsxindex 38a3ebb05..c9e37ae90 100644--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx@@ -2,9 +2,10 @@* Functime Analytics Panel - Time Series Forecasting* Bloomberg Professional Design* Integrated with functime library via PyO3+ * Enhanced with portfolio integration and yfinance data fetching*/-import React, { useState, useEffect, useMemo } from 'react';+import React, { useState, useEffect, useMemo, useCallback } from 'react';import {TrendingUp,TrendingDown,@@ -24,15 +25,35 @@ import {Clock,Layers,GitBranch,- Database+ Database,+ Briefcase,+ Search,+ AlertTriangle,+ Waves,+ BarChart3,+ History,+ Shuffle,+ Shield} from 'lucide-react';import {functimeService,type ForecastResult,type ForecastConfig,type PreprocessConfig,- type FullPipelineResponse+ type FullPipelineResponse,+ type AnomalyDetectionConfig,+ type SeasonalityConfig,+ type ConfidenceIntervalsConfig,+ type BacktestConfig} from '@/services/aiQuantLab/functimeService';+import {+ portfolioFunctimeService,+ type PortfolioPriceData,+ type PortfolioForecastResult,+ type PortfolioAnomalyResult,+ type PortfolioSeasonalityResult+} from '@/services/aiQuantLab/portfolioFunctimeService';+import { portfolioService, type Portfolio } from '@/services/portfolioService';// Bloomberg Professional Color Paletteconst BLOOMBERG = {@@ -96,6 +117,12 @@ interface ForecastAnalysisResult {};}+// Data source types+type DataSourceType = 'manual' | 'portfolio' | 'symbol';++// Analysis mode types+type AnalysisMode = 'forecast' | 'anomaly' | 'seasonality' | 'backtest';+export function FunctimePanel() {const [isFunctimeAvailable, setIsFunctimeAvailable] = useState<boolean | null>(null);const [isLoading, setIsLoading] = useState(false);@@ -103,6 +130,18 @@ export function FunctimePanel() {const [analysisResult, setAnalysisResult] = useState<ForecastAnalysisResult | null>(null);const [dataInput, setDataInput] = useState(JSON.stringify(SAMPLE_DATA, null, 2));+ // Data source configuration+ const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');+ const [symbolInput, setSymbolInput] = useState('AAPL');+ const [historicalDays, setHistoricalDays] = useState(365);+ const [priceDataLoading, setPriceDataLoading] = useState(false);+ const [priceData, setPriceData] = useState<PortfolioPriceData | null>(null);++ // Analysis mode+ const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('forecast');+// Forecast configurationconst [selectedModel, setSelectedModel] = useState('linear');const [horizon, setHorizon] = useState(7);@@ -116,17 +155,51 @@ export function FunctimePanel() {forecast: true,metrics: true,summary: true,- chart: true+ chart: true,+ dataSource: true,+ anomaly: true,+ seasonality: true,+ backtest: true});+ // Anomaly detection state+ const [anomalyMethod, setAnomalyMethod] = useState<'zscore' | 'iqr' | 'isolation_forest'>('zscore');+ const [anomalyThreshold, setAnomalyThreshold] = useState(3.0);+ const [anomalyResult, setAnomalyResult] = useState<PortfolioAnomalyResult | null>(null);++ // Seasonality state+ const [seasonalityResult, setSeasonalityResult] = useState<PortfolioSeasonalityResult | null>(null);++ // Expandable table state+ const [forecastTableExpanded, setForecastTableExpanded] = useState(false);+ const INITIAL_ROWS = 10;+ const EXPANDED_ROWS = 50;++ // Advanced models+ const advancedModels = functimeService.getAdvancedModels();+ const anomalyMethods = functimeService.getAnomalyMethods();+const models = functimeService.getAvailableModels();const frequencies = functimeService.getAvailableFrequencies();// Check functime availability on mountuseEffect(() => {checkFunctimeStatus();+ loadPortfolios();}, []);+ const loadPortfolios = async () => {+ try {+ const portfolioList = await portfolioFunctimeService.getAvailablePortfolios();+ setPortfolios(portfolioList);+ if (portfolioList.length > 0 && !selectedPortfolioId) {+ setSelectedPortfolioId(portfolioList[0].id);+ }+ } catch (err) {+ console.error('Failed to load portfolios:', err);+ }+ };+const checkFunctimeStatus = async () => {try {const status = await functimeService.checkStatus();@@ -140,6 +213,149 @@ export function FunctimePanel() {}};+ // Load data based on source type+ const loadDataFromSource = useCallback(async () => {+ if (dataSourceType === 'manual') {+ return; // Data already in dataInput+ }++ setPriceDataLoading(true);+ setError(null);++ try {+ if (dataSourceType === 'portfolio' && selectedPortfolioId) {+ const summary = await portfolioFunctimeService.getPortfolioSummary(selectedPortfolioId);+ if (!summary || summary.holdings.length === 0) {+ setError('Portfolio has no holdings');+ return;+ }++ const data = await portfolioFunctimeService.fetchHistoricalPrices(+ summary.holdings,+ historicalDays+ );++ if (data) {+ setPriceData(data);+ setDataInput(JSON.stringify(data.panelData, null, 2));+ } else {+ setError('Failed to fetch historical data for portfolio');+ }+ } else if (dataSourceType === 'symbol' && symbolInput) {+ const data = await portfolioFunctimeService.fetchSymbolData(symbolInput, historicalDays);+ if (data) {+ setDataInput(JSON.stringify(data, null, 2));+ setPriceData({+ panelData: data,+ assets: [symbolInput],+ nDataPoints: data.length,+ startDate: data[0]?.time || '',+ endDate: data[data.length - 1]?.time || ''+ });+ } else {+ setError(`Failed to fetch data for ${symbolInput}`);+ }+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to load data');+ } finally {+ setPriceDataLoading(false);+ }+ }, [dataSourceType, selectedPortfolioId, symbolInput, historicalDays]);++ // Run analysis based on mode+ const runAnalysis = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const data = JSON.parse(dataInput);++ if (analysisMode === 'forecast') {+ await runForecast();+ } else if (analysisMode === 'anomaly') {+ await runAnomalyDetection(data);+ } else if (analysisMode === 'seasonality') {+ await runSeasonalityAnalysis(data);+ } else if (analysisMode === 'backtest') {+ // For backtest, we use the forecast function with more settings+ await runForecast();+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Analysis failed');+ } finally {+ setIsLoading(false);+ }+ };++ // Anomaly detection+ const runAnomalyDetection = async (data: any[]) => {+ const config: AnomalyDetectionConfig = {+ method: anomalyMethod,+ threshold: anomalyThreshold+ };++ const result = await functimeService.detectAnomalies(data, config);++ if (!result.success) {+ setError(result.error || 'Anomaly detection failed');+ return;+ }++ // Format result for portfolio view+ const anomalies: Record<string, any> = {};+ if (result.results) {+ Object.entries(result.results).forEach(([symbol, data]) => {+ const anomalyList = data.anomalies?.filter((a: any) => a.is_anomaly) || [];+ anomalies[symbol] = {+ count: data.n_anomalies,+ rate: data.anomaly_rate,+ dates: anomalyList.map((a: any) => a.time),+ values: anomalyList.map((a: any) => a.value)+ };+ });+ }++ setAnomalyResult({+ success: true,+ portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,+ anomalies+ });+ };++ // Seasonality analysis+ const runSeasonalityAnalysis = async (data: any[]) => {+ const config: SeasonalityConfig = {+ operation: 'metrics'+ };++ const result = await functimeService.analyzeSeasonality(data, config);++ if (!result.success) {+ setError(result.error || 'Seasonality analysis failed');+ return;+ }++ // Format result+ const seasonality: Record<string, any> = {};+ if (result.metrics) {+ Object.entries(result.metrics).forEach(([symbol, metrics]) => {+ seasonality[symbol] = {+ period: metrics.detected_period || 0,+ strength: metrics.seasonal_strength,+ is_seasonal: metrics.is_seasonal,+ trend_strength: metrics.trend_strength+ };+ });+ }++ setSeasonalityResult({+ success: true,+ portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,+ seasonality+ });+ };+const runForecast = async () => {setIsLoading(true);setError(null);@@ -263,25 +479,244 @@ export function FunctimePanel() {{/* Scrollable Content */}<div className="flex-1 overflow-auto p-4 space-y-4">- {/* Data Input */}- <div>- <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>- PANEL DATA (JSON)- </label>- <textarea- value={dataInput}- onChange={(e) => setDataInput(e.target.value)}- className="w-full h-32 p-3 rounded text-xs font-mono resize-none"+ {/* Data Source Selection */}+ <div+ className="rounded overflow-hidden"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <button+ onClick={() => toggleSection('dataSource')}+ className="w-full px-3 py-2 flex items-center justify-between"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <div className="flex items-center gap-2">+ <Database size={14} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Data Source+ </span>+ </div>+ {expandedSections.dataSource ? (+ <ChevronUp size={14} color={BLOOMBERG.GRAY} />+ ) : (+ <ChevronDown size={14} color={BLOOMBERG.GRAY} />+ )}+ </button>++ {expandedSections.dataSource && (+ <div className="p-3 space-y-3">+ {/* Source Type Selection */}+ <div className="flex gap-2">+ <button+ onClick={() => setDataSourceType('manual')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'manual' ? 'border-2' : ''}`}+ style={{+ backgroundColor: dataSourceType === 'manual' ? BLOOMBERG.HEADER_BG : BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.ORANGE,+ color: dataSourceType === 'manual' ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY+ }}+ >+ Manual+ </button>+ <button+ onClick={() => setDataSourceType('portfolio')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'portfolio' ? 'border-2' : ''}`}+ style={{+ backgroundColor: dataSourceType === 'portfolio' ? BLOOMBERG.HEADER_BG : BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.ORANGE,+ color: dataSourceType === 'portfolio' ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY+ }}+ >+ <Briefcase size={12} className="inline mr-1" />+ Portfolio+ </button>+ <button+ onClick={() => setDataSourceType('symbol')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'symbol' ? 'border-2' : ''}`}+ style={{+ backgroundColor: dataSourceType === 'symbol' ? BLOOMBERG.HEADER_BG : BLOOMBERG.DARK_BG,+ borderColor: BLOOMBERG.ORANGE,+ color: dataSourceType === 'symbol' ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY+ }}+ >+ <Search size={12} className="inline mr-1" />+ Symbol+ </button>+ </div>++ {/* Portfolio Selection */}+ {dataSourceType === 'portfolio' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ SELECT PORTFOLIO+ </label>+ <select+ value={selectedPortfolioId}+ onChange={(e) => setSelectedPortfolioId(e.target.value)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ {portfolios.length === 0 ? (+ <option value="">No portfolios found</option>+ ) : (+ portfolios.map((p) => (+ <option key={p.id} value={p.id}>+ {p.name}+ </option>+ ))+ )}+ </select>+ </div>+ )}++ {/* Symbol Input */}+ {dataSourceType === 'symbol' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ TICKER SYMBOL+ </label>+ <input+ type="text"+ value={symbolInput}+ onChange={(e) => setSymbolInput(e.target.value.toUpperCase())}+ placeholder="AAPL"+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ )}++ {/* Historical Days */}+ {dataSourceType !== 'manual' && (+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ HISTORICAL DAYS+ </label>+ <input+ type="number"+ min={30}+ max={1825}+ value={historicalDays}+ onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ )}++ {/* Load Data Button */}+ {dataSourceType !== 'manual' && (+ <button+ onClick={loadDataFromSource}+ disabled={priceDataLoading}+ className="w-full py-2 rounded font-bold text-xs uppercase flex items-center justify-center gap-2"+ style={{ backgroundColor: BLOOMBERG.CYAN, color: BLOOMBERG.DARK_BG }}+ >+ {priceDataLoading ? (+ <>+ <RefreshCw size={12} className="animate-spin" />+ Loading...+ </>+ ) : (+ <>+ <Database size={12} />+ Fetch Data+ </>+ )}+ </button>+ )}++ {/* Data Info */}+ {priceData && dataSourceType !== 'manual' && (+ <div className="p-2 rounded text-xs font-mono" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>+ <div className="flex justify-between" style={{ color: BLOOMBERG.GRAY }}>+ <span>Assets:</span>+ <span style={{ color: BLOOMBERG.CYAN }}>{priceData.assets.length}</span>+ </div>+ <div className="flex justify-between" style={{ color: BLOOMBERG.GRAY }}>+ <span>Data Points:</span>+ <span style={{ color: BLOOMBERG.WHITE }}>{priceData.nDataPoints}</span>+ </div>+ <div className="flex justify-between" style={{ color: BLOOMBERG.GRAY }}>+ <span>Range:</span>+ <span style={{ color: BLOOMBERG.WHITE }}>{priceData.startDate} to {priceData.endDate}</span>+ </div>+ </div>+ )}+ </div>+ )}+ </div>++ {/* Analysis Mode Tabs */}+ <div className="flex gap-1 p-1 rounded" style={{ backgroundColor: BLOOMBERG.HEADER_BG }}>+ <button+ onClick={() => setAnalysisMode('forecast')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}style={{- backgroundColor: BLOOMBERG.DARK_BG,- color: BLOOMBERG.WHITE,- border: `1px solid ${BLOOMBERG.BORDER}`+ backgroundColor: analysisMode === 'forecast' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'forecast' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY}}- placeholder='[{"entity_id": "A", "time": "2024-01-01", "value": 100}, ...]'- />+ >+ <TrendingUp size={12} />+ Forecast+ </button>+ <button+ onClick={() => setAnalysisMode('anomaly')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}+ style={{+ backgroundColor: analysisMode === 'anomaly' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'anomaly' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ <AlertTriangle size={12} />+ Anomaly+ </button>+ <button+ onClick={() => setAnalysisMode('seasonality')}+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}+ style={{+ backgroundColor: analysisMode === 'seasonality' ? BLOOMBERG.ORANGE : 'transparent',+ color: analysisMode === 'seasonality' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY+ }}+ >+ <Waves size={12} />+ Season+ </button></div>- {/* Model Configuration */}+ {/* Data Input - Only for Manual */}+ {dataSourceType === 'manual' && (+ <div>+ <label className="block text-xs font-mono mb-2" style={{ color: BLOOMBERG.GRAY }}>+ PANEL DATA (JSON)+ </label>+ <textarea+ value={dataInput}+ onChange={(e) => setDataInput(e.target.value)}+ className="w-full h-32 p-3 rounded text-xs font-mono resize-none"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ placeholder='[{"entity_id": "A", "time": "2024-01-01", "value": 100}, ...]'+ />+ </div>+ )}++ {/* Model Configuration - Shown for forecast mode */}+ {analysisMode === 'forecast' && (<divclassName="rounded overflow-hidden"style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}@@ -436,12 +871,95 @@ export function FunctimePanel() {</div>)}</div>+ )}++ {/* Anomaly Detection Configuration */}+ {analysisMode === 'anomaly' && (+ <div+ className="rounded overflow-hidden"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <div+ className="px-3 py-2 flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <AlertTriangle size={14} color={BLOOMBERG.YELLOW} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Anomaly Detection Settings+ </span>+ </div>+ <div className="p-3 space-y-3">+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ DETECTION METHOD+ </label>+ <select+ value={anomalyMethod}+ onChange={(e) => setAnomalyMethod(e.target.value as 'zscore' | 'iqr' | 'isolation_forest')}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ >+ <option value="zscore">Z-Score</option>+ <option value="iqr">IQR (Interquartile Range)</option>+ <option value="isolation_forest">Isolation Forest</option>+ </select>+ </div>+ <div>+ <label className="block text-xs font-mono mb-1" style={{ color: BLOOMBERG.GRAY }}>+ THRESHOLD+ </label>+ <input+ type="number"+ step="0.5"+ min={1}+ max={5}+ value={anomalyThreshold}+ onChange={(e) => setAnomalyThreshold(parseFloat(e.target.value) || 3.0)}+ className="w-full p-2 rounded text-xs font-mono"+ style={{+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}+ />+ </div>+ </div>+ </div>+ )}++ {/* Seasonality Analysis Configuration */}+ {analysisMode === 'seasonality' && (+ <div+ className="rounded overflow-hidden"+ style={{ border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <div+ className="px-3 py-2 flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <Waves size={14} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase" style={{ color: BLOOMBERG.WHITE }}>+ Seasonality Analysis+ </span>+ </div>+ <div className="p-3">+ <p className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Analyzes time series for seasonal patterns, trend strength, and periodicity.+ Uses FFT and ACF for automatic period detection.+ </p>+ </div>+ </div>+ )}</div>{/* Run Button */}<div className="p-4 border-t" style={{ borderColor: BLOOMBERG.BORDER }}><button- onClick={runForecast}+ onClick={runAnalysis}disabled={isLoading}className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"style={{ backgroundColor: BLOOMBERG.ORANGE, color: BLOOMBERG.DARK_BG }}@@ -449,12 +967,14 @@ export function FunctimePanel() {{isLoading ? (<><RefreshCw size={16} className="animate-spin" />- FORECASTING...+ {analysisMode === 'forecast' ? 'FORECASTING...' :+ analysisMode === 'anomaly' ? 'DETECTING...' : 'ANALYZING...'}</>) : (<><Play size={16} />- RUN FORECAST+ {analysisMode === 'forecast' ? 'RUN FORECAST' :+ analysisMode === 'anomaly' ? 'DETECT ANOMALIES' : 'ANALYZE SEASONALITY'}</>)}</button>@@ -473,17 +993,137 @@ export function FunctimePanel() {</div>)}- {!analysisResult && !error && (+ {!analysisResult && !anomalyResult && !seasonalityResult && !error && (<div className="flex items-center justify-center h-full"><div className="text-center"><LineChart size={64} color={BLOOMBERG.MUTED} className="mx-auto mb-4" /><p className="text-sm font-mono" style={{ color: BLOOMBERG.GRAY }}>- Configure model and click "Run Forecast" to see predictions+ {analysisMode === 'forecast'+ ? 'Configure model and click "Run Forecast" to see predictions'+ : analysisMode === 'anomaly'+ ? 'Click "Detect Anomalies" to find outliers in your data'+ : 'Click "Analyze Seasonality" to discover patterns'}</p></div></div>)}+ {/* Anomaly Detection Results */}+ {anomalyResult && anomalyResult.success && anomalyResult.anomalies && (+ <div className="space-y-4">+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <div+ className="px-4 py-3 flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <AlertTriangle size={16} color={BLOOMBERG.YELLOW} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Anomaly Detection Results+ </span>+ </div>+ <div className="p-4">+ <div className="grid grid-cols-2 gap-4">+ {Object.entries(anomalyResult.anomalies).map(([symbol, data]) => (+ <div+ key={symbol}+ className="p-3 rounded"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex justify-between items-center mb-2">+ <span className="text-sm font-bold" style={{ color: BLOOMBERG.CYAN }}>+ {symbol}+ </span>+ <span+ className="text-xs px-2 py-0.5 rounded"+ style={{+ backgroundColor: data.count > 0 ? BLOOMBERG.RED : BLOOMBERG.GREEN,+ color: BLOOMBERG.WHITE+ }}+ >+ {data.count} anomalies+ </span>+ </div>+ <div className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ <div>Rate: {(data.rate * 100).toFixed(2)}%</div>+ {data.dates?.length > 0 && (+ <div className="mt-1">+ Latest: {data.dates[data.dates.length - 1]}+ </div>+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Seasonality Results */}+ {seasonalityResult && seasonalityResult.success && seasonalityResult.seasonality && (+ <div className="space-y-4">+ <div+ className="rounded overflow-hidden"+ style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ <div+ className="px-4 py-3 flex items-center gap-2"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG }}+ >+ <Waves size={16} color={BLOOMBERG.CYAN} />+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: BLOOMBERG.WHITE }}>+ Seasonality Analysis Results+ </span>+ </div>+ <div className="p-4">+ <div className="grid grid-cols-2 gap-4">+ {Object.entries(seasonalityResult.seasonality).map(([symbol, data]) => (+ <div+ key={symbol}+ className="p-3 rounded"+ style={{ backgroundColor: BLOOMBERG.DARK_BG }}+ >+ <div className="flex justify-between items-center mb-2">+ <span className="text-sm font-bold" style={{ color: BLOOMBERG.CYAN }}>+ {symbol}+ </span>+ <span+ className="text-xs px-2 py-0.5 rounded"+ style={{+ backgroundColor: data.is_seasonal ? BLOOMBERG.GREEN : BLOOMBERG.MUTED,+ color: BLOOMBERG.WHITE+ }}+ >+ {data.is_seasonal ? 'Seasonal' : 'Non-Seasonal'}+ </span>+ </div>+ <div className="text-xs font-mono space-y-1" style={{ color: BLOOMBERG.GRAY }}>+ <div className="flex justify-between">+ <span>Period:</span>+ <span style={{ color: BLOOMBERG.WHITE }}>{data.period} days</span>+ </div>+ <div className="flex justify-between">+ <span>Seasonal Strength:</span>+ <span style={{ color: BLOOMBERG.ORANGE }}>{(data.strength * 100).toFixed(1)}%</span>+ </div>+ {data.trend_strength !== undefined && (+ <div className="flex justify-between">+ <span>Trend Strength:</span>+ <span style={{ color: BLOOMBERG.GREEN }}>{(data.trend_strength * 100).toFixed(1)}%</span>+ </div>+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ )}+{analysisResult && (<div className="space-y-4">{/* Data Summary Section */}@@ -682,7 +1322,7 @@ export function FunctimePanel() {</tr></thead><tbody>- {analysisResult.forecast.slice(0, 20).map((row, idx) => (+ {analysisResult.forecast.slice(0, forecastTableExpanded ? EXPANDED_ROWS : INITIAL_ROWS).map((row, idx) => (<trkey={idx}style={{@@ -702,13 +1342,24 @@ export function FunctimePanel() {))}</tbody></table>- {analysisResult.forecast.length > 20 && (- <div- className="px-3 py-2 text-xs font-mono text-center"- style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.GRAY }}+ {analysisResult.forecast.length > INITIAL_ROWS && (+ <button+ onClick={() => setForecastTableExpanded(!forecastTableExpanded)}+ className="w-full px-3 py-2 text-xs font-mono text-center flex items-center justify-center gap-2 hover:opacity-80 transition-opacity"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.ORANGE }}>- + {analysisResult.forecast.length - 20} more rows- </div>+ {forecastTableExpanded ? (+ <>+ <ChevronUp size={12} />+ Show Less ({INITIAL_ROWS} rows)+ </>+ ) : (+ <>+ <ChevronDown size={12} />+ Show More ({Math.min(analysisResult.forecast.length, EXPANDED_ROWS)} of {analysisResult.forecast.length} rows)+ </>+ )}+ </button>)}</div></div>@@ -781,11 +1432,19 @@ function MetricCard({);}-// Forecast Chart Component - SVG-based line chart+// Forecast Chart Component - Interactive SVG-based line chart with tooltipsinterface ChartDataPoint {time: string;value: number;type: 'historical' | 'forecast';+ entity_id?: string;+}++interface TooltipState {+ visible: boolean;+ x: number;+ y: number;+ data: ChartDataPoint | null;}function ForecastChart({@@ -797,6 +1456,11 @@ function ForecastChart({forecastData: ForecastResult[];height?: number;}) {+ const [tooltip, setTooltip] = useState<TooltipState>({ visible: false, x: 0, y: 0, data: null });+ const [zoomLevel, setZoomLevel] = useState(1);+ const [panOffset, setPanOffset] = useState(0);+ const svgRef = React.useRef<SVGSVGElement>(null);+const chartData = useMemo(() => {const historical: ChartDataPoint[] = historicalData.map(d => ({time: d.time,@@ -807,7 +1471,8 @@ function ForecastChart({const forecast: ChartDataPoint[] = forecastData.map(d => ({time: d.time,value: d.value,- type: 'forecast' as const+ type: 'forecast' as const,+ entity_id: d.entity_id}));return [...historical, ...forecast];@@ -826,7 +1491,8 @@ function ForecastChart({);}- const width = 800;+ const baseWidth = 800;+ const width = baseWidth * zoomLevel;const padding = { top: 20, right: 60, bottom: 40, left: 60 };const chartWidth = width - padding.left - padding.right;const chartHeight = height - padding.top - padding.bottom;@@ -883,152 +1549,266 @@ function ForecastChart({arr.findIndex(t => t.index === item.index) === index && item.label);- return (- <div className="w-full overflow-x-auto">- <svg- width="100%"- height={height}- viewBox={`0 0 ${width} ${height}`}- preserveAspectRatio="xMidYMid meet"- style={{ backgroundColor: BLOOMBERG.DARK_BG }}- >- {/* Grid lines */}- {yTicks.map((tick, i) => (- <line- key={i}- x1={padding.left}- y1={tick.y}- x2={width - padding.right}- y2={tick.y}- stroke={BLOOMBERG.BORDER}- strokeWidth={1}- strokeDasharray="4,4"- />- ))}-- {/* Forecast region background */}- {forecastData.length > 0 && (- <rect- x={xScale(historicalEndIndex)}- y={padding.top}- width={chartWidth - xScale(historicalEndIndex) + padding.left}- height={chartHeight}- fill={BLOOMBERG.ORANGE}- opacity={0.05}- />- )}+ // Handle mouse events for interactive tooltips+ const handleMouseEnter = (data: ChartDataPoint, x: number, y: number) => {+ setTooltip({ visible: true, x, y, data });+ };- {/* Vertical line at forecast start */}- {forecastData.length > 0 && historicalData.length > 0 && (- <line- x1={xScale(historicalEndIndex)}- y1={padding.top}- x2={xScale(historicalEndIndex)}- y2={height - padding.bottom}- stroke={BLOOMBERG.ORANGE}- strokeWidth={1}- strokeDasharray="6,4"- opacity={0.6}- />- )}+ const handleMouseLeave = () => {+ setTooltip({ visible: false, x: 0, y: 0, data: null });+ };- {/* Historical line */}- {historicalPath && (- <path- d={historicalPath}- fill="none"- stroke={BLOOMBERG.CYAN}- strokeWidth={2}- />- )}+ // Zoom controls+ const handleZoomIn = () => setZoomLevel(prev => Math.min(prev + 0.5, 3));+ const handleZoomOut = () => setZoomLevel(prev => Math.max(prev - 0.5, 1));+ const handleResetZoom = () => { setZoomLevel(1); setPanOffset(0); };- {/* Forecast line */}- {forecastPath && (- <path- d={forecastPath}- fill="none"- stroke={BLOOMBERG.ORANGE}- strokeWidth={2}- strokeDasharray="6,3"- />+ return (+ <div className="w-full">+ {/* Zoom Controls */}+ <div className="flex justify-end gap-2 mb-2">+ <button+ onClick={handleZoomOut}+ className="px-2 py-1 rounded text-xs font-mono"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.WHITE, border: `1px solid ${BLOOMBERG.BORDER}` }}+ disabled={zoomLevel <= 1}+ >+ −+ </button>+ <span className="px-2 py-1 text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ {Math.round(zoomLevel * 100)}%+ </span>+ <button+ onClick={handleZoomIn}+ className="px-2 py-1 rounded text-xs font-mono"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.WHITE, border: `1px solid ${BLOOMBERG.BORDER}` }}+ disabled={zoomLevel >= 3}+ >+ ++ </button>+ {zoomLevel !== 1 && (+ <button+ onClick={handleResetZoom}+ className="px-2 py-1 rounded text-xs font-mono"+ style={{ backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.ORANGE, border: `1px solid ${BLOOMBERG.BORDER}` }}+ >+ Reset+ </button>)}+ </div>- {/* Historical data points */}- {historicalData.map((d, i) => (- <circle- key={`hist-${i}`}- cx={xScale(i)}- cy={yScale(d.value)}- r={3}- fill={BLOOMBERG.CYAN}- />- ))}-- {/* Forecast data points */}- {forecastData.map((d, i) => (- <circle- key={`forecast-${i}`}- cx={xScale(historicalData.length + i)}- cy={yScale(d.value)}- r={4}- fill={BLOOMBERG.ORANGE}- stroke={BLOOMBERG.DARK_BG}- strokeWidth={1}- />- ))}-- {/* Y-axis labels */}- {yTicks.map((tick, i) => (- <text- key={i}- x={padding.left - 10}- y={tick.y + 4}- textAnchor="end"- fontSize={10}- fontFamily="monospace"- fill={BLOOMBERG.GRAY}- >- {tick.value.toFixed(2)}- </text>- ))}-- {/* X-axis labels */}- {xLabels.map((item, i) => (- <text- key={i}- x={xScale(item.index)}- y={height - padding.bottom + 20}- textAnchor="middle"- fontSize={10}- fontFamily="monospace"- fill={BLOOMBERG.GRAY}- >- {item.label}- </text>- ))}-- {/* Legend */}- <g transform={`translate(${width - padding.right - 120}, ${padding.top})`}>- <rect x={0} y={0} width={120} height={50} fill={BLOOMBERG.PANEL_BG} rx={4} />- <line x1={10} y1={15} x2={35} y2={15} stroke={BLOOMBERG.CYAN} strokeWidth={2} />- <text x={42} y={18} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Historical</text>- <line x1={10} y1={35} x2={35} y2={35} stroke={BLOOMBERG.ORANGE} strokeWidth={2} strokeDasharray="6,3" />- <text x={42} y={38} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Forecast</text>- </g>-- {/* Forecast label */}- {forecastData.length > 0 && historicalData.length > 0 && (- <text- x={xScale(historicalEndIndex) + 5}- y={padding.top + 15}- fontSize={10}- fontFamily="monospace"- fill={BLOOMBERG.ORANGE}+ {/* Chart Container with horizontal scroll */}+ <div className="overflow-x-auto" style={{ position: 'relative' }}>+ <svg+ ref={svgRef}+ width={width}+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ style={{ backgroundColor: BLOOMBERG.DARK_BG, minWidth: baseWidth }}+ >+ {/* Grid lines */}+ {yTicks.map((tick, i) => (+ <line+ key={i}+ x1={padding.left}+ y1={tick.y}+ x2={width - padding.right}+ y2={tick.y}+ stroke={BLOOMBERG.BORDER}+ strokeWidth={1}+ strokeDasharray="4,4"+ />+ ))}++ {/* Forecast region background */}+ {forecastData.length > 0 && (+ <rect+ x={xScale(historicalEndIndex)}+ y={padding.top}+ width={chartWidth - xScale(historicalEndIndex) + padding.left}+ height={chartHeight}+ fill={BLOOMBERG.ORANGE}+ opacity={0.05}+ />+ )}++ {/* Vertical line at forecast start */}+ {forecastData.length > 0 && historicalData.length > 0 && (+ <line+ x1={xScale(historicalEndIndex)}+ y1={padding.top}+ x2={xScale(historicalEndIndex)}+ y2={height - padding.bottom}+ stroke={BLOOMBERG.ORANGE}+ strokeWidth={1}+ strokeDasharray="6,4"+ opacity={0.6}+ />+ )}++ {/* Historical line */}+ {historicalPath && (+ <path+ d={historicalPath}+ fill="none"+ stroke={BLOOMBERG.CYAN}+ strokeWidth={2}+ />+ )}++ {/* Forecast line */}+ {forecastPath && (+ <path+ d={forecastPath}+ fill="none"+ stroke={BLOOMBERG.ORANGE}+ strokeWidth={2}+ strokeDasharray="6,3"+ />+ )}++ {/* Historical data points - Interactive */}+ {historicalData.map((d, i) => {+ const cx = xScale(i);+ const cy = yScale(d.value);+ const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'historical' };+ return (+ <g key={`hist-${i}`}>+ {/* Larger invisible hit area */}+ <circle+ cx={cx}+ cy={cy}+ r={12}+ fill="transparent"+ style={{ cursor: 'pointer' }}+ onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}+ onMouseLeave={handleMouseLeave}+ />+ {/* Visible point */}+ <circle+ cx={cx}+ cy={cy}+ r={tooltip.data?.time === d.time && tooltip.data?.type === 'historical' ? 6 : 3}+ fill={BLOOMBERG.CYAN}+ style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}+ />+ </g>+ );+ })}++ {/* Forecast data points - Interactive */}+ {forecastData.map((d, i) => {+ const cx = xScale(historicalData.length + i);+ const cy = yScale(d.value);+ const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'forecast', entity_id: d.entity_id };+ return (+ <g key={`forecast-${i}`}>+ {/* Larger invisible hit area */}+ <circle+ cx={cx}+ cy={cy}+ r={12}+ fill="transparent"+ style={{ cursor: 'pointer' }}+ onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}+ onMouseLeave={handleMouseLeave}+ />+ {/* Visible point */}+ <circle+ cx={cx}+ cy={cy}+ r={tooltip.data?.time === d.time && tooltip.data?.type === 'forecast' ? 7 : 4}+ fill={BLOOMBERG.ORANGE}+ stroke={BLOOMBERG.DARK_BG}+ strokeWidth={1}+ style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}+ />+ </g>+ );+ })}++ {/* Y-axis labels */}+ {yTicks.map((tick, i) => (+ <text+ key={i}+ x={padding.left - 10}+ y={tick.y + 4}+ textAnchor="end"+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.GRAY}+ >+ {tick.value.toFixed(2)}+ </text>+ ))}++ {/* X-axis labels */}+ {xLabels.map((item, i) => (+ <text+ key={i}+ x={xScale(item.index)}+ y={height - padding.bottom + 20}+ textAnchor="middle"+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.GRAY}+ >+ {item.label}+ </text>+ ))}++ {/* Legend */}+ <g transform={`translate(${width - padding.right - 120}, ${padding.top})`}>+ <rect x={0} y={0} width={120} height={50} fill={BLOOMBERG.PANEL_BG} rx={4} />+ <line x1={10} y1={15} x2={35} y2={15} stroke={BLOOMBERG.CYAN} strokeWidth={2} />+ <text x={42} y={18} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Historical</text>+ <line x1={10} y1={35} x2={35} y2={35} stroke={BLOOMBERG.ORANGE} strokeWidth={2} strokeDasharray="6,3" />+ <text x={42} y={38} fontSize={10} fontFamily="monospace" fill={BLOOMBERG.WHITE}>Forecast</text>+ </g>++ {/* Forecast label */}+ {forecastData.length > 0 && historicalData.length > 0 && (+ <text+ x={xScale(historicalEndIndex) + 5}+ y={padding.top + 15}+ fontSize={10}+ fontFamily="monospace"+ fill={BLOOMBERG.ORANGE}+ >+ ▼ Forecast+ </text>+ )}+ </svg>++ {/* Tooltip */}+ {tooltip.visible && tooltip.data && (+ <div+ className="absolute pointer-events-none px-3 py-2 rounded shadow-lg z-50"+ style={{+ left: Math.min(tooltip.x + 10, width - 180),+ top: Math.max(tooltip.y - 60, 10),+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${tooltip.data.type === 'forecast' ? BLOOMBERG.ORANGE : BLOOMBERG.CYAN}`,+ minWidth: 160+ }}>- ▼ Forecast- </text>+ <div className="text-xs font-mono font-bold mb-1" style={{ color: tooltip.data.type === 'forecast' ? BLOOMBERG.ORANGE : BLOOMBERG.CYAN }}>+ {tooltip.data.type === 'forecast' ? '📈 FORECAST' : '📊 HISTORICAL'}+ </div>+ <div className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Date: <span style={{ color: BLOOMBERG.WHITE }}>{tooltip.data.time.split('T')[0]}</span>+ </div>+ <div className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Value: <span style={{ color: BLOOMBERG.GREEN, fontWeight: 'bold' }}>{tooltip.data.value.toFixed(4)}</span>+ </div>+ {tooltip.data.entity_id && (+ <div className="text-xs font-mono" style={{ color: BLOOMBERG.GRAY }}>+ Entity: <span style={{ color: BLOOMBERG.CYAN }}>{tooltip.data.entity_id}</span>+ </div>+ )}+ </div>)}- </svg>+ </div></div>);}diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.tsindex 4f2124abf..fa8b11595 100644--- a/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.ts+++ b/fincept-terminal-desktop/src/services/aiQuantLab/ffnService.ts@@ -109,6 +109,71 @@ export interface AssetComparisonResponse {error?: string;}+export interface PortfolioOptimizationResponse {+ success: boolean;+ method?: string;+ weights?: Record<string, number>;+ portfolio_stats?: {+ total_return: number;+ cagr: number;+ volatility: number;+ sharpe_ratio: number;+ sortino_ratio: number;+ max_drawdown: number;+ calmar_ratio?: number;+ };+ asset_contributions?: Record<string, {+ weight: number;+ volatility: number;+ return: number;+ risk_contribution: number;+ }>;+ correlation_matrix?: Record<string, Record<string, number>>;+ portfolio_prices?: Record<string, number>;+ error?: string;+}++export interface BenchmarkComparisonResponse {+ success: boolean;+ portfolio_name?: string;+ benchmark_name?: string;+ portfolio_stats?: {+ total_return: number;+ cagr: number;+ volatility: number;+ sharpe_ratio: number;+ sortino_ratio: number;+ max_drawdown: number;+ calmar_ratio?: number;+ };+ benchmark_stats?: {+ total_return: number;+ cagr: number;+ volatility: number;+ sharpe_ratio: number;+ sortino_ratio: number;+ max_drawdown: number;+ calmar_ratio?: number;+ };+ relative_metrics?: {+ alpha?: number;+ beta?: number;+ correlation?: number;+ tracking_error?: number;+ information_ratio?: number;+ up_capture?: number;+ down_capture?: number;+ };+ rebased_portfolio?: Record<string, number>;+ rebased_benchmark?: Record<string, number>;+ date_range?: {+ start: string;+ end: string;+ data_points: number;+ };+ error?: string;+}+export interface FullAnalysisResponse {success: boolean;performance?: PerformanceMetrics | Record<string, PerformanceMetrics>;@@ -348,6 +413,66 @@ class FFNService {}}+ /**+ * Portfolio optimization - calculate optimal weights+ * @param prices - Price data with multiple assets+ * @param method - Optimization method: 'erc', 'inv_vol', 'mean_var', 'equal'+ * @param riskFreeRate - Risk-free rate for calculations+ * @param weightBounds - Min/max weight bounds [min, max]+ */+ async portfolioOptimization(+ prices: PriceData,+ method?: 'erc' | 'inv_vol' | 'mean_var' | 'equal',+ riskFreeRate?: number,+ weightBounds?: [number, number]+ ): Promise<PortfolioOptimizationResponse> {+ try {+ const result = await invoke<string>('ffn_portfolio_optimization', {+ pricesJson: JSON.stringify(prices),+ method: method || 'erc',+ riskFreeRate: riskFreeRate || 0,+ weightBounds: weightBounds || [0, 1]+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] portfolioOptimization error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Benchmark comparison - compare portfolio against a benchmark+ * @param prices - Portfolio price data+ * @param benchmarkPrices - Benchmark price data+ * @param benchmarkName - Name of the benchmark (e.g., 'SPY', 'QQQ')+ * @param riskFreeRate - Risk-free rate for calculations+ */+ async benchmarkComparison(+ prices: PriceData,+ benchmarkPrices: PriceData,+ benchmarkName?: string,+ riskFreeRate?: number+ ): Promise<BenchmarkComparisonResponse> {+ try {+ const result = await invoke<string>('ffn_benchmark_comparison', {+ pricesJson: JSON.stringify(prices),+ benchmarkPricesJson: JSON.stringify(benchmarkPrices),+ benchmarkName: benchmarkName || 'Benchmark',+ riskFreeRate: riskFreeRate || 0+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FFNService] benchmarkComparison error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }+// ============================================================================// UTILITY METHODS// ============================================================================diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/fortitudoService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/fortitudoService.tsnew file mode 100644index 000000000..bce83df75--- /dev/null+++ b/fincept-terminal-desktop/src/services/aiQuantLab/fortitudoService.ts@@ -0,0 +1,701 @@+/**+ * Fortitudo.tech Analytics Service - Frontend API for portfolio risk analytics+ * Provides VaR, CVaR, volatility, Sharpe ratio, option pricing, and entropy pooling+ */++import { invoke } from '@tauri-apps/api/core';++// ============================================================================+// TYPE DEFINITIONS+// ============================================================================++export interface FortitudoStatusResponse {+ success: boolean;+ available: boolean;+ wrappers_available: boolean;+ version?: string;+ message?: string;+ error?: string;+}++export interface PortfolioMetrics {+ expected_return: number;+ volatility: number;+ var: number;+ cvar: number;+ sharpe_ratio: number;+ alpha: number;+}++export interface PortfolioMetricsResponse {+ success: boolean;+ metrics?: PortfolioMetrics;+ n_scenarios?: number;+ n_assets?: number;+ error?: string;+}++export interface CovarianceAnalysisResponse {+ success: boolean;+ covariance_matrix?: Record<string, Record<string, number>>;+ correlation_matrix?: Record<string, Record<string, number>>;+ moments?: Record<string, Record<string, number>>;+ assets?: string[];+ error?: string;+}++export interface ExpDecayResponse {+ success: boolean;+ probabilities?: number[];+ half_life?: number;+ n_scenarios?: number;+ sum?: number;+ error?: string;+}++export interface OptionPricingResult {+ call_price: number;+ put_price: number;+ straddle_price: number;+ forward_price: number;+ strike: number;+ volatility: number;+ risk_free_rate: number;+ time_to_maturity: number;+}++export interface ParityCheck {+ call_price: number;+ put_price: number;+ forward_price: number;+ parity_lhs: number;+ parity_rhs: number;+ parity_difference: number;+ parity_holds: boolean;+}++export interface OptionPricingResponse {+ success: boolean;+ forward_price?: number;+ call_price?: number;+ put_price?: number;+ straddle?: OptionPricingResult;+ parity_check?: ParityCheck;+ error?: string;+}++export interface OptionChainItem {+ strike: number;+ call_price: number;+ put_price: number;+ moneyness: number;+}++export interface OptionChainResponse {+ success: boolean;+ spot_price?: number;+ forward_price?: number;+ chain?: OptionChainItem[];+ error?: string;+}++export interface EntropyPoolingResponse {+ success: boolean;+ prior_probabilities?: number[];+ posterior_probabilities?: number[];+ effective_scenarios_prior?: number;+ effective_scenarios_posterior?: number;+ max_probability?: number;+ min_probability?: number;+ error?: string;+}++export interface ExposureStackingResponse {+ success: boolean;+ stacked_weights?: number[];+ mean_sample_weights?: number[];+ std_sample_weights?: number[];+ n_assets?: number;+ n_samples?: number;+ n_partitions?: number;+ weights_sum?: number;+ error?: string;+}++export interface OptionGreeks {+ delta: number;+ gamma: number;+ vega: number;+ theta: number;+ rho: number;+}++export interface OptionGreeksResponse {+ success: boolean;+ call?: OptionGreeks;+ put?: OptionGreeks;+ inputs?: {+ spot_price: number;+ strike: number;+ volatility: number;+ risk_free_rate: number;+ dividend_yield: number;+ time_to_maturity: number;+ };+ error?: string;+}++export interface FullAnalysisResponse {+ success: boolean;+ analysis?: {+ metrics_equal_weight: PortfolioMetrics;+ metrics_exp_decay: PortfolioMetrics;+ covariance_matrix?: Record<string, Record<string, number>>;+ correlation_matrix?: Record<string, Record<string, number>>;+ moments?: Record<string, Record<string, number>>;+ half_life: number;+ alpha: number;+ n_scenarios: number;+ n_assets: number;+ assets?: string[];+ };+ error?: string;+}++// Portfolio Optimization Types+export type OptimizationObjective = 'min_variance' | 'max_sharpe' | 'target_return' | 'min_cvar';++export interface OptimizationResult {+ success: boolean;+ weights?: number[] | Record<string, number>;+ expected_return?: number;+ volatility?: number;+ sharpe_ratio?: number;+ var?: number;+ cvar?: number;+ assets?: string[];+ objective?: string;+ error?: string;+}++export interface EfficientFrontierPoint {+ expected_return: number;+ volatility?: number;+ cvar?: number;+ sharpe_ratio?: number;+ weights: number[] | Record<string, number>;+}++export interface EfficientFrontierResponse {+ success: boolean;+ frontier?: EfficientFrontierPoint[];+ assets?: string[];+ n_points?: number;+ error?: string;+}++// Returns data can be provided in multiple formats+export type ReturnsData =+ | Record<string, number> // {date: return}+ | Record<string, Record<string, number>> // {symbol: {date: return}}+ | Array<{ date: string; returns: number; symbol?: string }>; // Array format++// Weights can be array or object+export type WeightsData = number[] | Record<string, number>;++// ============================================================================+// FORTITUDO SERVICE CLASS+// ============================================================================++class FortitudoService {+ /**+ * Check fortitudo.tech library status and availability+ */+ async checkStatus(): Promise<FortitudoStatusResponse> {+ try {+ const result = await invoke<string>('fortitudo_check_status');+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] checkStatus error:', error);+ return {+ success: false,+ available: false,+ wrappers_available: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate comprehensive portfolio risk metrics+ * @param returns - Historical returns data+ * @param weights - Portfolio weights+ * @param alpha - Confidence level for VaR/CVaR (default: 0.05 = 95%)+ * @param probabilities - Optional scenario probabilities+ */+ async portfolioMetrics(+ returns: ReturnsData,+ weights: WeightsData,+ alpha?: number,+ probabilities?: number[]+ ): Promise<PortfolioMetricsResponse> {+ try {+ const result = await invoke<string>('fortitudo_portfolio_metrics', {+ returnsJson: JSON.stringify(returns),+ weightsJson: JSON.stringify(weights),+ alpha,+ probabilities: probabilities ? JSON.stringify(probabilities) : null+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] portfolioMetrics error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate covariance and correlation matrices with statistical moments+ * @param returns - Historical returns data+ * @param probabilities - Optional scenario probabilities+ */+ async covarianceAnalysis(+ returns: ReturnsData,+ probabilities?: number[]+ ): Promise<CovarianceAnalysisResponse> {+ try {+ const result = await invoke<string>('fortitudo_covariance_analysis', {+ returnsJson: JSON.stringify(returns),+ probabilities: probabilities ? JSON.stringify(probabilities) : null+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] covarianceAnalysis error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate exponentially decaying probabilities for scenario weighting+ * @param returns - Historical returns data+ * @param halfLife - Half-life in days (default: 252 = 1 year)+ */+ async expDecayWeighting(+ returns: ReturnsData,+ halfLife?: number+ ): Promise<ExpDecayResponse> {+ try {+ const result = await invoke<string>('fortitudo_exp_decay_weighting', {+ returnsJson: JSON.stringify(returns),+ halfLife+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] expDecayWeighting error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Price options using Black-Scholes model+ * @param spotPrice - Current spot price+ * @param strike - Strike price+ * @param volatility - Implied volatility (annual, e.g., 0.25 for 25%)+ * @param riskFreeRate - Risk-free rate (annual)+ * @param dividendYield - Dividend yield (annual)+ * @param timeToMaturity - Time to maturity in years+ */+ async optionPricing(+ spotPrice: number,+ strike: number,+ volatility: number,+ riskFreeRate?: number,+ dividendYield?: number,+ timeToMaturity?: number+ ): Promise<OptionPricingResponse> {+ try {+ const result = await invoke<string>('fortitudo_option_pricing', {+ spotPrice,+ strike,+ volatility,+ riskFreeRate,+ dividendYield,+ timeToMaturity+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] optionPricing error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Generate option chain for multiple strikes+ * @param spotPrice - Current spot price+ * @param volatility - Implied volatility+ * @param strikes - Array of strike prices (optional, auto-generated if not provided)+ * @param riskFreeRate - Risk-free rate+ * @param dividendYield - Dividend yield+ * @param timeToMaturity - Time to maturity in years+ */+ async optionChain(+ spotPrice: number,+ volatility: number,+ strikes?: number[],+ riskFreeRate?: number,+ dividendYield?: number,+ timeToMaturity?: number+ ): Promise<OptionChainResponse> {+ try {+ const result = await invoke<string>('fortitudo_option_chain', {+ spotPrice,+ volatility,+ strikes,+ riskFreeRate,+ dividendYield,+ timeToMaturity+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] optionChain error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Apply entropy pooling for scenario probability adjustment+ * @param nScenarios - Number of scenarios+ * @param maxProbability - Maximum probability for any scenario (e.g., 0.05 for 5%)+ */+ async entropyPooling(+ nScenarios: number,+ maxProbability?: number+ ): Promise<EntropyPoolingResponse> {+ try {+ const result = await invoke<string>('fortitudo_entropy_pooling', {+ nScenarios,+ maxProbability+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] entropyPooling error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate exposure stacking portfolio from sample portfolios+ * @param samplePortfolios - Sample portfolio weights matrix (n_assets x n_samples)+ * @param nPartitions - Number of partition sets+ */+ async exposureStacking(+ samplePortfolios: number[][],+ nPartitions?: number+ ): Promise<ExposureStackingResponse> {+ try {+ const result = await invoke<string>('fortitudo_exposure_stacking', {+ samplePortfoliosJson: JSON.stringify(samplePortfolios),+ nPartitions+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] exposureStacking error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Full portfolio risk analysis combining all metrics+ * @param returns - Historical returns data+ * @param weights - Portfolio weights+ * @param alpha - Confidence level for VaR/CVaR+ * @param halfLife - Half-life for exponential decay+ */+ async fullAnalysis(+ returns: ReturnsData,+ weights: WeightsData,+ alpha?: number,+ halfLife?: number+ ): Promise<FullAnalysisResponse> {+ try {+ const result = await invoke<string>('fortitudo_full_analysis', {+ returnsJson: JSON.stringify(returns),+ weightsJson: JSON.stringify(weights),+ alpha,+ halfLife+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] fullAnalysis error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Calculate option Greeks (Delta, Gamma, Vega, Theta, Rho)+ * @param spotPrice - Current spot price+ * @param strike - Strike price+ * @param volatility - Implied volatility (annual, e.g., 0.25 for 25%)+ * @param riskFreeRate - Risk-free rate (annual)+ * @param dividendYield - Dividend yield (annual)+ * @param timeToMaturity - Time to maturity in years+ */+ async optionGreeks(+ spotPrice: number,+ strike: number,+ volatility: number,+ riskFreeRate?: number,+ dividendYield?: number,+ timeToMaturity?: number+ ): Promise<OptionGreeksResponse> {+ try {+ const result = await invoke<string>('fortitudo_option_greeks', {+ spotPrice,+ strike,+ volatility,+ riskFreeRate,+ dividendYield,+ timeToMaturity+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] optionGreeks error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ // ============================================================================+ // PORTFOLIO OPTIMIZATION METHODS+ // ============================================================================++ /**+ * Mean-Variance portfolio optimization+ * @param returns - Historical returns data+ * @param objective - Optimization objective: 'min_variance', 'max_sharpe', 'target_return'+ * @param longOnly - Constraint for long-only portfolios (default: true)+ * @param maxWeight - Maximum weight per asset+ * @param minWeight - Minimum weight per asset+ * @param riskFreeRate - Risk-free rate for Sharpe calculation+ * @param targetReturn - Target return for 'target_return' objective+ */+ async optimizeMeanVariance(+ returns: ReturnsData,+ objective?: OptimizationObjective,+ longOnly?: boolean,+ maxWeight?: number,+ minWeight?: number,+ riskFreeRate?: number,+ targetReturn?: number+ ): Promise<OptimizationResult> {+ try {+ const result = await invoke<string>('fortitudo_optimize_mean_variance', {+ returnsJson: JSON.stringify(returns),+ objective,+ longOnly,+ maxWeight,+ minWeight,+ riskFreeRate,+ targetReturn+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] optimizeMeanVariance error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Mean-CVaR portfolio optimization (Conditional Value-at-Risk)+ * @param returns - Historical returns data+ * @param objective - Optimization objective: 'min_cvar', 'target_return'+ * @param alpha - Confidence level for CVaR (default: 0.05 = 95%)+ * @param longOnly - Constraint for long-only portfolios (default: true)+ * @param maxWeight - Maximum weight per asset+ * @param minWeight - Minimum weight per asset+ * @param riskFreeRate - Risk-free rate+ * @param targetReturn - Target return for 'target_return' objective+ */+ async optimizeMeanCVaR(+ returns: ReturnsData,+ objective?: OptimizationObjective,+ alpha?: number,+ longOnly?: boolean,+ maxWeight?: number,+ minWeight?: number,+ riskFreeRate?: number,+ targetReturn?: number+ ): Promise<OptimizationResult> {+ try {+ const result = await invoke<string>('fortitudo_optimize_mean_cvar', {+ returnsJson: JSON.stringify(returns),+ objective,+ alpha,+ longOnly,+ maxWeight,+ minWeight,+ riskFreeRate,+ targetReturn+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] optimizeMeanCVaR error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Generate Mean-Variance efficient frontier+ * @param returns - Historical returns data+ * @param nPoints - Number of points on the frontier (default: 20)+ * @param longOnly - Constraint for long-only portfolios+ * @param maxWeight - Maximum weight per asset+ * @param riskFreeRate - Risk-free rate+ */+ async efficientFrontierMV(+ returns: ReturnsData,+ nPoints?: number,+ longOnly?: boolean,+ maxWeight?: number,+ riskFreeRate?: number+ ): Promise<EfficientFrontierResponse> {+ try {+ const result = await invoke<string>('fortitudo_efficient_frontier_mv', {+ returnsJson: JSON.stringify(returns),+ nPoints,+ longOnly,+ maxWeight,+ riskFreeRate+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] efficientFrontierMV error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ /**+ * Generate Mean-CVaR efficient frontier+ * @param returns - Historical returns data+ * @param nPoints - Number of points on the frontier (default: 20)+ * @param alpha - Confidence level for CVaR+ * @param longOnly - Constraint for long-only portfolios+ * @param maxWeight - Maximum weight per asset+ */+ async efficientFrontierCVaR(+ returns: ReturnsData,+ nPoints?: number,+ alpha?: number,+ longOnly?: boolean,+ maxWeight?: number+ ): Promise<EfficientFrontierResponse> {+ try {+ const result = await invoke<string>('fortitudo_efficient_frontier_cvar', {+ returnsJson: JSON.stringify(returns),+ nPoints,+ alpha,+ longOnly,+ maxWeight+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FortitudoService] efficientFrontierCVaR error:', error);+ return {+ success: false,+ error: String(error)+ };+ }+ }++ // ============================================================================+ // UTILITY METHODS+ // ============================================================================++ /**+ * Format percentage for display+ */+ formatPercent(value: number | null | undefined, decimals = 2): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `${(value * 100).toFixed(decimals)}%`;+ }++ /**+ * Format ratio for display+ */+ formatRatio(value: number | null | undefined, decimals = 3): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return value.toFixed(decimals);+ }++ /**+ * Format currency for display+ */+ formatCurrency(value: number | null | undefined, decimals = 2): string {+ if (value === null || value === undefined || isNaN(value)) return 'N/A';+ return `$${value.toFixed(decimals)}`;+ }++ /**+ * Generate sample returns data for testing+ */+ generateSampleReturns(+ nScenarios = 200,+ nAssets = 4,+ assetNames = ['Stocks', 'Bonds', 'Commodities', 'Cash']+ ): Record<string, Record<string, number>> {+ const returns: Record<string, Record<string, number>> = {};+ const expectedReturns = [0.08, 0.04, 0.06, 0.02];++ for (let i = 0; i < nAssets; i++) {+ const assetName = assetNames[i] || `Asset${i + 1}`;+ returns[assetName] = {};++ for (let j = 0; j < nScenarios; j++) {+ const date = new Date(2024, 0, j + 1).toISOString().split('T')[0];+ // Random return around expected value+ const dailyExpected = expectedReturns[i] / 252;+ const dailyVol = (i === 0 ? 0.02 : i === 1 ? 0.01 : 0.015);+ returns[assetName][date] = dailyExpected + (Math.random() - 0.5) * dailyVol * 2;+ }+ }++ return returns;+ }+}++// Export singleton instance+export const fortitudoService = new FortitudoService();diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.tsindex 37f16fb73..9b3fbca01 100644--- a/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.ts+++ b/fincept-terminal-desktop/src/services/aiQuantLab/functimeService.ts@@ -16,6 +16,14 @@ export interface FunctimeStatusResponse {polars_available?: boolean;lightgbm_available?: boolean;functime_cloud_available?: boolean;+ advanced_models_available?: boolean;+ ensemble_available?: boolean;+ anomaly_available?: boolean;+ seasonality_available?: boolean;+ confidence_available?: boolean;+ feature_importance_available?: boolean;+ advanced_cv_available?: boolean;+ backtesting_available?: boolean;message?: string;error?: string;}@@ -156,6 +164,349 @@ export type PanelData =| Record<string, number> // {date: value} (single entity)| Array<{ entity_id: string; time: string; value: number }>; // Array format++// ============================================================================+// ADVANCED MODELS TYPES+// ============================================================================++export type AdvancedModel = 'naive' | 'seasonal_naive' | 'drift' | 'ses' | 'holt' |+ 'theta' | 'croston' | 'xgboost' | 'catboost';++export interface AdvancedForecastConfig {+ model: AdvancedModel;+ horizon?: number;+ frequency?: string;+ model_params?: {+ seasonal_period?: number;+ alpha?: number;+ beta?: number;+ n_lags?: number;+ xgb_params?: Record<string, unknown>;+ cat_params?: Record<string, unknown>;+ };+}++export interface AdvancedForecastResponse {+ success: boolean;+ model?: string;+ forecast?: ForecastResult[];+ shape?: [number, number];+ error?: string;+}+++// ============================================================================+// ENSEMBLE TYPES+// ============================================================================++export type EnsembleMethod = 'mean' | 'median' | 'trimmed_mean' | 'weighted' | 'stacking';++export interface EnsembleConfig {+ method: EnsembleMethod;+ trim_pct?: number;+ weights?: number[];+}++export interface EnsembleResponse {+ success: boolean;+ method?: string;+ data?: Array<{ entity_id: string; time: string; value: number }>;+ shape?: [number, number];+ error?: string;+}++export interface AutoEnsembleResponse {+ success: boolean;+ method?: string;+ models_used?: string[];+ model_scores?: Record<string, number>;+ ensemble_forecast?: Array<{ entity_id: string; time: string; value: number }>;+ error?: string;+}+++// ============================================================================+// ANOMALY DETECTION TYPES+// ============================================================================++export type AnomalyMethod = 'zscore' | 'iqr' | 'grubbs' | 'isolation_forest' | 'lof' | 'residual' | 'change_points';++export interface AnomalyDetectionConfig {+ method: AnomalyMethod;+ threshold?: number;+ multiplier?: number;+ alpha?: number;+ contamination?: number;+ n_neighbors?: number;+ n_bkps?: number;+}++export interface AnomalyResult {+ entity_id: string;+ anomalies: Array<{+ index: number;+ time: string;+ value: number;+ zscore?: number;+ is_anomaly: boolean;+ }>;+ n_anomalies: number;+ anomaly_rate: number;+}++export interface AnomalyDetectionResponse {+ success: boolean;+ method?: string;+ results?: Record<string, AnomalyResult>;+ error?: string;+}+++// ============================================================================+// SEASONALITY TYPES+// ============================================================================++export type SeasonalityOperation = 'detect_period' | 'decompose_stl' | 'decompose_classical' | 'adjust' | 'metrics';++export interface SeasonalityConfig {+ operation: SeasonalityOperation;+ period?: number;+ method?: 'fft' | 'acf' | 'both' | 'stl' | 'classical';+ max_period?: number;+ robust?: boolean;+ model?: 'additive' | 'multiplicative';+}++export interface SeasonalDecompositionResult {+ trend: number[];+ seasonal: number[];+ residual: number[];+ times: string[];+ period: number;+ seasonal_strength?: number;+}++export interface SeasonalityResponse {+ success: boolean;+ method?: string;+ results?: Record<string, SeasonalDecompositionResult | { period: number; strength: number }>;+ data?: Array<{ entity_id: string; time: string; original: number; adjusted: number }>;+ metrics?: Record<string, {+ detected_period?: number;+ seasonal_strength: number;+ trend_strength: number;+ is_seasonal: boolean;+ is_trending: boolean;+ }>;+ error?: string;+}+++// ============================================================================+// CONFIDENCE INTERVALS TYPES+// ============================================================================++export type IntervalMethod = 'bootstrap' | 'residual' | 'quantile' | 'conformal' | 'monte_carlo';++export interface ConfidenceIntervalsConfig {+ method: IntervalMethod;+ horizon?: number;+ frequency?: string;+ confidence_levels?: number[];+ n_bootstrap?: number;+ n_simulations?: number;+ lags?: number;+ quantiles?: number[];+ calibration_size?: number;+ model?: 'random_walk' | 'drift' | 'mean_revert';+}++export interface IntervalDataPoint {+ entity_id: string;+ time: string;+ forecast: number;+ horizon: number;+ lower_80?: number;+ upper_80?: number;+ lower_95?: number;+ upper_95?: number;+ [key: string]: unknown;+}++export interface ConfidenceIntervalsResponse {+ success: boolean;+ method?: string;+ confidence_levels?: number[];+ data?: IntervalDataPoint[];+ shape?: [number, number];+ error?: string;+}+++// ============================================================================+// FEATURE IMPORTANCE TYPES+// ============================================================================++export type ImportanceMethod = 'permutation' | 'model' | 'shap' | 'lag_analysis' | 'sensitivity';++export interface FeatureImportanceConfig {+ method: ImportanceMethod;+ n_lags?: number;+ n_repeats?: number;+ model_type?: 'ridge' | 'lasso' | 'rf';+ max_samples?: number;+ max_lags?: number;+ horizon?: number;+ perturbation_pct?: number;+ frequency?: string;+}++export interface FeatureImportanceResult {+ feature_names: string[];+ importance_mean?: number[];+ importance_std?: number[];+ importance?: number[];+ acf?: number[];+ pacf?: number[];+ significant_lags?: number[];+ recommended_lags?: number[];+ sensitivity_by_point?: Array<{+ point_index: number;+ recency: number;+ sensitivity: number;+ }>;+}++export interface FeatureImportanceResponse {+ success: boolean;+ method?: string;+ n_lags?: number;+ results?: Record<string, FeatureImportanceResult>;+ error?: string;+}+++// ============================================================================+// ADVANCED CROSS-VALIDATION TYPES+// ============================================================================++export type AdvancedCVMethod = 'blocked' | 'purged' | 'combinatorial' | 'walk_forward' | 'nested';++export interface AdvancedCVConfig {+ method: AdvancedCVMethod;+ n_splits?: number;+ test_size?: number;+ gap?: number;+ embargo_pct?: number;+ purge_pct?: number;+ n_test_splits?: number;+ n_groups?: number;+ initial_train_size?: number;+ step_size?: number;+ anchored?: boolean;+ outer_splits?: number;+ inner_splits?: number;+}++export interface CVSplitInfo {+ split: number;+ train_shape: [number, number];+ test_shape: [number, number];+ train_size?: number;+ test_size?: number;+}++export interface AdvancedCVResponse {+ success: boolean;+ method?: string;+ n_splits?: number;+ data?: Array<{+ entity_id: string;+ n_splits: number;+ splits: CVSplitInfo[];+ }>;+ error?: string;+}+++// ============================================================================+// BACKTESTING TYPES+// ============================================================================++export type BacktestOperation = 'walk_forward' | 'compare_models' | 'rolling_origin' | 'attribution' | 'summary';++export interface BacktestConfig {+ operation: BacktestOperation;+ initial_train_size?: number;+ test_size?: number;+ step_size?: number;+ horizons?: number[];+ frequency?: string;+ retrain?: boolean;+ min_train_size?: number;+ max_train_size?: number;+}++export interface BacktestForecast {+ origin: number;+ horizon: number;+ forecast: number;+ actual: number;+ error: number;+ abs_error: number;+}++export interface BacktestEntityResult {+ entity_id: string;+ n_origins: number;+ forecasts: BacktestForecast[];+ metrics_by_horizon: Record<number, {+ mae: number;+ rmse: number;+ mape: number;+ bias: number;+ n_forecasts: number;+ }>;+}++export interface BacktestResponse {+ success: boolean;+ method?: string;+ results?: BacktestEntityResult[];+ comparison?: Array<{+ model: string;+ mae: number;+ rmse: number;+ mape: number;+ rank: number;+ }>;+ best_model?: string;+ summary?: {+ total_forecasts: number;+ total_origins: number;+ overall_metrics: {+ mae: number;+ rmse: number;+ bias: number;+ std_error: number;+ };+ error_distribution: {+ min: number;+ p25: number;+ median: number;+ p75: number;+ p95: number;+ max: number;+ };+ by_horizon: Record<number, {+ mae: number;+ rmse: number;+ n_forecasts: number;+ }>;+ };+ error?: string;+}+// ============================================================================// FUNCTIME SERVICE CLASS// ============================================================================@@ -379,6 +730,270 @@ class FunctimeService {}}+ // ============================================================================+ // ADVANCED MODELS METHODS+ // ============================================================================++ /**+ * Run advanced forecasting models (Naive, SES, Holt, Theta, Croston, XGBoost, CatBoost)+ */+ async advancedForecast(+ data: PanelData,+ config: AdvancedForecastConfig+ ): Promise<AdvancedForecastResponse> {+ try {+ const result = await invoke<string>('functime_advanced_forecast', {+ dataJson: JSON.stringify(data),+ model: config.model,+ horizon: config.horizon,+ frequency: config.frequency,+ modelParams: config.model_params+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] advancedForecast error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // ENSEMBLE METHODS+ // ============================================================================++ /**+ * Combine multiple forecasts using ensemble methods+ */+ async ensemble(+ forecasts: Array<Array<{ entity_id: string; time: string; value: number }>>,+ config: EnsembleConfig,+ yTrain?: PanelData+ ): Promise<EnsembleResponse> {+ try {+ const result = await invoke<string>('functime_ensemble', {+ forecastsJson: JSON.stringify(forecasts),+ method: config.method,+ trimPct: config.trim_pct,+ weights: config.weights,+ yTrainJson: yTrain ? JSON.stringify(yTrain) : undefined+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] ensemble error:', error);+ return { success: false, error: String(error) };+ }+ }++ /**+ * Automatic ensemble selection and combination+ */+ async autoEnsemble(+ data: PanelData,+ horizon?: number,+ frequency?: string,+ nBest?: number+ ): Promise<AutoEnsembleResponse> {+ try {+ const result = await invoke<string>('functime_auto_ensemble', {+ dataJson: JSON.stringify(data),+ horizon,+ frequency,+ nBest+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] autoEnsemble error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // ANOMALY DETECTION METHODS+ // ============================================================================++ /**+ * Detect anomalies in time series data+ */+ async detectAnomalies(+ data: PanelData,+ config: AnomalyDetectionConfig+ ): Promise<AnomalyDetectionResponse> {+ try {+ const result = await invoke<string>('functime_anomaly_detection', {+ dataJson: JSON.stringify(data),+ method: config.method,+ threshold: config.threshold,+ multiplier: config.multiplier,+ alpha: config.alpha,+ contamination: config.contamination,+ nNeighbors: config.n_neighbors,+ nBkps: config.n_bkps+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] detectAnomalies error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // SEASONALITY METHODS+ // ============================================================================++ /**+ * Analyze seasonality patterns in time series+ */+ async analyzeSeasonality(+ data: PanelData,+ config: SeasonalityConfig+ ): Promise<SeasonalityResponse> {+ try {+ const result = await invoke<string>('functime_seasonality', {+ dataJson: JSON.stringify(data),+ operation: config.operation,+ period: config.period,+ method: config.method,+ maxPeriod: config.max_period,+ robust: config.robust,+ model: config.model+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] analyzeSeasonality error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // CONFIDENCE INTERVALS METHODS+ // ============================================================================++ /**+ * Generate prediction/confidence intervals+ */+ async generateIntervals(+ data: PanelData,+ config: ConfidenceIntervalsConfig,+ forecast?: PanelData+ ): Promise<ConfidenceIntervalsResponse> {+ try {+ const result = await invoke<string>('functime_confidence_intervals', {+ dataJson: JSON.stringify(data),+ forecastJson: forecast ? JSON.stringify(forecast) : undefined,+ method: config.method,+ horizon: config.horizon,+ frequency: config.frequency,+ confidenceLevels: config.confidence_levels,+ nBootstrap: config.n_bootstrap,+ nSimulations: config.n_simulations,+ lags: config.lags,+ quantiles: config.quantiles,+ calibrationSize: config.calibration_size,+ model: config.model+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] generateIntervals error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // FEATURE IMPORTANCE METHODS+ // ============================================================================++ /**+ * Calculate feature importance for time series models+ */+ async calculateFeatureImportance(+ data: PanelData,+ config: FeatureImportanceConfig+ ): Promise<FeatureImportanceResponse> {+ try {+ const result = await invoke<string>('functime_feature_importance', {+ dataJson: JSON.stringify(data),+ method: config.method,+ nLags: config.n_lags,+ nRepeats: config.n_repeats,+ modelType: config.model_type,+ maxSamples: config.max_samples,+ maxLags: config.max_lags,+ horizon: config.horizon,+ perturbationPct: config.perturbation_pct,+ frequency: config.frequency+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] calculateFeatureImportance error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // ADVANCED CROSS-VALIDATION METHODS+ // ============================================================================++ /**+ * Run advanced cross-validation methods+ */+ async advancedCrossValidate(+ data: PanelData,+ config: AdvancedCVConfig+ ): Promise<AdvancedCVResponse> {+ try {+ const result = await invoke<string>('functime_advanced_cv', {+ dataJson: JSON.stringify(data),+ method: config.method,+ nSplits: config.n_splits,+ testSize: config.test_size,+ gap: config.gap,+ embargoPct: config.embargo_pct,+ purgePct: config.purge_pct,+ nTestSplits: config.n_test_splits,+ nGroups: config.n_groups,+ initialTrainSize: config.initial_train_size,+ stepSize: config.step_size,+ anchored: config.anchored,+ outerSplits: config.outer_splits,+ innerSplits: config.inner_splits+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] advancedCrossValidate error:', error);+ return { success: false, error: String(error) };+ }+ }++ // ============================================================================+ // BACKTESTING METHODS+ // ============================================================================++ /**+ * Run backtesting on time series forecasts+ */+ async backtest(+ data: PanelData,+ config: BacktestConfig+ ): Promise<BacktestResponse> {+ try {+ const result = await invoke<string>('functime_backtest', {+ dataJson: JSON.stringify(data),+ operation: config.operation,+ initialTrainSize: config.initial_train_size,+ testSize: config.test_size,+ stepSize: config.step_size,+ horizons: config.horizons,+ frequency: config.frequency,+ retrain: config.retrain,+ minTrainSize: config.min_train_size,+ maxTrainSize: config.max_train_size+ });+ return JSON.parse(result);+ } catch (error) {+ console.error('[FunctimeService] backtest error:', error);+ return { success: false, error: String(error) };+ }+ }+// ============================================================================// UTILITY METHODS// ============================================================================@@ -453,6 +1068,81 @@ class FunctimeService {];}+ /**+ * Get available advanced forecast models+ */+ getAdvancedModels(): Array<{ id: string; name: string; description: string; category: string }> {+ return [+ // Baseline models+ { id: 'naive', name: 'Naive', description: 'Last value forecast', category: 'Baseline' },+ { id: 'seasonal_naive', name: 'Seasonal Naive', description: 'Same period last season', category: 'Baseline' },+ { id: 'drift', name: 'Drift', description: 'Linear extrapolation from history', category: 'Baseline' },+ // Exponential smoothing+ { id: 'ses', name: 'Simple Exponential Smoothing', description: 'Level smoothing only', category: 'Exponential Smoothing' },+ { id: 'holt', name: 'Holt\'s Linear Trend', description: 'Level and trend smoothing', category: 'Exponential Smoothing' },+ { id: 'theta', name: 'Theta Method', description: 'Decomposition-based forecasting', category: 'Exponential Smoothing' },+ // Specialized+ { id: 'croston', name: 'Croston\'s Method', description: 'For intermittent demand', category: 'Specialized' },+ // ML models+ { id: 'xgboost', name: 'XGBoost', description: 'Gradient boosting with lag features', category: 'Machine Learning' },+ { id: 'catboost', name: 'CatBoost', description: 'Gradient boosting with categorical support', category: 'Machine Learning' }+ ];+ }++ /**+ * Get available anomaly detection methods+ */+ getAnomalyMethods(): Array<{ id: string; name: string; description: string }> {+ return [+ { id: 'zscore', name: 'Z-Score', description: 'Statistical outlier detection' },+ { id: 'iqr', name: 'IQR', description: 'Interquartile range method' },+ { id: 'grubbs', name: 'Grubbs Test', description: 'Statistical hypothesis testing' },+ { id: 'isolation_forest', name: 'Isolation Forest', description: 'Tree-based anomaly detection' },+ { id: 'lof', name: 'Local Outlier Factor', description: 'Density-based detection' },+ { id: 'residual', name: 'Residual', description: 'Model residual-based detection' },+ { id: 'change_points', name: 'Change Points', description: 'Structural break detection' }+ ];+ }++ /**+ * Get available ensemble methods+ */+ getEnsembleMethods(): Array<{ id: string; name: string; description: string }> {+ return [+ { id: 'mean', name: 'Mean', description: 'Simple average of forecasts' },+ { id: 'median', name: 'Median', description: 'Median of forecasts (robust)' },+ { id: 'trimmed_mean', name: 'Trimmed Mean', description: 'Mean with outliers removed' },+ { id: 'weighted', name: 'Weighted', description: 'Error-weighted combination' },+ { id: 'stacking', name: 'Stacking', description: 'Meta-learner combination' }+ ];+ }++ /**+ * Get available confidence interval methods+ */+ getIntervalMethods(): Array<{ id: string; name: string; description: string }> {+ return [+ { id: 'bootstrap', name: 'Bootstrap', description: 'Resampling-based intervals' },+ { id: 'residual', name: 'Residual', description: 'Based on historical residuals' },+ { id: 'quantile', name: 'Quantile Regression', description: 'Direct quantile modeling' },+ { id: 'conformal', name: 'Conformal Prediction', description: 'Coverage-guaranteed intervals' },+ { id: 'monte_carlo', name: 'Monte Carlo', description: 'Simulation-based intervals' }+ ];+ }++ /**+ * Get available CV methods+ */+ getCVMethods(): Array<{ id: string; name: string; description: string }> {+ return [+ { id: 'blocked', name: 'Blocked', description: 'Fixed-size training blocks' },+ { id: 'purged', name: 'Purged K-Fold', description: 'For overlapping labels' },+ { id: 'combinatorial', name: 'Combinatorial Purged', description: 'All test group combinations' },+ { id: 'walk_forward', name: 'Walk-Forward', description: 'Rolling origin validation' },+ { id: 'nested', name: 'Nested', description: 'For model selection' }+ ];+ }+/*** Get available frequencies*/diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFortitudoService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFortitudoService.tsnew file mode 100644index 000000000..65dcb867d--- /dev/null+++ b/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFortitudoService.ts@@ -0,0 +1,553 @@+/**+ * Portfolio-Fortitudo Integration Service+ * Bridges user portfolios from Portfolio Tab to Fortitudo.tech analytics+ *+ * Fetches historical returns for portfolio holdings and formats them+ * for use with portfolio risk metrics, optimization, and efficient frontier.+ */++import { portfolioService, Portfolio, PortfolioSummary, HoldingWithQuote } from '../portfolioService';+import { yfinanceService, HistoricalDataPoint } from '../yfinanceService';+import { fortitudoService, ReturnsData, WeightsData, OptimizationResult, EfficientFrontierResponse, FullAnalysisResponse } from './fortitudoService';++// ============================================================================+// TYPES+// ============================================================================++export interface PortfolioReturnsData {+ returns: Record<string, Record<string, number>>; // {symbol: {date: return}}+ weights: Record<string, number>; // {symbol: weight}+ assets: string[];+ nScenarios: number;+ startDate: string;+ endDate: string;+}++export interface PortfolioForAnalysis {+ portfolio: Portfolio;+ summary: PortfolioSummary;+ returnsData: PortfolioReturnsData | null;+ isLoading: boolean;+ error: string | null;+}++export interface PortfolioAnalysisResult {+ success: boolean;+ portfolio: Portfolio;+ analysis?: {+ metrics_equal_weight: any;+ metrics_exp_decay: any;+ covariance_matrix?: Record<string, Record<string, number>>;+ correlation_matrix?: Record<string, Record<string, number>>;+ moments?: Record<string, Record<string, number>>;+ half_life: number;+ alpha: number;+ n_scenarios: number;+ n_assets: number;+ assets: string[];+ };+ error?: string;+}++// ============================================================================+// SERVICE CLASS+// ============================================================================++class PortfolioFortitudoService {+ /**+ * Get all user portfolios available for analysis+ */+ async getAvailablePortfolios(): Promise<Portfolio[]> {+ try {+ return await portfolioService.getPortfolios();+ } catch (error) {+ console.error('[PortfolioFortitudoService] Error fetching portfolios:', error);+ return [];+ }+ }++ /**+ * Get portfolio summary with current holdings and weights+ */+ async getPortfolioSummary(portfolioId: string): Promise<PortfolioSummary | null> {+ try {+ return await portfolioService.getPortfolioSummary(portfolioId);+ } catch (error) {+ console.error('[PortfolioFortitudoService] Error fetching portfolio summary:', error);+ return null;+ }+ }++ /**+ * Fetch historical returns data for portfolio holdings+ * Converts price data to daily returns format required by Fortitudo+ *+ * @param holdings - Array of portfolio holdings with symbols+ * @param days - Number of historical days (default: 252 = 1 year)+ */+ async fetchHistoricalReturns(+ holdings: HoldingWithQuote[],+ days: number = 252+ ): Promise<PortfolioReturnsData | null> {+ try {+ const symbols = holdings.map(h => h.symbol);+ const weights: Record<string, number> = {};++ // Build weights from holdings (normalized to 0-1)+ holdings.forEach(h => {+ weights[h.symbol] = h.weight / 100; // Convert from percentage to decimal+ });++ // Calculate date range+ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - days - 30); // Extra buffer for non-trading days++ const formatDate = (date: Date) => date.toISOString().split('T')[0];++ // Fetch historical data for all symbols in parallel+ const historicalPromises = symbols.map(symbol =>+ yfinanceService.getHistoricalData(symbol, formatDate(startDate), formatDate(endDate))+ .then(data => ({ symbol, data }))+ .catch(err => {+ console.warn(`[PortfolioFortitudoService] Failed to fetch data for ${symbol}:`, err);+ return { symbol, data: [] as HistoricalDataPoint[] };+ })+ );++ const historicalResults = await Promise.all(historicalPromises);++ // Convert price data to returns+ const returns: Record<string, Record<string, number>> = {};+ let minLength = Infinity;+ const allDates = new Set<string>();++ historicalResults.forEach(({ symbol, data }) => {+ if (data.length < 2) {+ console.warn(`[PortfolioFortitudoService] Insufficient data for ${symbol}`);+ return;+ }++ returns[symbol] = {};++ // Calculate daily returns: (P_t - P_{t-1}) / P_{t-1}+ for (let i = 1; i < data.length; i++) {+ const prevClose = data[i - 1].adj_close || data[i - 1].close;+ const currClose = data[i].adj_close || data[i].close;++ if (prevClose > 0) {+ const dailyReturn = (currClose - prevClose) / prevClose;+ const dateStr = new Date(data[i].timestamp * 1000).toISOString().split('T')[0];+ returns[symbol][dateStr] = dailyReturn;+ allDates.add(dateStr);+ }+ }++ minLength = Math.min(minLength, Object.keys(returns[symbol]).length);+ });++ // Filter to only symbols with sufficient data+ const validSymbols = Object.keys(returns).filter(s => Object.keys(returns[s]).length >= 20);++ if (validSymbols.length === 0) {+ console.error('[PortfolioFortitudoService] No symbols with sufficient historical data');+ return null;+ }++ // Align returns to common dates+ const sortedDates = Array.from(allDates).sort();+ const alignedReturns: Record<string, Record<string, number>> = {};++ validSymbols.forEach(symbol => {+ alignedReturns[symbol] = {};+ sortedDates.forEach(date => {+ if (returns[symbol][date] !== undefined) {+ alignedReturns[symbol][date] = returns[symbol][date];+ }+ });+ });++ // Normalize weights to only include valid symbols+ const validWeights: Record<string, number> = {};+ let totalWeight = 0;+ validSymbols.forEach(s => {+ if (weights[s]) {+ totalWeight += weights[s];+ }+ });++ validSymbols.forEach(s => {+ validWeights[s] = weights[s] ? weights[s] / totalWeight : 1 / validSymbols.length;+ });++ return {+ returns: alignedReturns,+ weights: validWeights,+ assets: validSymbols,+ nScenarios: Math.min(...validSymbols.map(s => Object.keys(alignedReturns[s]).length)),+ startDate: sortedDates[0],+ endDate: sortedDates[sortedDates.length - 1]+ };+ } catch (error) {+ console.error('[PortfolioFortitudoService] Error fetching historical returns:', error);+ return null;+ }+ }++ /**+ * Run full portfolio analysis using Fortitudo.tech+ *+ * @param portfolioId - Portfolio ID to analyze+ * @param alpha - VaR/CVaR confidence level (default: 0.05 = 95%)+ * @param halfLife - Half-life for exponential decay (default: 252 days)+ * @param days - Historical days to fetch (default: 252)+ */+ async runPortfolioAnalysis(+ portfolioId: string,+ alpha: number = 0.05,+ halfLife: number = 252,+ days: number = 252+ ): Promise<PortfolioAnalysisResult> {+ try {+ // Get portfolio summary+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary) {+ return { success: false, portfolio: null as any, error: 'Portfolio not found' };+ }++ if (summary.holdings.length === 0) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Portfolio has no holdings'+ };+ }++ // Fetch historical returns+ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Failed to fetch historical returns data'+ };+ }++ // Run Fortitudo analysis+ const result = await fortitudoService.fullAnalysis(+ returnsData.returns,+ Object.values(returnsData.weights),+ alpha,+ halfLife+ );++ if (!result.success || !result.analysis) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: result.error || 'Analysis failed'+ };+ }++ return {+ success: true,+ portfolio: summary.portfolio,+ analysis: {+ ...result.analysis,+ assets: returnsData.assets+ }+ };+ } catch (error) {+ console.error('[PortfolioFortitudoService] Analysis error:', error);+ return {+ success: false,+ portfolio: null as any,+ error: String(error)+ };+ }+ }++ /**+ * Run Mean-Variance portfolio optimization+ */+ async optimizeMeanVariance(+ portfolioId: string,+ objective: 'min_variance' | 'max_sharpe' | 'target_return' = 'min_variance',+ longOnly: boolean = true,+ maxWeight: number = 0.5,+ riskFreeRate: number = 0.05,+ targetReturn?: number,+ days: number = 252+ ): Promise<OptimizationResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return { success: false, error: 'Failed to fetch historical returns' };+ }++ return fortitudoService.optimizeMeanVariance(+ returnsData.returns,+ objective,+ longOnly,+ maxWeight,+ 0, // minWeight+ riskFreeRate,+ targetReturn+ );+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Run Mean-CVaR portfolio optimization+ */+ async optimizeMeanCVaR(+ portfolioId: string,+ objective: 'min_cvar' | 'target_return' = 'min_cvar',+ alpha: number = 0.05,+ longOnly: boolean = true,+ maxWeight: number = 0.5,+ riskFreeRate: number = 0.05,+ targetReturn?: number,+ days: number = 252+ ): Promise<OptimizationResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return { success: false, error: 'Failed to fetch historical returns' };+ }++ return fortitudoService.optimizeMeanCVaR(+ returnsData.returns,+ objective,+ alpha,+ longOnly,+ maxWeight,+ 0,+ riskFreeRate,+ targetReturn+ );+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Generate efficient frontier for portfolio assets+ */+ async generateEfficientFrontier(+ portfolioId: string,+ type: 'mv' | 'cvar' = 'mv',+ nPoints: number = 20,+ longOnly: boolean = true,+ maxWeight: number = 0.5,+ alpha: number = 0.05,+ riskFreeRate: number = 0.05,+ days: number = 252+ ): Promise<EfficientFrontierResponse> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return { success: false, error: 'Failed to fetch historical returns' };+ }++ if (type === 'mv') {+ return fortitudoService.efficientFrontierMV(+ returnsData.returns,+ nPoints,+ longOnly,+ maxWeight,+ riskFreeRate+ );+ } else {+ return fortitudoService.efficientFrontierCVaR(+ returnsData.returns,+ nPoints,+ alpha,+ longOnly,+ maxWeight+ );+ }+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Compare current portfolio weights vs optimal weights+ */+ async compareWithOptimal(+ portfolioId: string,+ objective: 'min_variance' | 'max_sharpe' = 'min_variance',+ days: number = 252+ ): Promise<{+ success: boolean;+ current: { weights: Record<string, number>; metrics: any } | null;+ optimal: { weights: Record<string, number>; metrics: any } | null;+ improvement: Record<string, number> | null;+ error?: string;+ }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, current: null, optimal: null, improvement: null, error: 'Portfolio not found or empty' };+ }++ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return { success: false, current: null, optimal: null, improvement: null, error: 'Failed to fetch historical returns' };+ }++ // Calculate current portfolio metrics+ const currentResult = await fortitudoService.fullAnalysis(+ returnsData.returns,+ Object.values(returnsData.weights),+ 0.05,+ 252+ );++ // Get optimal weights+ const optimalResult = await fortitudoService.optimizeMeanVariance(+ returnsData.returns,+ objective,+ true,+ 0.5,+ 0,+ 0.05+ );++ if (!currentResult.success || !optimalResult.success) {+ return {+ success: false,+ current: null,+ optimal: null,+ improvement: null,+ error: currentResult.error || optimalResult.error+ };+ }++ // Calculate improvement+ const improvement: Record<string, number> = {};++ if (currentResult.analysis && optimalResult) {+ const currentMetrics = currentResult.analysis.metrics_equal_weight;+ improvement.expected_return = (optimalResult.expected_return || 0) - (currentMetrics?.expected_return || 0);+ improvement.volatility = (currentMetrics?.volatility || 0) - (optimalResult.volatility || 0); // Lower is better+ improvement.sharpe_ratio = (optimalResult.sharpe_ratio || 0) - (currentMetrics?.sharpe_ratio || 0);+ }++ return {+ success: true,+ current: {+ weights: returnsData.weights,+ metrics: currentResult.analysis?.metrics_equal_weight+ },+ optimal: {+ weights: optimalResult.weights as Record<string, number>,+ metrics: {+ expected_return: optimalResult.expected_return,+ volatility: optimalResult.volatility,+ sharpe_ratio: optimalResult.sharpe_ratio+ }+ },+ improvement+ };+ } catch (error) {+ return { success: false, current: null, optimal: null, improvement: null, error: String(error) };+ }+ }++ /**+ * Get portfolio risk contribution by asset+ */+ async getRiskContribution(+ portfolioId: string,+ days: number = 252+ ): Promise<{+ success: boolean;+ contributions?: Record<string, { weight: number; marginal_var: number; component_var: number; pct_contribution: number }>;+ total_var?: number;+ error?: string;+ }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const returnsData = await this.fetchHistoricalReturns(summary.holdings, days);+ if (!returnsData) {+ return { success: false, error: 'Failed to fetch historical returns' };+ }++ // Get covariance matrix+ const covResult = await fortitudoService.covarianceAnalysis(returnsData.returns);++ if (!covResult.success || !covResult.covariance_matrix) {+ return { success: false, error: 'Failed to calculate covariance matrix' };+ }++ // Calculate risk contributions (simplified Euler decomposition)+ const weights = returnsData.weights;+ const assets = returnsData.assets;+ const cov = covResult.covariance_matrix;++ // Portfolio variance = w' * Cov * w+ let portfolioVar = 0;+ assets.forEach((a1, i) => {+ assets.forEach((a2, j) => {+ portfolioVar += weights[a1] * weights[a2] * (cov[a1]?.[a2] || 0);+ });+ });++ const portfolioVol = Math.sqrt(portfolioVar);++ // Marginal contribution = (Cov * w) / portfolio_vol+ const contributions: Record<string, any> = {};++ assets.forEach(asset => {+ let marginalSum = 0;+ assets.forEach(other => {+ marginalSum += (cov[asset]?.[other] || 0) * weights[other];+ });++ const marginalVar = marginalSum / portfolioVol;+ const componentVar = weights[asset] * marginalVar;++ contributions[asset] = {+ weight: weights[asset],+ marginal_var: marginalVar,+ component_var: componentVar,+ pct_contribution: portfolioVol > 0 ? componentVar / portfolioVol * 100 : 0+ };+ });++ return {+ success: true,+ contributions,+ total_var: portfolioVar+ };+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }+}++// Export singleton instance+export const portfolioFortitudoService = new PortfolioFortitudoService();diff --git a/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFunctimeService.ts b/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFunctimeService.tsnew file mode 100644index 000000000..441de23d4--- /dev/null+++ b/fincept-terminal-desktop/src/services/aiQuantLab/portfolioFunctimeService.ts@@ -0,0 +1,670 @@+/**+ * Portfolio-Functime Integration Service+ * Bridges user portfolios from Portfolio Tab to Functime time series analytics+ *+ * Fetches historical price data for portfolio holdings and formats them+ * for use with forecasting, anomaly detection, seasonality analysis, etc.+ */++import { portfolioService, Portfolio, PortfolioSummary, HoldingWithQuote } from '../portfolioService';+import { yfinanceService, HistoricalDataPoint } from '../yfinanceService';+import {+ functimeService,+ PanelData,+ ForecastResult,+ ForecastConfig,+ AdvancedForecastConfig,+ AnomalyDetectionConfig,+ SeasonalityConfig,+ ConfidenceIntervalsConfig,+ BacktestConfig,+ ForecastResponse,+ AdvancedForecastResponse,+ AnomalyDetectionResponse,+ SeasonalityResponse,+ ConfidenceIntervalsResponse,+ BacktestResponse,+ AutoEnsembleResponse+} from './functimeService';++// ============================================================================+// TYPES+// ============================================================================++export interface PortfolioPriceData {+ panelData: Array<{ entity_id: string; time: string; value: number }>;+ assets: string[];+ nDataPoints: number;+ startDate: string;+ endDate: string;+}++export interface PortfolioForForecasting {+ portfolio: Portfolio;+ summary: PortfolioSummary;+ priceData: PortfolioPriceData | null;+ isLoading: boolean;+ error: string | null;+}++export interface PortfolioForecastResult {+ success: boolean;+ portfolio: Portfolio;+ forecasts?: Record<string, ForecastResult[]>; // {symbol: forecasts}+ metrics?: Record<string, {+ mae?: number;+ rmse?: number;+ smape?: number;+ }>;+ error?: string;+}++export interface PortfolioAnomalyResult {+ success: boolean;+ portfolio: Portfolio;+ anomalies?: Record<string, {+ count: number;+ rate: number;+ dates: string[];+ values: number[];+ }>;+ error?: string;+}++export interface PortfolioSeasonalityResult {+ success: boolean;+ portfolio: Portfolio;+ seasonality?: Record<string, {+ period: number;+ strength: number;+ is_seasonal: boolean;+ trend_strength?: number;+ }>;+ error?: string;+}++// ============================================================================+// SERVICE CLASS+// ============================================================================++class PortfolioFunctimeService {+ /**+ * Get all user portfolios available for analysis+ */+ async getAvailablePortfolios(): Promise<Portfolio[]> {+ try {+ return await portfolioService.getPortfolios();+ } catch (error) {+ console.error('[PortfolioFunctimeService] Error fetching portfolios:', error);+ return [];+ }+ }++ /**+ * Get portfolio summary with current holdings+ */+ async getPortfolioSummary(portfolioId: string): Promise<PortfolioSummary | null> {+ try {+ return await portfolioService.getPortfolioSummary(portfolioId);+ } catch (error) {+ console.error('[PortfolioFunctimeService] Error fetching portfolio summary:', error);+ return null;+ }+ }++ /**+ * Fetch historical price data for portfolio holdings in panel data format+ * This format is required by functime for multi-entity time series analysis+ *+ * @param holdings - Array of portfolio holdings with symbols+ * @param days - Number of historical days (default: 365)+ */+ async fetchHistoricalPrices(+ holdings: HoldingWithQuote[],+ days: number = 365+ ): Promise<PortfolioPriceData | null> {+ try {+ const symbols = holdings.map(h => h.symbol);++ // Calculate date range+ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - days - 30); // Extra buffer++ const formatDate = (date: Date) => date.toISOString().split('T')[0];++ // Fetch historical data for all symbols in parallel+ const historicalPromises = symbols.map(symbol =>+ yfinanceService.getHistoricalData(symbol, formatDate(startDate), formatDate(endDate))+ .then(data => ({ symbol, data }))+ .catch(err => {+ console.warn(`[PortfolioFunctimeService] Failed to fetch data for ${symbol}:`, err);+ return { symbol, data: [] as HistoricalDataPoint[] };+ })+ );++ const historicalResults = await Promise.all(historicalPromises);++ // Convert to panel data format+ const panelData: Array<{ entity_id: string; time: string; value: number }> = [];+ const validSymbols: string[] = [];+ const allDates = new Set<string>();++ historicalResults.forEach(({ symbol, data }) => {+ if (data.length < 10) {+ console.warn(`[PortfolioFunctimeService] Insufficient data for ${symbol}`);+ return;+ }++ validSymbols.push(symbol);++ data.forEach(point => {+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];+ const price = point.adj_close || point.close;++ panelData.push({+ entity_id: symbol,+ time: dateStr,+ value: price+ });++ allDates.add(dateStr);+ });+ });++ if (validSymbols.length === 0) {+ console.error('[PortfolioFunctimeService] No symbols with sufficient historical data');+ return null;+ }++ // Sort panel data by entity and time+ panelData.sort((a, b) => {+ if (a.entity_id !== b.entity_id) {+ return a.entity_id.localeCompare(b.entity_id);+ }+ return a.time.localeCompare(b.time);+ });++ const sortedDates = Array.from(allDates).sort();++ return {+ panelData,+ assets: validSymbols,+ nDataPoints: panelData.length,+ startDate: sortedDates[0],+ endDate: sortedDates[sortedDates.length - 1]+ };+ } catch (error) {+ console.error('[PortfolioFunctimeService] Error fetching historical prices:', error);+ return null;+ }+ }++ /**+ * Run forecasting for all portfolio holdings+ *+ * @param portfolioId - Portfolio ID to forecast+ * @param model - Forecast model to use+ * @param horizon - Forecast horizon in days+ * @param frequency - Data frequency+ * @param days - Historical days to fetch+ */+ async forecastPortfolio(+ portfolioId: string,+ model: string = 'linear',+ horizon: number = 30,+ frequency: string = '1d',+ days: number = 365+ ): Promise<PortfolioForecastResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary) {+ return { success: false, portfolio: null as any, error: 'Portfolio not found' };+ }++ if (summary.holdings.length === 0) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Portfolio has no holdings'+ };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Failed to fetch historical price data'+ };+ }++ // Run forecast using functime+ const result = await functimeService.fullPipeline(+ priceData.panelData,+ model,+ horizon,+ frequency,+ Math.min(horizon, 30) // Test size+ );++ if (!result.success) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: result.error+ };+ }++ // Group forecasts by symbol+ const forecastsBySymbol: Record<string, ForecastResult[]> = {};+ result.forecast?.forEach(fc => {+ if (!forecastsBySymbol[fc.entity_id]) {+ forecastsBySymbol[fc.entity_id] = [];+ }+ forecastsBySymbol[fc.entity_id].push(fc);+ });++ return {+ success: true,+ portfolio: summary.portfolio,+ forecasts: forecastsBySymbol,+ metrics: result.evaluation_metrics ? { overall: result.evaluation_metrics } : undefined+ };+ } catch (error) {+ console.error('[PortfolioFunctimeService] Forecast error:', error);+ return { success: false, portfolio: null as any, error: String(error) };+ }+ }++ /**+ * Run advanced forecasting models on portfolio holdings+ */+ async advancedForecastPortfolio(+ portfolioId: string,+ config: AdvancedForecastConfig,+ days: number = 365+ ): Promise<PortfolioForecastResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, portfolio: summary?.portfolio || null as any, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Failed to fetch historical price data'+ };+ }++ const result = await functimeService.advancedForecast(priceData.panelData, config);++ if (!result.success) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: result.error+ };+ }++ // Group forecasts by symbol+ const forecastsBySymbol: Record<string, ForecastResult[]> = {};+ result.forecast?.forEach(fc => {+ if (!forecastsBySymbol[fc.entity_id]) {+ forecastsBySymbol[fc.entity_id] = [];+ }+ forecastsBySymbol[fc.entity_id].push(fc);+ });++ return {+ success: true,+ portfolio: summary.portfolio,+ forecasts: forecastsBySymbol+ };+ } catch (error) {+ return { success: false, portfolio: null as any, error: String(error) };+ }+ }++ /**+ * Run auto ensemble forecasting on portfolio+ */+ async autoEnsemblePortfolio(+ portfolioId: string,+ horizon: number = 30,+ frequency: string = '1d',+ nBest: number = 3,+ days: number = 365+ ): Promise<AutoEnsembleResponse & { portfolio?: Portfolio }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return { success: false, error: 'Failed to fetch historical price data' };+ }++ const result = await functimeService.autoEnsemble(priceData.panelData, horizon, frequency, nBest);+ return { ...result, portfolio: summary.portfolio };+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Detect anomalies in portfolio holdings' price movements+ */+ async detectPortfolioAnomalies(+ portfolioId: string,+ config: AnomalyDetectionConfig = { method: 'zscore', threshold: 3.0 },+ days: number = 365+ ): Promise<PortfolioAnomalyResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, portfolio: summary?.portfolio || null as any, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Failed to fetch historical price data'+ };+ }++ const result = await functimeService.detectAnomalies(priceData.panelData, config);++ if (!result.success || !result.results) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: result.error || 'Anomaly detection failed'+ };+ }++ // Format results by symbol+ const anomalies: Record<string, any> = {};+ Object.entries(result.results).forEach(([symbol, data]) => {+ const anomalyList = data.anomalies?.filter(a => a.is_anomaly) || [];+ anomalies[symbol] = {+ count: data.n_anomalies,+ rate: data.anomaly_rate,+ dates: anomalyList.map(a => a.time),+ values: anomalyList.map(a => a.value)+ };+ });++ return {+ success: true,+ portfolio: summary.portfolio,+ anomalies+ };+ } catch (error) {+ return { success: false, portfolio: null as any, error: String(error) };+ }+ }++ /**+ * Analyze seasonality patterns in portfolio holdings+ */+ async analyzePortfolioSeasonality(+ portfolioId: string,+ days: number = 730 // 2 years for better seasonality detection+ ): Promise<PortfolioSeasonalityResult> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, portfolio: summary?.portfolio || null as any, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: 'Failed to fetch historical price data'+ };+ }++ // Get seasonality metrics+ const result = await functimeService.analyzeSeasonality(priceData.panelData, {+ operation: 'metrics'+ });++ if (!result.success) {+ return {+ success: false,+ portfolio: summary.portfolio,+ error: result.error || 'Seasonality analysis failed'+ };+ }++ // Format results by symbol+ const seasonality: Record<string, any> = {};+ if (result.metrics) {+ Object.entries(result.metrics).forEach(([symbol, data]) => {+ seasonality[symbol] = {+ period: data.detected_period || 0,+ strength: data.seasonal_strength,+ is_seasonal: data.is_seasonal,+ trend_strength: data.trend_strength+ };+ });+ }++ return {+ success: true,+ portfolio: summary.portfolio,+ seasonality+ };+ } catch (error) {+ return { success: false, portfolio: null as any, error: String(error) };+ }+ }++ /**+ * Generate prediction intervals for portfolio forecasts+ */+ async generatePortfolioIntervals(+ portfolioId: string,+ config: ConfidenceIntervalsConfig,+ days: number = 365+ ): Promise<ConfidenceIntervalsResponse & { portfolio?: Portfolio }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return { success: false, error: 'Failed to fetch historical price data' };+ }++ const result = await functimeService.generateIntervals(priceData.panelData, config);+ return { ...result, portfolio: summary.portfolio };+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Run backtesting on portfolio holdings+ */+ async backtestPortfolio(+ portfolioId: string,+ config: BacktestConfig,+ days: number = 500+ ): Promise<BacktestResponse & { portfolio?: Portfolio }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ const priceData = await this.fetchHistoricalPrices(summary.holdings, days);+ if (!priceData) {+ return { success: false, error: 'Failed to fetch historical price data' };+ }++ const result = await functimeService.backtest(priceData.panelData, config);+ return { ...result, portfolio: summary.portfolio };+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Get portfolio-wide forecast summary with all holdings+ */+ async getPortfolioForecastSummary(+ portfolioId: string,+ horizon: number = 30,+ days: number = 365+ ): Promise<{+ success: boolean;+ portfolio?: Portfolio;+ holdings?: Array<{+ symbol: string;+ currentPrice: number;+ forecastedPrice: number;+ change: number;+ changePct: number;+ }>;+ portfolioForecast?: {+ currentValue: number;+ forecastedValue: number;+ change: number;+ changePct: number;+ };+ error?: string;+ }> {+ try {+ const summary = await this.getPortfolioSummary(portfolioId);+ if (!summary || summary.holdings.length === 0) {+ return { success: false, error: 'Portfolio not found or empty' };+ }++ // Forecast each holding+ const forecastResult = await this.forecastPortfolio(+ portfolioId,+ 'auto_ridge', // Use auto-tuned model+ horizon,+ '1d',+ days+ );++ if (!forecastResult.success || !forecastResult.forecasts) {+ return { success: false, portfolio: summary.portfolio, error: forecastResult.error };+ }++ const holdingsSummary: Array<any> = [];+ let currentPortfolioValue = 0;+ let forecastedPortfolioValue = 0;++ summary.holdings.forEach(holding => {+ const forecasts = forecastResult.forecasts?.[holding.symbol];+ const lastForecast = forecasts?.[forecasts.length - 1];++ const currentPrice = holding.current_price || 0;+ const forecastedPrice = lastForecast?.value || currentPrice;+ const change = forecastedPrice - currentPrice;+ const changePct = currentPrice > 0 ? (change / currentPrice) * 100 : 0;++ holdingsSummary.push({+ symbol: holding.symbol,+ currentPrice,+ forecastedPrice,+ change,+ changePct+ });++ currentPortfolioValue += currentPrice * holding.quantity;+ forecastedPortfolioValue += forecastedPrice * holding.quantity;+ });++ const portfolioChange = forecastedPortfolioValue - currentPortfolioValue;+ const portfolioChangePct = currentPortfolioValue > 0+ ? (portfolioChange / currentPortfolioValue) * 100+ : 0;++ return {+ success: true,+ portfolio: summary.portfolio,+ holdings: holdingsSummary,+ portfolioForecast: {+ currentValue: currentPortfolioValue,+ forecastedValue: forecastedPortfolioValue,+ change: portfolioChange,+ changePct: portfolioChangePct+ }+ };+ } catch (error) {+ return { success: false, error: String(error) };+ }+ }++ /**+ * Fetch data for a single symbol (not portfolio-based)+ */+ async fetchSymbolData(+ symbol: string,+ days: number = 365+ ): Promise<Array<{ entity_id: string; time: string; value: number }> | null> {+ try {+ const endDate = new Date();+ const startDate = new Date();+ startDate.setDate(startDate.getDate() - days);++ const formatDate = (date: Date) => date.toISOString().split('T')[0];++ const data = await yfinanceService.getHistoricalData(+ symbol,+ formatDate(startDate),+ formatDate(endDate)+ );++ if (!data || data.length === 0) {+ return null;+ }++ return data.map(point => ({+ entity_id: symbol,+ time: new Date(point.timestamp * 1000).toISOString().split('T')[0],+ value: point.adj_close || point.close+ }));+ } catch (error) {+ console.error(`[PortfolioFunctimeService] Error fetching symbol data for ${symbol}:`, error);+ return null;+ }+ }++ /**+ * Forecast a single symbol+ */+ async forecastSymbol(+ symbol: string,+ model: string = 'linear',+ horizon: number = 30,+ frequency: string = '1d',+ days: number = 365+ ): Promise<ForecastResponse> {+ const data = await this.fetchSymbolData(symbol, days);+ if (!data) {+ return { success: false, error: `No data available for ${symbol}` };+ }++ return functimeService.fullPipeline(data, model, horizon, frequency);+ }+}++// Export singleton instance+export const portfolioFunctimeService = new PortfolioFunctimeService();