Skip to content

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.

equity trading tab update

tilakpatel22e2fb553fd2c6
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index a2a8932b0..344067ba1 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -904,6 +904,7 @@ set(MCP_SOURCES
src/mcp/McpInit.cpp
src/mcp/SchemaValidator.cpp
src/mcp/ToolRetriever.cpp
+ src/mcp/ToolSelfTest.cpp
src/mcp/TerminalMcpBridge.cpp
# Tool modules
@@ -971,6 +972,7 @@ set(TRADING_SOURCES
src/trading/AccountManager.cpp
src/trading/AccountDataStream.cpp
src/trading/DataStreamManager.cpp
+ src/trading/HistoricalDataService.cpp
src/trading/ExchangeService.cpp
src/trading/ExchangeSession.cpp
src/trading/ExchangeSessionManager.cpp
@@ -1153,6 +1155,7 @@ set(SERVICE_SOURCES
src/services/agents/AgentService_Workflows.cpp
src/services/agents/AgentService_Repositories.cpp
src/services/file_manager/FileManagerService.cpp
+ src/services/notebooks/NotebookLibraryService.cpp
# Wallet (Phase 1 — Solana wallet identity + balance display)
src/services/wallet/Ed25519Verifier.cpp
@@ -1541,10 +1544,11 @@ set(SCREEN_SOURCES
src/screens/dbnomics/DBnomicsSelectionPanel.cpp
src/screens/dbnomics/DBnomicsScreen.cpp
- # Code Editor (Python Colab) — partial-class split: see header comment.
+ # Code Editor (Fincept Notebook) — partial-class split: see header comment.
src/screens/code_editor/CodeEditorScreen.cpp
src/screens/code_editor/CodeEditorScreen_Cells.cpp
src/screens/code_editor/CodeEditorScreen_Navigator.cpp
+ src/screens/code_editor/CodeEditorScreen_Library.cpp
# Excel Spreadsheet
src/screens/excel/ExcelScreen.cpp
@@ -1927,6 +1931,8 @@ set_source_files_properties(
src/screens/code_editor/CodeEditorScreen.cpp
src/screens/code_editor/CodeEditorScreen_Cells.cpp
src/screens/code_editor/CodeEditorScreen_Navigator.cpp
+ src/screens/code_editor/CodeEditorScreen_Library.cpp
+ src/services/notebooks/NotebookLibraryService.cpp
src/screens/crypto_trading/CryptoBottomPanel.cpp
src/screens/crypto_trading/CryptoChart.cpp
src/screens/crypto_trading/CryptoCredentials.cpp
@@ -2397,6 +2403,7 @@ set_source_files_properties(
src/mcp/McpInit.cpp
src/mcp/SchemaValidator.cpp
src/mcp/ToolRetriever.cpp
+ src/mcp/ToolSelfTest.cpp
src/mcp/TerminalMcpBridge.cpp
src/mcp/tools/NavigationTools.cpp
src/mcp/tools/MarketsTools.cpp
@@ -3154,6 +3161,10 @@ add_custom_command(TARGET FinceptTerminal POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_CURRENT_SOURCE_DIR}/resources/charts/vendor"
"$<TARGET_FILE_DIR:FinceptTerminal>/resources/charts/vendor"
+ # Prebuilt Fincept Notebook library (manifest + .ipynb files).
+ COMMAND ${CMAKE_COMMAND} -E copy_directory
+ "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/resources/notebooks"
COMMENT "Copying requirements files to build output..."
)
@@ -3223,6 +3234,9 @@ if(WIN32)
"${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"
DESTINATION "resources" COMPONENT core)
+ # Prebuilt Fincept Notebook library (bundled + seeded into the File Manager).
+ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks/"
+ DESTINATION "resources/notebooks" COMPONENT core)
elseif(APPLE)
# macOS: install the .app bundle
@@ -3232,6 +3246,9 @@ elseif(APPLE)
"${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy1.txt"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/requirements-numpy2.txt"
DESTINATION "FinceptTerminal.app/Contents/Resources/resources" COMPONENT core)
+ # Prebuilt Fincept Notebook library (bundled + seeded into the File Manager).
+ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks/"
+ DESTINATION "FinceptTerminal.app/Contents/Resources/resources/notebooks" COMPONENT core)
else()
# Linux: FHS-compliant layout. Architecture-neutral — works for x86_64
@@ -3270,6 +3287,10 @@ else()
USE_SOURCE_PERMISSIONS COMPONENT scripts
REGEX "(\\.deleted\\.|\\.pytest_cache|\\.benchmarks|__pycache__|\\.pyc$|\\.db$|\\.sqlite$|\\.sqlite3$|\\.bak$|\\.orig$)" EXCLUDE)
+ # Prebuilt Fincept Notebook library (bundled + seeded into the File Manager).
+ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/resources/notebooks/"
+ DESTINATION "share/fincept-terminal/resources/notebooks" COMPONENT core)
+
# App icon (PNG required for hicolor theme; convert .ico → .png in CI)
set(_ICON_PNG "${CMAKE_CURRENT_SOURCE_DIR}/resources/fincept.png")
if(EXISTS "${_ICON_PNG}")
diff --git a/fincept-qt/resources/notebooks/economics_inflation_real_returns.ipynb b/fincept-qt/resources/notebooks/economics_inflation_real_returns.ipynb
new file mode 100644
index 000000000..57314db98
--- /dev/null
+++ b/fincept-qt/resources/notebooks/economics_inflation_real_returns.ipynb
@@ -0,0 +1,226 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Inflation & Real Returns\n",
+ "\n",
+ "**Economics · Beginner · ~12 min · Standard library only**\n",
+ "\n",
+ "Inflation quietly erodes the value of money. This notebook starts from a Consumer Price Index (CPI) series, derives year-over-year inflation, converts nominal investment returns into real (inflation-adjusted) returns using the Fisher relation, shows how the purchasing power of idle cash decays, and uses the Rule of 72 to estimate doubling times.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to compute year-over-year inflation from a CPI index\n",
+ "- The Fisher relation: turning nominal returns into real returns\n",
+ "- How inflation erodes the purchasing power of cash over time\n",
+ "- The Rule of 72 for estimating doubling (and halving) times\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. CPI index and year-over-year inflation\n",
+ "\n",
+ "A **CPI** is an index that tracks the average price level of a basket of goods, anchored to a base year. The **year-over-year inflation rate** between two years is simply the percentage change in the index:\n",
+ "\n",
+ "`inflation_t = CPI_t / CPI_{t-1} − 1`\n",
+ "\n",
+ "Below is an embedded annual CPI series; we compute the inflation rate for each year.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "CPI & inflation"
+ },
+ "outputs": [],
+ "source": [
+ "# Annual end-of-year CPI index (illustrative, base = 100.0 in the first year)\n",
+ "cpi = {\n",
+ " 2015: 100.0,\n",
+ " 2016: 101.3,\n",
+ " 2017: 103.4,\n",
+ " 2018: 105.9,\n",
+ " 2019: 107.8,\n",
+ " 2020: 109.2,\n",
+ " 2021: 114.4,\n",
+ " 2022: 123.6,\n",
+ " 2023: 128.7,\n",
+ " 2024: 132.6,\n",
+ "}\n",
+ "\n",
+ "years = sorted(cpi)\n",
+ "print(\"Year-over-year inflation from the CPI series:\")\n",
+ "print(f\"{'Year':>6}{'CPI':>10}{'Inflation':>12}\")\n",
+ "print('-' * 28)\n",
+ "inflation = {}\n",
+ "for prev, cur in zip(years, years[1:]):\n",
+ " rate = cpi[cur] / cpi[prev] - 1\n",
+ " inflation[cur] = rate\n",
+ " print(f\"{cur:>6}{cpi[cur]:>10.1f}{rate:>11.2%}\")\n",
+ "\n",
+ "# Average (compound annual) inflation over the whole span\n",
+ "n = years[-1] - years[0]\n",
+ "cagr = (cpi[years[-1]] / cpi[years[0]]) ** (1 / n) - 1\n",
+ "print('-' * 28)\n",
+ "print(f\"\\nCumulative price rise {years[0]}-{years[-1]}: {cpi[years[-1]] / cpi[years[0]] - 1:.1%}\")\n",
+ "print(f\"Average annual inflation (CAGR): {cagr:.2%}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Nominal vs real returns (the Fisher relation)\n",
+ "\n",
+ "A **nominal** return is the headline percentage your money grew. The **real** return strips out inflation to show the gain in actual purchasing power. The exact Fisher relation is:\n",
+ "\n",
+ "`1 + real = (1 + nominal) / (1 + inflation)` → `real = (1 + nominal) / (1 + inflation) − 1`\n",
+ "\n",
+ "A common shortcut, `real ≈ nominal − inflation`, is close but slightly overstates the real return; we show both.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Real returns"
+ },
+ "outputs": [],
+ "source": [
+ "def real_return(nominal, inflation):\n",
+ " \"\"\"Exact Fisher relation: real return given a nominal return and inflation.\"\"\"\n",
+ " return (1 + nominal) / (1 + inflation) - 1\n",
+ "\n",
+ "# A few investments and the inflation backdrop each faced\n",
+ "scenarios = [\n",
+ " ('Savings account', 0.015, 0.032),\n",
+ " ('Government bond', 0.035, 0.032),\n",
+ " ('Balanced fund', 0.070, 0.045),\n",
+ " ('Equity portfolio', 0.110, 0.045),\n",
+ " ('High-inflation yr', 0.080, 0.090),\n",
+ "]\n",
+ "\n",
+ "print(\"Nominal vs real returns (exact Fisher relation):\")\n",
+ "print(f\"{'Asset':<20}{'Nominal':>10}{'Inflation':>11}{'Real (exact)':>14}{'Approx':>9}\")\n",
+ "print('-' * 64)\n",
+ "for name, nom, infl in scenarios:\n",
+ " real = real_return(nom, infl)\n",
+ " approx = nom - infl\n",
+ " print(f\"{name:<20}{nom:>10.2%}{infl:>11.2%}{real:>14.2%}{approx:>9.2%}\")\n",
+ "\n",
+ "print(\"\\nNote: when nominal return < inflation, the real return is negative —\")\n",
+ "print(\"your money grows in dollars but buys less than before.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Purchasing power erosion of cash\n",
+ "\n",
+ "Cash earning nothing loses real value every year inflation is positive. If you hold a fixed amount of money, its purchasing power in base-year terms is:\n",
+ "\n",
+ "`real value_t = nominal amount × CPI_base / CPI_t`\n",
+ "\n",
+ "We track $10,000 of idle cash across the same CPI series to see how much buying power it quietly loses.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Purchasing power"
+ },
+ "outputs": [],
+ "source": [
+ "cpi = {\n",
+ " 2015: 100.0, 2016: 101.3, 2017: 103.4, 2018: 105.9, 2019: 107.8,\n",
+ " 2020: 109.2, 2021: 114.4, 2022: 123.6, 2023: 128.7, 2024: 132.6,\n",
+ "}\n",
+ "\n",
+ "years = sorted(cpi)\n",
+ "base = years[0]\n",
+ "cash = 10000.0\n",
+ "\n",
+ "print(f\"Purchasing power of ${cash:,.0f} held as idle cash (in {base} dollars):\")\n",
+ "print(f\"{'Year':>6}{'CPI':>10}{'Real value':>14}{'Buying power lost':>20}\")\n",
+ "print('-' * 50)\n",
+ "for y in years:\n",
+ " real_value = cash * cpi[base] / cpi[y]\n",
+ " lost = cash - real_value\n",
+ " print(f\"{y:>6}{cpi[y]:>10.1f}{real_value:>14,.2f}{lost:>20,.2f}\")\n",
+ "\n",
+ "final_real = cash * cpi[base] / cpi[years[-1]]\n",
+ "print('-' * 50)\n",
+ "print(f\"\\nOver {years[-1] - base} years, ${cash:,.0f} of cash kept only \"\n",
+ " f\"${final_real:,.2f} of {base} purchasing power\")\n",
+ "print(f\"— a real loss of {(1 - final_real / cash):.1%}.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. The Rule of 72\n",
+ "\n",
+ "The **Rule of 72** is a quick mental estimate: divide 72 by a percentage growth rate to approximate the years needed to double. It also works in reverse for inflation — dividing 72 by the inflation rate estimates how long until money's purchasing power halves. We compare the rule against the exact logarithmic answer.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Rule of 72"
+ },
+ "outputs": [],
+ "source": [
+ "import math\n",
+ "\n",
+ "def rule_of_72(rate_pct):\n",
+ " return 72 / rate_pct\n",
+ "\n",
+ "def exact_doubling(rate_pct):\n",
+ " return math.log(2) / math.log(1 + rate_pct / 100)\n",
+ "\n",
+ "print(\"Doubling time: Rule of 72 vs exact\")\n",
+ "print(f\"{'Rate':>6}{'Rule of 72':>14}{'Exact (yrs)':>14}{'Error':>10}\")\n",
+ "print('-' * 44)\n",
+ "for rate in [2, 3, 4, 6, 8, 10, 12]:\n",
+ " approx = rule_of_72(rate)\n",
+ " exact = exact_doubling(rate)\n",
+ " print(f\"{rate:>5}%{approx:>14.1f}{exact:>14.1f}{approx - exact:>+10.2f}\")\n",
+ "\n",
+ "# Applied to inflation: how fast does purchasing power halve?\n",
+ "print(\"\\nApplied to inflation — years for prices to double / money to halve:\")\n",
+ "print(f\"{'Inflation':>10}{'Rule of 72':>14}{'Exact (yrs)':>14}\")\n",
+ "print('-' * 38)\n",
+ "for infl in [2, 3, 5, 7]:\n",
+ " print(f\"{infl:>9}%{rule_of_72(infl):>14.1f}{exact_doubling(infl):>14.1f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/economics_yield_curve.ipynb b/fincept-qt/resources/notebooks/economics_yield_curve.ipynb
new file mode 100644
index 000000000..0a303d73e
--- /dev/null
+++ b/fincept-qt/resources/notebooks/economics_yield_curve.ipynb
@@ -0,0 +1,225 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Yield Curve & Recession Signal\n",
+ "\n",
+ "**Economics · Hard · ~30 min · pandas + numpy**\n",
+ "\n",
+ "The shape of the U.S. Treasury yield curve is one of the most-watched macro indicators. When short-term yields rise above long-term yields (an *inversion*), it has historically preceded recessions. In this notebook we build curves for a normal day and an inverted day, interpolate yields at any maturity, and compute the classic recession spreads.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- Build a pandas DataFrame of Treasury yields across tenors (3M to 30Y)\n",
+ "- Interpolate yields at off-grid maturities with `np.interp`\n",
+ "- Compute the 10y-2y and 10y-3m spreads and classify the curve shape\n",
+ "- Explain why a negative 10y-2y spread is read as a recession signal\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The yield-curve data\n",
+ "\n",
+ "We embed two real-world-shaped snapshots of constant-maturity Treasury (CMT) yields, quoted in percent. The **2021-06-30** curve is upward-sloping (*normal*): you get paid more to lend for longer. The **2023-07-03** curve is *inverted*: the 3M bill out-yields the 10Y note — a textbook recession warning.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Build curve DataFrame"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "# Tenors in years, and CMT yields (%) for two dates.\n",
+ "TENORS = {\"3M\": 0.25, \"6M\": 0.5, \"1Y\": 1, \"2Y\": 2, \"3Y\": 3,\n",
+ " \"5Y\": 5, \"7Y\": 7, \"10Y\": 10, \"20Y\": 20, \"30Y\": 30}\n",
+ "YIELDS = {\n",
+ " \"2021-06-30\": [0.05, 0.06, 0.07, 0.25, 0.46, 0.87, 1.21, 1.45, 2.00, 2.06], # normal\n",
+ " \"2023-07-03\": [5.43, 5.47, 5.40, 4.94, 4.66, 4.36, 4.23, 3.86, 4.16, 3.91], # inverted\n",
+ "}\n",
+ "\n",
+ "df = pd.DataFrame(YIELDS, index=pd.Index(TENORS.keys(), name=\"Tenor\"))\n",
+ "df.insert(0, \"Maturity(yr)\", list(TENORS.values()))\n",
+ "\n",
+ "print(\"U.S. Treasury constant-maturity yields (%)\")\n",
+ "print(\"=\" * 48)\n",
+ "print(df.to_string())\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Interpolating yields at any maturity\n",
+ "\n",
+ "The market only quotes a handful of tenors, but you often need a yield at an *off-grid* point — say a bond with 4 years left, or an 18-month liability. Because the curve is smooth, simple **linear interpolation** between the two neighbouring quotes is a reasonable first approximation. `np.interp(x, xp, fp)` does exactly this: given the grid maturities `xp` and their yields `fp`, it returns the yield at each requested maturity `x`.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Interpolate off-grid"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "TENORS = {\"3M\": 0.25, \"6M\": 0.5, \"1Y\": 1, \"2Y\": 2, \"3Y\": 3,\n",
+ " \"5Y\": 5, \"7Y\": 7, \"10Y\": 10, \"20Y\": 20, \"30Y\": 30}\n",
+ "YIELDS = {\n",
+ " \"2021-06-30\": [0.05, 0.06, 0.07, 0.25, 0.46, 0.87, 1.21, 1.45, 2.00, 2.06],\n",
+ " \"2023-07-03\": [5.43, 5.47, 5.40, 4.94, 4.66, 4.36, 4.23, 3.86, 4.16, 3.91],\n",
+ "}\n",
+ "\n",
+ "xp = np.array(list(TENORS.values())) # grid maturities in years\n",
+ "targets = [0.75, 1.5, 4.0, 8.0, 15.0, 25.0] # off-grid maturities we want\n",
+ "\n",
+ "rows = []\n",
+ "for date, ys in YIELDS.items():\n",
+ " fp = np.array(ys)\n",
+ " interp = np.interp(targets, xp, fp)\n",
+ " for m, y in zip(targets, interp):\n",
+ " rows.append({\"Date\": date, \"Maturity(yr)\": m, \"Interp yield (%)\": round(float(y), 3)})\n",
+ "\n",
+ "out = pd.DataFrame(rows).pivot(index=\"Maturity(yr)\", columns=\"Date\", values=\"Interp yield (%)\")\n",
+ "print(\"Linearly interpolated yields at off-grid maturities\")\n",
+ "print(\"=\" * 52)\n",
+ "print(out.to_string())\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. The recession spreads & curve shape\n",
+ "\n",
+ "Two spreads matter most:\n",
+ "\n",
+ "- **10y − 2y**: the classic slope. It has gone negative before *every* U.S. recession since the 1970s.\n",
+ "- **10y − 3m**: favoured by the Fed's own research as the cleanest predictor.\n",
+ "\n",
+ "We classify the overall shape from the 10y−2y spread: clearly positive → **normal**, near zero → **flat**, negative → **inverted**.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Spreads & shape"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "TENORS = [\"3M\", \"6M\", \"1Y\", \"2Y\", \"3Y\", \"5Y\", \"7Y\", \"10Y\", \"20Y\", \"30Y\"]\n",
+ "YIELDS = {\n",
+ " \"2021-06-30\": [0.05, 0.06, 0.07, 0.25, 0.46, 0.87, 1.21, 1.45, 2.00, 2.06],\n",
+ " \"2023-07-03\": [5.43, 5.47, 5.40, 4.94, 4.66, 4.36, 4.23, 3.86, 4.16, 3.91],\n",
+ "}\n",
+ "df = pd.DataFrame(YIELDS, index=TENORS)\n",
+ "\n",
+ "def classify(spread_10_2):\n",
+ " if spread_10_2 < -0.10:\n",
+ " return \"INVERTED\"\n",
+ " if spread_10_2 <= 0.25:\n",
+ " return \"FLAT\"\n",
+ " return \"NORMAL\"\n",
+ "\n",
+ "rows = []\n",
+ "for date in df.columns:\n",
+ " s = df[date]\n",
+ " sp_10_2 = s[\"10Y\"] - s[\"2Y\"]\n",
+ " sp_10_3m = s[\"10Y\"] - s[\"3M\"]\n",
+ " rows.append({\n",
+ " \"Date\": date,\n",
+ " \"2Y (%)\": s[\"2Y\"], \"10Y (%)\": s[\"10Y\"],\n",
+ " \"10y-2y (bp)\": round(sp_10_2 * 100, 1),\n",
+ " \"10y-3m (bp)\": round(sp_10_3m * 100, 1),\n",
+ " \"Shape\": classify(sp_10_2),\n",
+ " \"Recession signal\": \"YES\" if sp_10_2 < 0 else \"no\",\n",
+ " })\n",
+ "\n",
+ "summary = pd.DataFrame(rows).set_index(\"Date\")\n",
+ "print(\"Yield-curve spreads and classification\")\n",
+ "print(\"=\" * 64)\n",
+ "print(summary.to_string())\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Reading the signal\n",
+ "\n",
+ "Compare the two dates side by side. On the normal day the slope is steeply positive (the 10Y yields ~120bp more than the 2Y); on the inverted day the 2Y *out-yields* the 10Y by over 100bp. We print a tenor-by-tenor difference so you can see where the inversion bites hardest.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Compare two dates"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "TENORS = [\"3M\", \"6M\", \"1Y\", \"2Y\", \"3Y\", \"5Y\", \"7Y\", \"10Y\", \"20Y\", \"30Y\"]\n",
+ "MAT = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]\n",
+ "YIELDS = {\n",
+ " \"2021-06-30\": [0.05, 0.06, 0.07, 0.25, 0.46, 0.87, 1.21, 1.45, 2.00, 2.06],\n",
+ " \"2023-07-03\": [5.43, 5.47, 5.40, 4.94, 4.66, 4.36, 4.23, 3.86, 4.16, 3.91],\n",
+ "}\n",
+ "df = pd.DataFrame(YIELDS, index=TENORS)\n",
+ "df[\"Change (bp)\"] = ((df[\"2023-07-03\"] - df[\"2021-06-30\"]) * 100).round(0).astype(int)\n",
+ "\n",
+ "print(\"Normal vs inverted curve, tenor by tenor\")\n",
+ "print(\"=\" * 56)\n",
+ "print(df.to_string())\n",
+ "print()\n",
+ "\n",
+ "# Slope of each curve: yield(30Y) - yield(3M)\n",
+ "for date in [\"2021-06-30\", \"2023-07-03\"]:\n",
+ " slope = df.loc[\"30Y\", date] - df.loc[\"3M\", date]\n",
+ " direction = \"upward (normal)\" if slope > 0 else \"downward (inverted)\"\n",
+ " print(f\"{date}: 30Y-3M slope = {slope:+.2f} pts -> {direction}\")\n",
+ "\n",
+ "print()\n",
+ "print(\"Takeaway: a negative 10y-2y spread means investors expect the Fed to\")\n",
+ "print(\"cut rates in the future (weaker growth), so they lock in long yields now —\")\n",
+ "print(\"the curve inverts. Historically this has led recessions by ~6-18 months.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
+ "language_info": {"name": "python"}
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/finance_financial_ratios.ipynb b/fincept-qt/resources/notebooks/finance_financial_ratios.ipynb
new file mode 100644
index 000000000..a3b4f7596
--- /dev/null
+++ b/fincept-qt/resources/notebooks/finance_financial_ratios.ipynb
@@ -0,0 +1,371 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Financial Statement Ratios\n",
+ "\n",
+ "**Finance · Intermediate · ~18 min · pandas + numpy**\n",
+ "\n",
+ "Ratios turn raw financial statements into comparable signals about a company's health. We build a compact income statement and balance sheet for a fictional company, *Fincept Demo Corp*, then compute the four classic ratio families — liquidity, profitability, leverage, and efficiency — and interpret each one.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to represent an income statement and balance sheet as pandas structures\n",
+ "- Liquidity ratios (current, quick) and what they say about short-term solvency\n",
+ "- Profitability (margins, ROE, ROA) and leverage (debt-to-equity, interest coverage)\n",
+ "- Efficiency via asset turnover, and how to read a tidy ratio table\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The financial statements\n",
+ "\n",
+ "We start with a small, self-contained dictionary of figures (all in $ thousands) for *Fincept Demo Corp*. The income statement flows from revenue down to net income; the balance sheet obeys the identity **Assets = Liabilities + Equity**. We load it into pandas Series so later cells can slice it cleanly. Each code cell re-embeds this dictionary so it can run on its own.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Statements"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "# Fincept Demo Corp — all figures in $ thousands\n",
+ "FIN = {\n",
+ " # Income statement\n",
+ " 'revenue': 12000.0,\n",
+ " 'cogs': 7200.0,\n",
+ " 'operating_expenses': 2400.0,\n",
+ " 'interest_expense': 300.0,\n",
+ " 'taxes': 540.0,\n",
+ " # Balance sheet — current assets\n",
+ " 'cash': 1500.0,\n",
+ " 'accounts_receivable': 1800.0,\n",
+ " 'inventory': 2200.0,\n",
+ " # Balance sheet — non-current assets\n",
+ " 'net_ppe': 6500.0,\n",
+ " # Balance sheet — liabilities\n",
+ " 'accounts_payable': 1400.0,\n",
+ " 'short_term_debt': 900.0,\n",
+ " 'long_term_debt': 3600.0,\n",
+ " # Balance sheet — equity\n",
+ " 'common_equity': 6600.0,\n",
+ "}\n",
+ "\n",
+ "# Build the income statement as a derived Series\n",
+ "gross_profit = FIN['revenue'] - FIN['cogs']\n",
+ "operating_income = gross_profit - FIN['operating_expenses']\n",
+ "pretax_income = operating_income - FIN['interest_expense']\n",
+ "net_income = pretax_income - FIN['taxes']\n",
+ "income_statement = pd.Series({\n",
+ " 'Revenue': FIN['revenue'],\n",
+ " 'COGS': -FIN['cogs'],\n",
+ " 'Gross profit': gross_profit,\n",
+ " 'Operating expenses': -FIN['operating_expenses'],\n",
+ " 'Operating income (EBIT)': operating_income,\n",
+ " 'Interest expense': -FIN['interest_expense'],\n",
+ " 'Pretax income': pretax_income,\n",
+ " 'Taxes': -FIN['taxes'],\n",
+ " 'Net income': net_income,\n",
+ "}, name='$000s')\n",
+ "\n",
+ "current_assets = FIN['cash'] + FIN['accounts_receivable'] + FIN['inventory']\n",
+ "total_assets = current_assets + FIN['net_ppe']\n",
+ "current_liabilities = FIN['accounts_payable'] + FIN['short_term_debt']\n",
+ "total_liabilities = current_liabilities + FIN['long_term_debt']\n",
+ "balance_sheet = pd.Series({\n",
+ " 'Cash': FIN['cash'],\n",
+ " 'Accounts receivable': FIN['accounts_receivable'],\n",
+ " 'Inventory': FIN['inventory'],\n",
+ " 'Total current assets': current_assets,\n",
+ " 'Net PP&E': FIN['net_ppe'],\n",
+ " 'TOTAL ASSETS': total_assets,\n",
+ " 'Current liabilities': current_liabilities,\n",
+ " 'Long-term debt': FIN['long_term_debt'],\n",
+ " 'Total liabilities': total_liabilities,\n",
+ " 'Common equity': FIN['common_equity'],\n",
+ " 'LIAB + EQUITY': total_liabilities + FIN['common_equity'],\n",
+ "}, name='$000s')\n",
+ "\n",
+ "print(\"FINCEPT DEMO CORP — Income Statement ($000s)\")\n",
+ "print(income_statement.round(1).to_string())\n",
+ "print()\n",
+ "print(\"FINCEPT DEMO CORP — Balance Sheet ($000s)\")\n",
+ "print(balance_sheet.round(1).to_string())\n",
+ "print()\n",
+ "print(f\"Balance check: Assets {total_assets:,.0f} == Liab+Equity {total_liabilities + FIN['common_equity']:,.0f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Liquidity ratios\n",
+ "\n",
+ "Liquidity ratios ask: *can the company cover its short-term bills?*\n",
+ "\n",
+ "- **Current ratio** = current assets / current liabilities. Above 1.0 means current assets exceed current obligations.\n",
+ "- **Quick (acid-test) ratio** = (current assets − inventory) / current liabilities. It strips out inventory, the least-liquid current asset, for a stricter test.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Liquidity"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "FIN = {\n",
+ " 'revenue': 12000.0, 'cogs': 7200.0, 'operating_expenses': 2400.0,\n",
+ " 'interest_expense': 300.0, 'taxes': 540.0,\n",
+ " 'cash': 1500.0, 'accounts_receivable': 1800.0, 'inventory': 2200.0,\n",
+ " 'net_ppe': 6500.0, 'accounts_payable': 1400.0, 'short_term_debt': 900.0,\n",
+ " 'long_term_debt': 3600.0, 'common_equity': 6600.0,\n",
+ "}\n",
+ "\n",
+ "current_assets = FIN['cash'] + FIN['accounts_receivable'] + FIN['inventory']\n",
+ "current_liabilities = FIN['accounts_payable'] + FIN['short_term_debt']\n",
+ "\n",
+ "current_ratio = current_assets / current_liabilities\n",
+ "quick_ratio = (current_assets - FIN['inventory']) / current_liabilities\n",
+ "\n",
+ "liquidity = pd.DataFrame({\n",
+ " 'Ratio': ['Current ratio', 'Quick ratio'],\n",
+ " 'Value': [current_ratio, quick_ratio],\n",
+ " 'Formula': ['CA / CL', '(CA - Inventory) / CL'],\n",
+ " 'Interpretation': [\n",
+ " 'Comfortable short-term cushion (>1.5 is healthy)',\n",
+ " 'Can meet current bills without selling inventory',\n",
+ " ],\n",
+ "})\n",
+ "liquidity['Value'] = liquidity['Value'].round(2)\n",
+ "print(\"LIQUIDITY RATIOS — Fincept Demo Corp\")\n",
+ "print(liquidity.to_string(index=False))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Profitability ratios\n",
+ "\n",
+ "Profitability ratios measure how much of each revenue dollar (or each dollar of capital) becomes profit.\n",
+ "\n",
+ "- **Gross / operating / net margin** = gross profit, EBIT, or net income divided by revenue.\n",
+ "- **ROA** = net income / total assets — return generated per dollar of assets.\n",
+ "- **ROE** = net income / common equity — return to shareholders.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Profitability"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "FIN = {\n",
+ " 'revenue': 12000.0, 'cogs': 7200.0, 'operating_expenses': 2400.0,\n",
+ " 'interest_expense': 300.0, 'taxes': 540.0,\n",
+ " 'cash': 1500.0, 'accounts_receivable': 1800.0, 'inventory': 2200.0,\n",
+ " 'net_ppe': 6500.0, 'accounts_payable': 1400.0, 'short_term_debt': 900.0,\n",
+ " 'long_term_debt': 3600.0, 'common_equity': 6600.0,\n",
+ "}\n",
+ "\n",
+ "gross_profit = FIN['revenue'] - FIN['cogs']\n",
+ "operating_income = gross_profit - FIN['operating_expenses']\n",
+ "pretax_income = operating_income - FIN['interest_expense']\n",
+ "net_income = pretax_income - FIN['taxes']\n",
+ "total_assets = FIN['cash'] + FIN['accounts_receivable'] + FIN['inventory'] + FIN['net_ppe']\n",
+ "\n",
+ "profitability = pd.DataFrame({\n",
+ " 'Ratio': ['Gross margin', 'Operating margin', 'Net margin', 'Return on assets (ROA)', 'Return on equity (ROE)'],\n",
+ " 'Value': [\n",
+ " gross_profit / FIN['revenue'],\n",
+ " operating_income / FIN['revenue'],\n",
+ " net_income / FIN['revenue'],\n",
+ " net_income / total_assets,\n",
+ " net_income / FIN['common_equity'],\n",
+ " ],\n",
+ " 'Interpretation': [\n",
+ " 'Share of revenue left after direct costs',\n",
+ " 'Profitability of core operations (pre-interest/tax)',\n",
+ " 'Bottom-line profit per revenue dollar',\n",
+ " 'Profit generated per dollar of assets',\n",
+ " 'Profit generated per dollar of shareholder equity',\n",
+ " ],\n",
+ "})\n",
+ "profitability['Value %'] = (profitability['Value'] * 100).round(1)\n",
+ "profitability = profitability[['Ratio', 'Value %', 'Interpretation']]\n",
+ "print(\"PROFITABILITY RATIOS — Fincept Demo Corp (all shown as %)\")\n",
+ "print(profitability.to_string(index=False))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Leverage & efficiency ratios\n",
+ "\n",
+ "**Leverage** ratios gauge how much the company relies on debt, and how easily it services it:\n",
+ "\n",
+ "- **Debt-to-equity** = total debt / common equity.\n",
+ "- **Interest coverage** = EBIT / interest expense — how many times operating profit covers interest.\n",
+ "\n",
+ "**Efficiency** ratios show how hard the asset base works:\n",
+ "\n",
+ "- **Asset turnover** = revenue / total assets — revenue produced per dollar of assets.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Leverage & efficiency"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "FIN = {\n",
+ " 'revenue': 12000.0, 'cogs': 7200.0, 'operating_expenses': 2400.0,\n",
+ " 'interest_expense': 300.0, 'taxes': 540.0,\n",
+ " 'cash': 1500.0, 'accounts_receivable': 1800.0, 'inventory': 2200.0,\n",
+ " 'net_ppe': 6500.0, 'accounts_payable': 1400.0, 'short_term_debt': 900.0,\n",
+ " 'long_term_debt': 3600.0, 'common_equity': 6600.0,\n",
+ "}\n",
+ "\n",
+ "gross_profit = FIN['revenue'] - FIN['cogs']\n",
+ "operating_income = gross_profit - FIN['operating_expenses'] # EBIT\n",
+ "total_assets = FIN['cash'] + FIN['accounts_receivable'] + FIN['inventory'] + FIN['net_ppe']\n",
+ "total_debt = FIN['short_term_debt'] + FIN['long_term_debt']\n",
+ "\n",
+ "debt_to_equity = total_debt / FIN['common_equity']\n",
+ "interest_coverage = operating_income / FIN['interest_expense']\n",
+ "asset_turnover = FIN['revenue'] / total_assets\n",
+ "\n",
+ "lev_eff = pd.DataFrame({\n",
+ " 'Family': ['Leverage', 'Leverage', 'Efficiency'],\n",
+ " 'Ratio': ['Debt-to-equity', 'Interest coverage', 'Asset turnover'],\n",
+ " 'Value': [debt_to_equity, interest_coverage, asset_turnover],\n",
+ " 'Unit': ['x', 'x', 'x'],\n",
+ " 'Interpretation': [\n",
+ " 'Debt is below equity — moderate leverage',\n",
+ " 'EBIT covers interest many times over — low default risk',\n",
+ " 'Each $1 of assets generates this much revenue',\n",
+ " ],\n",
+ "})\n",
+ "lev_eff['Value'] = lev_eff['Value'].round(2)\n",
+ "print(\"LEVERAGE & EFFICIENCY RATIOS — Fincept Demo Corp\")\n",
+ "print(lev_eff.to_string(index=False))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Full ratio summary\n",
+ "\n",
+ "Finally, we assemble every ratio into one tidy DataFrame grouped by family — the kind of one-glance scorecard an analyst keeps next to the statements.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Summary table"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "FIN = {\n",
+ " 'revenue': 12000.0, 'cogs': 7200.0, 'operating_expenses': 2400.0,\n",
+ " 'interest_expense': 300.0, 'taxes': 540.0,\n",
+ " 'cash': 1500.0, 'accounts_receivable': 1800.0, 'inventory': 2200.0,\n",
+ " 'net_ppe': 6500.0, 'accounts_payable': 1400.0, 'short_term_debt': 900.0,\n",
+ " 'long_term_debt': 3600.0, 'common_equity': 6600.0,\n",
+ "}\n",
+ "\n",
+ "gross_profit = FIN['revenue'] - FIN['cogs']\n",
+ "operating_income = gross_profit - FIN['operating_expenses']\n",
+ "pretax_income = operating_income - FIN['interest_expense']\n",
+ "net_income = pretax_income - FIN['taxes']\n",
+ "current_assets = FIN['cash'] + FIN['accounts_receivable'] + FIN['inventory']\n",
+ "total_assets = current_assets + FIN['net_ppe']\n",
+ "current_liabilities = FIN['accounts_payable'] + FIN['short_term_debt']\n",
+ "total_debt = FIN['short_term_debt'] + FIN['long_term_debt']\n",
+ "\n",
+ "rows = [\n",
+ " ('Liquidity', 'Current ratio', current_assets / current_liabilities, 'x'),\n",
+ " ('Liquidity', 'Quick ratio', (current_assets - FIN['inventory']) / current_liabilities, 'x'),\n",
+ " ('Profitability', 'Gross margin', gross_profit / FIN['revenue'] * 100, '%'),\n",
+ " ('Profitability', 'Operating margin', operating_income / FIN['revenue'] * 100, '%'),\n",
+ " ('Profitability', 'Net margin', net_income / FIN['revenue'] * 100, '%'),\n",
+ " ('Profitability', 'ROA', net_income / total_assets * 100, '%'),\n",
+ " ('Profitability', 'ROE', net_income / FIN['common_equity'] * 100, '%'),\n",
+ " ('Leverage', 'Debt-to-equity', total_debt / FIN['common_equity'], 'x'),\n",
+ " ('Leverage', 'Interest coverage', operating_income / FIN['interest_expense'], 'x'),\n",
+ " ('Efficiency', 'Asset turnover', FIN['revenue'] / total_assets, 'x'),\n",
+ "]\n",
+ "summary = pd.DataFrame(rows, columns=['Family', 'Ratio', 'Value', 'Unit'])\n",
+ "summary['Value'] = summary['Value'].round(2)\n",
+ "print(\"FINCEPT DEMO CORP — RATIO SCORECARD\")\n",
+ "print(summary.to_string(index=False))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/finance_time_value_of_money.ipynb b/fincept-qt/resources/notebooks/finance_time_value_of_money.ipynb
new file mode 100644
index 000000000..bb386b2fc
--- /dev/null
+++ b/fincept-qt/resources/notebooks/finance_time_value_of_money.ipynb
@@ -0,0 +1,260 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Time Value of Money\n",
+ "\n",
+ "**Finance · Beginner · ~10 min · Standard library only**\n",
+ "\n",
+ "Money today is worth more than the same money tomorrow. This notebook walks through the core building blocks of valuation: discounting and compounding a single cash flow, valuing a stream of cash flows with NPV, solving for the internal rate of return (IRR), and breaking a loan into its amortization schedule.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- Present value (PV) and future value (FV), and how compounding frequency changes the answer\n",
+ "- Net present value (NPV) of a cash-flow stream at a given discount rate\n",
+ "- How to solve for IRR numerically with the bisection method\n",
+ "- How to build a loan amortization schedule\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Present value & future value\n",
+ "\n",
+ "A single cash flow `C` grows to a **future value** `FV = C · (1 + r/m)^(m·t)` and a future amount discounts back to a **present value** `PV = C / (1 + r/m)^(m·t)`, where `r` is the annual rate, `m` is the compounding frequency per year, and `t` is years.\n",
+ "\n",
+ "The table below shows how $1,000 grows over time and how the discount rate changes today's value of a fixed future amount.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "PV / FV tables"
+ },
+ "outputs": [],
+ "source": [
+ "import math\n",
+ "\n",
+ "def future_value(pv, annual_rate, years, m=1):\n",
+ " \"\"\"Future value of a lump sum with m compounding periods per year.\"\"\"\n",
+ " return pv * (1 + annual_rate / m) ** (m * years)\n",
+ "\n",
+ "def present_value(fv, annual_rate, years, m=1):\n",
+ " \"\"\"Present value of a future lump sum.\"\"\"\n",
+ " return fv / (1 + annual_rate / m) ** (m * years)\n",
+ "\n",
+ "# --- Worked example -------------------------------------------------\n",
+ "principal = 1000.0\n",
+ "rate = 0.06 # 6% annual\n",
+ "years = 5\n",
+ "fv_annual = future_value(principal, rate, years, m=1)\n",
+ "print(f\"Invest ${principal:,.2f} at {rate:.1%} for {years} years (annual compounding):\")\n",
+ "print(f\" Future value = ${fv_annual:,.2f}\")\n",
+ "print(f\" Check PV = ${present_value(fv_annual, rate, years, m=1):,.2f} (should return the principal)\")\n",
+ "\n",
+ "# --- Compounding frequency matters ----------------------------------\n",
+ "print(\"\\nEffect of compounding frequency ($1,000 at 6% for 5 years):\")\n",
+ "print(f\"{'Frequency':<14}{'m':>4}{'Future value':>16}\")\n",
+ "print('-' * 34)\n",
+ "for label, m in [('Annual', 1), ('Semiannual', 2), ('Quarterly', 4), ('Monthly', 12), ('Daily', 365)]:\n",
+ " print(f\"{label:<14}{m:>4}{future_value(principal, rate, years, m):>16,.2f}\")\n",
+ "\n",
+ "# --- FV grid over several years and rates ---------------------------\n",
+ "rates = [0.03, 0.05, 0.07, 0.10]\n",
+ "horizons = [1, 3, 5, 10, 20]\n",
+ "print(\"\\nFuture value of $1,000 (annual compounding):\")\n",
+ "header = f\"{'Years':>6}\" + ''.join(f\"{r:>12.0%}\" for r in rates)\n",
+ "print(header)\n",
+ "print('-' * len(header))\n",
+ "for t in horizons:\n",
+ " row = f\"{t:>6}\" + ''.join(f\"{future_value(principal, r, t):>12,.0f}\" for r in rates)\n",
+ " print(row)\n",
+ "\n",
+ "# --- PV of a fixed future amount at several discount rates ----------\n",
+ "target = 10000.0\n",
+ "print(f\"\\nPresent value of ${target:,.0f} received in 5 years:\")\n",
+ "print(f\"{'Discount rate':>14}{'Present value':>16}\")\n",
+ "print('-' * 30)\n",
+ "for r in rates:\n",
+ " print(f\"{r:>14.0%}{present_value(target, r, 5):>16,.2f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Net present value of a cash-flow stream\n",
+ "\n",
+ "A project's **NPV** discounts every future cash flow back to today and sums them:\n",
+ "\n",
+ "`NPV = Σ Cₜ / (1 + r)ᵗ` for t = 0, 1, 2, …\n",
+ "\n",
+ "Year 0 is the up-front outlay (a negative number). A positive NPV means the project adds value at the chosen discount rate. Below we value a project with an initial $10,000 investment followed by five years of inflows, and tabulate how NPV falls as the discount rate rises.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Compute NPV"
+ },
+ "outputs": [],
+ "source": [
+ "def npv(rate, cashflows):\n",
+ " \"\"\"NPV of cashflows[0..n] where index = period (0 = today).\"\"\"\n",
+ " return sum(cf / (1 + rate) ** t for t, cf in enumerate(cashflows))\n",
+ "\n",
+ "# Initial outlay then five annual inflows\n",
+ "cashflows = [-10000, 2500, 3000, 3500, 4000, 4500]\n",
+ "discount_rate = 0.08\n",
+ "\n",
+ "print(\"Project cash flows:\")\n",
+ "print(f\"{'Year':>5}{'Cash flow':>14}{'Discount factor':>18}{'Present value':>16}\")\n",
+ "print('-' * 53)\n",
+ "for t, cf in enumerate(cashflows):\n",
+ " df = 1 / (1 + discount_rate) ** t\n",
+ " print(f\"{t:>5}{cf:>14,.2f}{df:>18.4f}{cf * df:>16,.2f}\")\n",
+ "print('-' * 53)\n",
+ "print(f\"{'NPV at ' + format(discount_rate, '.0%'):>23}{'':>18}{npv(discount_rate, cashflows):>16,.2f}\")\n",
+ "\n",
+ "# NPV at a range of discount rates\n",
+ "print(\"\\nNPV sensitivity to the discount rate:\")\n",
+ "print(f\"{'Discount rate':>14}{'NPV':>16}\")\n",
+ "print('-' * 30)\n",
+ "for r in [0.00, 0.04, 0.08, 0.12, 0.16, 0.20]:\n",
+ " print(f\"{r:>14.0%}{npv(r, cashflows):>16,.2f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Internal rate of return (IRR) by bisection\n",
+ "\n",
+ "The **IRR** is the discount rate that makes NPV exactly zero — the project's break-even rate of return. There is no closed-form solution in general, so we find it numerically. The **bisection method** brackets the IRR between a low and high rate (where NPV changes sign) and repeatedly halves the interval until it converges.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Solve IRR"
+ },
+ "outputs": [],
+ "source": [
+ "def npv(rate, cashflows):\n",
+ " return sum(cf / (1 + rate) ** t for t, cf in enumerate(cashflows))\n",
+ "\n",
+ "def irr_bisection(cashflows, low=-0.9, high=1.0, tol=1e-9, max_iter=200):\n",
+ " \"\"\"Find IRR via bisection. Requires NPV(low) and NPV(high) to differ in sign.\"\"\"\n",
+ " f_low, f_high = npv(low, cashflows), npv(high, cashflows)\n",
+ " if f_low * f_high > 0:\n",
+ " raise ValueError(\"NPV does not change sign on the bracket; widen [low, high].\")\n",
+ " for _ in range(max_iter):\n",
+ " mid = (low + high) / 2\n",
+ " f_mid = npv(mid, cashflows)\n",
+ " if abs(f_mid) < tol:\n",
+ " return mid\n",
+ " if f_low * f_mid < 0:\n",
+ " high, f_high = mid, f_mid\n",
+ " else:\n",
+ " low, f_low = mid, f_mid\n",
+ " return (low + high) / 2\n",
+ "\n",
+ "# Same project as before (re-embedded so this cell stands alone)\n",
+ "cashflows = [-10000, 2500, 3000, 3500, 4000, 4500]\n",
+ "\n",
+ "irr = irr_bisection(cashflows)\n",
+ "print(f\"IRR = {irr:.6f} ({irr:.2%})\")\n",
+ "print(f\"Verification: NPV at the IRR = {npv(irr, cashflows):,.6f} (should be ~0)\")\n",
+ "\n",
+ "print(\"\\nDecision rule: accept the project when IRR exceeds your cost of capital.\")\n",
+ "for hurdle in [0.06, 0.08, 0.12, 0.15]:\n",
+ " verdict = 'ACCEPT' if irr > hurdle else 'REJECT'\n",
+ " print(f\" Hurdle rate {hurdle:>5.0%} -> {verdict}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Loan amortization schedule\n",
+ "\n",
+ "A fully-amortizing loan is repaid in equal periodic payments. Each payment covers the period's interest first, and whatever is left reduces the principal. The level payment is:\n",
+ "\n",
+ "`PMT = P · i / (1 − (1 + i)^(−n))`\n",
+ "\n",
+ "where `P` is the principal, `i` is the per-period rate, and `n` is the number of payments. As the balance shrinks, the interest portion falls and the principal portion grows.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Amortization schedule"
+ },
+ "outputs": [],
+ "source": [
+ "def level_payment(principal, annual_rate, years, periods_per_year=12):\n",
+ " \"\"\"Equal periodic payment for a fully-amortizing loan.\"\"\"\n",
+ " i = annual_rate / periods_per_year\n",
+ " n = years * periods_per_year\n",
+ " if i == 0:\n",
+ " return principal / n\n",
+ " return principal * i / (1 - (1 + i) ** -n)\n",
+ "\n",
+ "# A $25,000 loan at 7.5% APR over 2 years, monthly payments\n",
+ "principal = 25000.0\n",
+ "annual_rate = 0.075\n",
+ "years = 2\n",
+ "ppy = 12\n",
+ "i = annual_rate / ppy\n",
+ "n = years * ppy\n",
+ "pmt = level_payment(principal, annual_rate, years, ppy)\n",
+ "\n",
+ "print(f\"Loan: ${principal:,.2f} at {annual_rate:.2%} APR, {n} monthly payments\")\n",
+ "print(f\"Level monthly payment = ${pmt:,.2f}\\n\")\n",
+ "\n",
+ "print(f\"{'Pmt':>4}{'Payment':>12}{'Interest':>12}{'Principal':>12}{'Balance':>14}\")\n",
+ "print('-' * 54)\n",
+ "balance = principal\n",
+ "total_interest = 0.0\n",
+ "for k in range(1, n + 1):\n",
+ " interest = balance * i\n",
+ " principal_paid = pmt - interest\n",
+ " balance -= principal_paid\n",
+ " if k == n: # absorb tiny rounding drift in the final payment\n",
+ " principal_paid += balance\n",
+ " balance = 0.0\n",
+ " total_interest += interest\n",
+ " print(f\"{k:>4}{pmt:>12,.2f}{interest:>12,.2f}{principal_paid:>12,.2f}{balance:>14,.2f}\")\n",
+ "print('-' * 54)\n",
+ "print(f\"Total paid = ${pmt * n:,.2f}\")\n",
+ "print(f\"Total interest = ${total_interest:,.2f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/investing_dividend_compounding.ipynb b/fincept-qt/resources/notebooks/investing_dividend_compounding.ipynb
new file mode 100644
index 000000000..d5c29341d
--- /dev/null
+++ b/fincept-qt/resources/notebooks/investing_dividend_compounding.ipynb
@@ -0,0 +1,227 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Dividend Growth & DRIP Compounding\n",
+ "\n",
+ "**Investing · Intermediate · ~18 min · pandas + numpy**\n",
+ "\n",
+ "A dividend reinvestment plan (DRIP) automatically uses every dividend payment to buy more shares. Those extra shares then pay their own dividends, which buy still more shares — the snowball that powers long-run equity returns. This notebook models a single dividend-growth stock over 25 years and measures exactly how much the 'reinvest' decision is worth versus taking the cash.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to project shares, price, and dividend-per-share forward year by year\n",
+ "- How to build the full DRIP table in pandas and read yield-on-cost\n",
+ "- The size of the compounding gap between reinvesting and spending dividends\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The inputs\n",
+ "\n",
+ "We model one position with five assumptions: starting shares, starting price, annual price appreciation, the starting dividend yield, and how fast the dividend grows each year. Every code cell re-embeds these so it runs independently.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Inputs & year-1 math"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "# --- Model inputs (edit these) ---\n",
+ "START_SHARES = 100.0 # shares owned at year 0\n",
+ "START_PRICE = 50.00 # price per share at year 0 ($)\n",
+ "PRICE_GROWTH = 0.06 # annual price appreciation (6%)\n",
+ "START_YIELD = 0.030 # starting dividend yield (3.0% of price)\n",
+ "DIV_GROWTH = 0.07 # annual dividend-per-share growth (7%)\n",
+ "YEARS = 25\n",
+ "\n",
+ "start_div_per_share = START_PRICE * START_YIELD\n",
+ "cost_basis = START_SHARES * START_PRICE\n",
+ "\n",
+ "print(\"Starting position\")\n",
+ "print(f\" Shares : {START_SHARES:,.2f}\")\n",
+ "print(f\" Price / share : ${START_PRICE:,.2f}\")\n",
+ "print(f\" Market value : ${cost_basis:,.2f}\")\n",
+ "print(f\" Dividend / share : ${start_div_per_share:,.3f} ({START_YIELD:.1%} yield)\")\n",
+ "print(f\" Year-1 dividends : ${START_SHARES * start_div_per_share:,.2f}\")\n",
+ "print()\n",
+ "print(\"Growth assumptions\")\n",
+ "print(f\" Price appreciation : {PRICE_GROWTH:.1%} / yr\")\n",
+ "print(f\" Dividend growth : {DIV_GROWTH:.1%} / yr\")\n",
+ "print(f\" Horizon : {YEARS} years\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Build the DRIP table\n",
+ "\n",
+ "Each year: the dividend per share grows, dividends paid = shares × dividend/share, those dividends buy new shares at **that year's price**, and share count rises. We capture every year in a DataFrame and also compute **yield-on-cost** — this year's dividend income divided by the original cost basis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "DRIP year-by-year table"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "START_SHARES, START_PRICE = 100.0, 50.00\n",
+ "PRICE_GROWTH, START_YIELD, DIV_GROWTH, YEARS = 0.06, 0.030, 0.07, 25\n",
+ "\n",
+ "cost_basis = START_SHARES * START_PRICE\n",
+ "div_per_share = START_PRICE * START_YIELD\n",
+ "shares = START_SHARES\n",
+ "price = START_PRICE\n",
+ "\n",
+ "rows = []\n",
+ "for year in range(1, YEARS + 1):\n",
+ " # price and dividend grow at the start of each year\n",
+ " price = price * (1 + PRICE_GROWTH)\n",
+ " div_per_share = div_per_share * (1 + DIV_GROWTH)\n",
+ "\n",
+ " dividends = shares * div_per_share\n",
+ " new_shares = dividends / price # reinvest at this year's price\n",
+ " shares += new_shares\n",
+ " value = shares * price\n",
+ " yield_on_cost = (shares * div_per_share) / cost_basis\n",
+ "\n",
+ " rows.append({\n",
+ " \"Year\": year,\n",
+ " \"Price\": round(price, 2),\n",
+ " \"Div/Share\": round(div_per_share, 4),\n",
+ " \"Dividends\": round(dividends, 2),\n",
+ " \"NewShares\": round(new_shares, 4),\n",
+ " \"Shares\": round(shares, 4),\n",
+ " \"Value\": round(value, 2),\n",
+ " \"YieldOnCost\": round(yield_on_cost * 100, 2),\n",
+ " })\n",
+ "\n",
+ "df = pd.DataFrame(rows)\n",
+ "# Show first 5 and last 5 years to keep the table readable\n",
+ "show = pd.concat([df.head(5), df.tail(5)])\n",
+ "print(\"DRIP projection (years 1-5 and 21-25):\\n\")\n",
+ "print(show.to_string(index=False))\n",
+ "\n",
+ "print(f\"\\nShares grew from {START_SHARES:,.1f} to {df['Shares'].iloc[-1]:,.1f} \"\n",
+ " f\"(+{df['Shares'].iloc[-1] / START_SHARES - 1:.0%}) purely from reinvested dividends.\")\n",
+ "print(f\"Yield-on-cost climbed from {START_YIELD:.1%} to {df['YieldOnCost'].iloc[-1]:.1f}%.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Reinvest vs take the cash\n",
+ "\n",
+ "Now the headline comparison. The **WITH reinvestment** path is the DRIP above. The **WITHOUT** path holds the original shares forever and pockets each dividend as cash; we sum that cash and add it to the unchanged stock value. Same business, same dividends — only the reinvest decision differs.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "DRIP vs cash dividends"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "START_SHARES, START_PRICE = 100.0, 50.00\n",
+ "PRICE_GROWTH, START_YIELD, DIV_GROWTH, YEARS = 0.06, 0.030, 0.07, 25\n",
+ "\n",
+ "cost_basis = START_SHARES * START_PRICE\n",
+ "\n",
+ "# --- WITH reinvestment (DRIP) ---\n",
+ "shares_drip = START_SHARES\n",
+ "price = START_PRICE\n",
+ "dps = START_PRICE * START_YIELD\n",
+ "for _ in range(YEARS):\n",
+ " price *= (1 + PRICE_GROWTH)\n",
+ " dps *= (1 + DIV_GROWTH)\n",
+ " shares_drip += (shares_drip * dps) / price\n",
+ "drip_value = shares_drip * price\n",
+ "\n",
+ "# --- WITHOUT reinvestment (cash out) ---\n",
+ "price = START_PRICE\n",
+ "dps = START_PRICE * START_YIELD\n",
+ "cash_collected = 0.0\n",
+ "for _ in range(YEARS):\n",
+ " price *= (1 + PRICE_GROWTH)\n",
+ " dps *= (1 + DIV_GROWTH)\n",
+ " cash_collected += START_SHARES * dps # shares never change\n",
+ "stock_value_nocash = START_SHARES * price\n",
+ "nocash_total = stock_value_nocash + cash_collected\n",
+ "\n",
+ "summary = pd.DataFrame([\n",
+ " {\"Strategy\": \"WITH reinvest (DRIP)\", \"FinalShares\": round(shares_drip, 2),\n",
+ " \"StockValue\": round(drip_value, 2), \"CashCollected\": 0.00,\n",
+ " \"TotalWealth\": round(drip_value, 2)},\n",
+ " {\"Strategy\": \"WITHOUT (cash out)\", \"FinalShares\": round(START_SHARES, 2),\n",
+ " \"StockValue\": round(stock_value_nocash, 2), \"CashCollected\": round(cash_collected, 2),\n",
+ " \"TotalWealth\": round(nocash_total, 2)},\n",
+ "])\n",
+ "print(summary.to_string(index=False))\n",
+ "\n",
+ "gap = drip_value - nocash_total\n",
+ "print(f\"\\nStarting cost basis : ${cost_basis:,.2f}\")\n",
+ "print(f\"Compounding advantage : ${gap:,.2f}\")\n",
+ "print(f\"DRIP total / cash-out total: {drip_value / nocash_total:.2f}x\")\n",
+ "print(\"\\nReinvesting wins because each new share itself earns a growing dividend —\")\n",
+ "print(\"the cash-out investor's share count (and so dividend income) never grows.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/investing_dollar_cost_averaging.ipynb b/fincept-qt/resources/notebooks/investing_dollar_cost_averaging.ipynb
new file mode 100644
index 000000000..e5b2afde7
--- /dev/null
+++ b/fincept-qt/resources/notebooks/investing_dollar_cost_averaging.ipynb
@@ -0,0 +1,234 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Dollar-Cost Averaging Simulator\n",
+ "\n",
+ "**Investing · Beginner · ~12 min · Standard library only**\n",
+ "\n",
+ "Dollar-cost averaging (DCA) means investing a fixed dollar amount on a regular schedule — say $500 every month — regardless of price. You buy more units when prices are low and fewer when prices are high. This notebook simulates DCA over a 24-month price series for an index fund and compares it against putting the same total in as a single lump sum on day one.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to track units, cost basis, and portfolio value month by month under DCA\n",
+ "- How DCA's average cost per unit differs from the simple average price\n",
+ "- When DCA wins (volatile or declining entry) versus when lump-sum wins (steadily rising market)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The price series\n",
+ "\n",
+ "Here is our embedded 24-month month-end price series for a hypothetical index fund. It dips early, bottoms around month 8, then recovers — a realistic 'choppy then rising' path. Every code cell below re-embeds this same list so it can run on its own.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Price series"
+ },
+ "outputs": [],
+ "source": [
+ "# Month-end prices for the index fund (month 0 .. month 23)\n",
+ "prices = [\n",
+ " 100.00, 98.50, 95.20, 92.80, 90.10, 93.40, 88.70, 85.30,\n",
+ " 82.90, 86.50, 89.20, 91.80, 94.30, 92.10, 96.70, 99.40,\n",
+ " 101.20, 103.80, 102.50, 105.90, 108.30, 110.10, 112.70, 115.00,\n",
+ "]\n",
+ "\n",
+ "print(f\"Months in series : {len(prices)}\")\n",
+ "print(f\"Start price (m0) : ${prices[0]:>7.2f}\")\n",
+ "print(f\"Lowest price : ${min(prices):>7.2f} (month {prices.index(min(prices))})\")\n",
+ "print(f\"Highest price : ${max(prices):>7.2f} (month {prices.index(max(prices))})\")\n",
+ "print(f\"End price (m23) : ${prices[-1]:>7.2f}\")\n",
+ "\n",
+ "simple_avg = sum(prices) / len(prices)\n",
+ "print(f\"\\nSimple average price over the 24 months: ${simple_avg:.2f}\")\n",
+ "total_change = (prices[-1] / prices[0] - 1) * 100\n",
+ "print(f\"Total price change month 0 -> month 23 : {total_change:+.1f}%\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Run the DCA simulation\n",
+ "\n",
+ "We invest a fixed **$500 every month**. Each month, units bought = contribution / price. We accumulate units, total invested, and portfolio value (units held × current price). The **average cost per unit** is total invested ÷ units held — the number that really matters.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "DCA month-by-month"
+ },
+ "outputs": [],
+ "source": [
+ "prices = [\n",
+ " 100.00, 98.50, 95.20, 92.80, 90.10, 93.40, 88.70, 85.30,\n",
+ " 82.90, 86.50, 89.20, 91.80, 94.30, 92.10, 96.70, 99.40,\n",
+ " 101.20, 103.80, 102.50, 105.90, 108.30, 110.10, 112.70, 115.00,\n",
+ "]\n",
+ "\n",
+ "MONTHLY = 500.00 # fixed dollar contribution each month\n",
+ "\n",
+ "units = 0.0\n",
+ "invested = 0.0\n",
+ "\n",
+ "header = f\"{'Mo':>3} {'Price':>8} {'Buy$':>7} {'Units+':>8} {'Units':>9} {'Invested':>10} {'Value':>10} {'AvgCost':>8}\"\n",
+ "print(header)\n",
+ "print(\"-\" * len(header))\n",
+ "\n",
+ "for m, p in enumerate(prices):\n",
+ " bought = MONTHLY / p\n",
+ " units += bought\n",
+ " invested += MONTHLY\n",
+ " value = units * p\n",
+ " avg_cost = invested / units\n",
+ " # print every 3rd month plus the last, to keep the table compact\n",
+ " if m % 3 == 0 or m == len(prices) - 1:\n",
+ " print(f\"{m:>3} {p:>8.2f} {MONTHLY:>7.0f} {bought:>8.3f} \"\n",
+ " f\"{units:>9.3f} {invested:>10.2f} {value:>10.2f} {avg_cost:>8.2f}\")\n",
+ "\n",
+ "print(\"-\" * len(header))\n",
+ "print(f\"\\nDCA final units held : {units:.3f}\")\n",
+ "print(f\"DCA total invested : ${invested:,.2f}\")\n",
+ "print(f\"DCA average cost / unit : ${invested / units:.2f}\")\n",
+ "print(f\"DCA final value (@m23) : ${units * prices[-1]:,.2f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. DCA vs lump-sum\n",
+ "\n",
+ "Now compare. The lump-sum investor puts the **entire 24 months of contributions in at month 0** — 24 × $500 = $12,000 — and holds. Both end with the same dollars contributed; the only difference is *when*. We compare final value, profit, and return.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "DCA vs lump-sum"
+ },
+ "outputs": [],
+ "source": [
+ "prices = [\n",
+ " 100.00, 98.50, 95.20, 92.80, 90.10, 93.40, 88.70, 85.30,\n",
+ " 82.90, 86.50, 89.20, 91.80, 94.30, 92.10, 96.70, 99.40,\n",
+ " 101.20, 103.80, 102.50, 105.90, 108.30, 110.10, 112.70, 115.00,\n",
+ "]\n",
+ "\n",
+ "MONTHLY = 500.00\n",
+ "n = len(prices)\n",
+ "total_capital = MONTHLY * n # same total dollars for both strategies\n",
+ "end_price = prices[-1]\n",
+ "\n",
+ "# --- DCA ---\n",
+ "dca_units = sum(MONTHLY / p for p in prices)\n",
+ "dca_value = dca_units * end_price\n",
+ "dca_avg_cost = total_capital / dca_units\n",
+ "\n",
+ "# --- Lump sum: all capital at month 0 price ---\n",
+ "ls_units = total_capital / prices[0]\n",
+ "ls_value = ls_units * end_price\n",
+ "ls_avg_cost = prices[0]\n",
+ "\n",
+ "def pct(value, cost):\n",
+ " return (value / cost - 1) * 100\n",
+ "\n",
+ "rows = [\n",
+ " (\"Total invested\", f\"${total_capital:,.2f}\", f\"${total_capital:,.2f}\"),\n",
+ " (\"Units acquired\", f\"{dca_units:,.3f}\", f\"{ls_units:,.3f}\"),\n",
+ " (\"Avg cost / unit\", f\"${dca_avg_cost:,.2f}\", f\"${ls_avg_cost:,.2f}\"),\n",
+ " (\"Final value\", f\"${dca_value:,.2f}\", f\"${ls_value:,.2f}\"),\n",
+ " (\"Profit\", f\"${dca_value - total_capital:,.2f}\", f\"${ls_value - total_capital:,.2f}\"),\n",
+ " (\"Return\", f\"{pct(dca_value, total_capital):+.1f}%\", f\"{pct(ls_value, total_capital):+.1f}%\"),\n",
+ "]\n",
+ "\n",
+ "print(f\"{'Metric':<16} {'DCA':>14} {'Lump sum':>14}\")\n",
+ "print(\"-\" * 46)\n",
+ "for label, a, b in rows:\n",
+ " print(f\"{label:<16} {a:>14} {b:>14}\")\n",
+ "\n",
+ "print(\"-\" * 46)\n",
+ "diff = ls_value - dca_value\n",
+ "winner = \"Lump sum\" if diff > 0 else \"DCA\"\n",
+ "print(f\"\\nWinner in THIS series: {winner} by ${abs(diff):,.2f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. When does each strategy win?\n",
+ "\n",
+ "The result is path-dependent. To see why, we test the same DCA-vs-lump-sum logic on three stylised 12-month paths: a steadily **rising** market, a steadily **declining** market, and a **V-shaped** dip-and-recover. Watch which strategy wins in each.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Three market regimes"
+ },
+ "outputs": [],
+ "source": [
+ "def simulate(prices, monthly=500.0):\n",
+ " n = len(prices)\n",
+ " capital = monthly * n\n",
+ " end = prices[-1]\n",
+ " dca_units = sum(monthly / p for p in prices)\n",
+ " ls_units = capital / prices[0]\n",
+ " return capital, dca_units * end, ls_units * end\n",
+ "\n",
+ "# Three 12-month regimes (start at 100 in each)\n",
+ "rising = [100 + 2.0 * i for i in range(12)] # straight up\n",
+ "declining = [100 - 2.0 * i for i in range(12)] # straight down\n",
+ "v_shaped = [100, 95, 90, 85, 80, 78, 80, 85, 90, 95, 100, 105] # dip then recover\n",
+ "\n",
+ "scenarios = [(\"Rising\", rising), (\"Declining\", declining), (\"V-shaped\", v_shaped)]\n",
+ "\n",
+ "print(f\"{'Regime':<11} {'DCA value':>12} {'Lump value':>12} {'Winner':>10}\")\n",
+ "print(\"-\" * 47)\n",
+ "for name, series in scenarios:\n",
+ " cap, dca_v, ls_v = simulate(series)\n",
+ " winner = \"Lump sum\" if ls_v > dca_v else \"DCA\"\n",
+ " print(f\"{name:<11} {dca_v:>12,.2f} {ls_v:>12,.2f} {winner:>10}\")\n",
+ "\n",
+ "print(\"\\nTakeaways:\")\n",
+ "print(\" - Rising market : lump sum wins. Money invested earlier rides the whole climb.\")\n",
+ "print(\" - Declining : DCA wins. Later buys are cheaper, lowering average cost.\")\n",
+ "print(\" - V-shaped : DCA wins. It loads up near the bottom; lump-sum bought at the top.\")\n",
+ "print(\"\\nRule of thumb: lump-sum has the higher EXPECTED return because markets rise\")\n",
+ "print(\"more often than they fall, but DCA reduces timing risk and is easier to stick to.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/notebooks_manifest.json b/fincept-qt/resources/notebooks/notebooks_manifest.json
new file mode 100644
index 000000000..71066af4a
--- /dev/null
+++ b/fincept-qt/resources/notebooks/notebooks_manifest.json
@@ -0,0 +1,126 @@
+{
+ "version": 1,
+ "brand": "Fincept Notebook",
+ "notebooks": [
+ {
+ "id": "finance-time-value-of-money",
+ "title": "Time Value of Money",
+ "category": "Finance",
+ "difficulty": "Beginner",
+ "est_minutes": 10,
+ "requires": "stdlib",
+ "summary": "Present value, future value, NPV and IRR from first principles — the math behind every valuation, using only the Python standard library.",
+ "file": "finance_time_value_of_money.ipynb"
+ },
+ {
+ "id": "finance-financial-ratios",
+ "title": "Financial Statement Ratios",
+ "category": "Finance",
+ "difficulty": "Intermediate",
+ "est_minutes": 18,
+ "requires": "pandas + numpy",
+ "summary": "Turn an income statement and balance sheet into liquidity, profitability and leverage ratios with a tidy pandas DataFrame.",
+ "file": "finance_financial_ratios.ipynb"
+ },
+ {
+ "id": "economics-inflation-real-returns",
+ "title": "Inflation & Real Returns",
+ "category": "Economics",
+ "difficulty": "Beginner",
+ "est_minutes": 12,
+ "requires": "stdlib",
+ "summary": "Read a CPI series, compute inflation, and learn why nominal returns lie — real vs nominal and the Rule of 72.",
+ "file": "economics_inflation_real_returns.ipynb"
+ },
+ {
+ "id": "economics-yield-curve",
+ "title": "Yield Curve & Recession Signal",
+ "category": "Economics",
+ "difficulty": "Hard",
+ "est_minutes": 30,
+ "requires": "pandas + numpy",
+ "summary": "Build a Treasury yield curve, interpolate missing tenors with numpy, and detect the 10y-2y inversion that precedes recessions.",
+ "file": "economics_yield_curve.ipynb"
+ },
+ {
+ "id": "trading-first-watchlist",
+ "title": "Your First Watchlist & Returns",
+ "category": "Trading",
+ "difficulty": "Beginner",
+ "est_minutes": 12,
+ "requires": "stdlib",
+ "summary": "Build a watchlist, compute daily returns and volatility, and rank winners and losers — pure standard library.",
+ "file": "trading_first_watchlist.ipynb"
+ },
+ {
+ "id": "trading-sma-crossover-backtest",
+ "title": "Moving Average Crossover Backtest",
+ "category": "Trading",
+ "difficulty": "Intermediate",
+ "est_minutes": 22,
+ "requires": "pandas + numpy",
+ "summary": "Backtest a fast/slow SMA crossover strategy on a price series, build the equity curve, and measure return, drawdown and Sharpe.",
+ "file": "trading_sma_crossover_backtest.ipynb"
+ },
+ {
+ "id": "investing-dollar-cost-averaging",
+ "title": "Dollar-Cost Averaging Simulator",
+ "category": "Investing",
+ "difficulty": "Beginner",
+ "est_minutes": 12,
+ "requires": "stdlib",
+ "summary": "Simulate dollar-cost averaging vs a lump-sum investment over a volatile market and see which wins and why.",
+ "file": "investing_dollar_cost_averaging.ipynb"
+ },
+ {
+ "id": "investing-dividend-compounding",
+ "title": "Dividend Growth & DRIP Compounding",
+ "category": "Investing",
+ "difficulty": "Intermediate",
+ "est_minutes": 18,
+ "requires": "pandas + numpy",
+ "summary": "Model a dividend reinvestment plan (DRIP) with growing dividends and watch compounding snowball over decades with pandas.",
+ "file": "investing_dividend_compounding.ipynb"
+ },
+ {
+ "id": "portfolio-weights-returns",
+ "title": "Portfolio Weights & Returns",
+ "category": "Portfolio",
+ "difficulty": "Beginner",
+ "est_minutes": 12,
+ "requires": "stdlib",
+ "summary": "Allocate weights across assets, compute the weighted portfolio return, and see how drift forces rebalancing.",
+ "file": "portfolio_weights_returns.ipynb"
+ },
+ {
+ "id": "portfolio-mean-variance-optimization",
+ "title": "Mean-Variance Optimization",
+ "category": "Portfolio",
+ "difficulty": "Hard",
+ "est_minutes": 35,
+ "requires": "pandas + numpy",
+ "summary": "Build the efficient frontier: covariance, thousands of simulated portfolios with numpy, and the max-Sharpe and min-volatility picks.",
+ "file": "portfolio_mean_variance_optimization.ipynb"
+ },
+ {
+ "id": "quant-monte-carlo-gbm",
+ "title": "Monte Carlo Price Simulation",
+ "category": "Quant",
+ "difficulty": "Intermediate",
+ "est_minutes": 22,
+ "requires": "pandas + numpy",
+ "summary": "Simulate thousands of Geometric Brownian Motion price paths with numpy, build a percentile cone, and estimate Value at Risk.",
+ "file": "quant_monte_carlo_gbm.ipynb"
+ },
+ {
+ "id": "quant-pairs-trading-zscore",
+ "title": "Pairs Trading: Spread Z-Score",
+ "category": "Quant",
+ "difficulty": "Hard",
+ "est_minutes": 32,
+ "requires": "pandas + numpy",
+ "summary": "Estimate a hedge ratio by least squares, build the spread z-score, and generate mean-reversion entry/exit signals with a simple P&L.",
+ "file": "quant_pairs_trading_zscore.ipynb"
+ }
+ ]
+}
diff --git a/fincept-qt/resources/notebooks/portfolio_mean_variance_optimization.ipynb b/fincept-qt/resources/notebooks/portfolio_mean_variance_optimization.ipynb
new file mode 100644
index 000000000..d46c35418
--- /dev/null
+++ b/fincept-qt/resources/notebooks/portfolio_mean_variance_optimization.ipynb
@@ -0,0 +1,368 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Mean-Variance Optimization\n",
+ "\n",
+ "**Portfolio · Hard · ~35 min · pandas + numpy**\n",
+ "\n",
+ "Harry Markowitz's mean-variance framework is the foundation of modern portfolio theory. The core idea: a portfolio is not just a basket of returns — it is a trade-off between *expected return* and *risk* (volatility), and because assets are imperfectly correlated, the risk of the whole is less than the sum of its parts. In this notebook we build a covariance matrix from volatilities and correlations, simulate thousands of long-only portfolios, and locate the two portfolios every quant cares about: the **maximum-Sharpe** (tangency) portfolio and the **minimum-variance** portfolio.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to build an annualized covariance matrix from volatilities + a correlation matrix\n",
+ "- How to compute portfolio expected return, volatility, and Sharpe ratio from weights\n",
+ "- How Monte Carlo sampling traces out the efficient frontier and reveals the diversification benefit\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The inputs: expected returns, vols, and correlations\n",
+ "\n",
+ "Mean-variance optimization needs three things for a universe of *N* assets:\n",
+ "\n",
+ "1. **Expected annual returns** `μ` — a length-N vector.\n",
+ "2. **Annual volatilities** `σ` — a length-N vector (the standard deviation of each asset's annual return).\n",
+ "3. **A correlation matrix** `R` — how the assets move together.\n",
+ "\n",
+ "The **covariance matrix** is then built as `Σ = D · R · D`, where `D = diag(σ)`. Element `Σ[i,j] = σ_i · σ_j · ρ_ij`. We use four realistic assets: US Equity, Intl Equity, Bonds, and Gold.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Build Covariance"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "assets = [\"US_Equity\", \"Intl_Equity\", \"Bonds\", \"Gold\"]\n",
+ "\n",
+ "# Expected ANNUAL returns and ANNUAL volatilities (realistic long-run estimates)\n",
+ "mu = np.array([0.085, 0.075, 0.035, 0.055]) # expected annual return\n",
+ "vol = np.array([0.160, 0.180, 0.060, 0.150]) # annual volatility (std dev)\n",
+ "\n",
+ "# Correlation matrix (symmetric, 1s on diagonal)\n",
+ "corr = np.array([\n",
+ " [1.00, 0.80, 0.10, 0.15],\n",
+ " [0.80, 1.00, 0.05, 0.20],\n",
+ " [0.10, 0.05, 1.00, 0.25],\n",
+ " [0.15, 0.20, 0.25, 1.00],\n",
+ "])\n",
+ "\n",
+ "# Covariance = diag(vol) @ corr @ diag(vol)\n",
+ "D = np.diag(vol)\n",
+ "cov = D @ corr @ D\n",
+ "\n",
+ "print(\"Expected annual return & volatility per asset\")\n",
+ "print(pd.DataFrame({\"E[return]\": mu, \"volatility\": vol}, index=assets).round(4).to_string())\n",
+ "print()\n",
+ "print(\"Correlation matrix\")\n",
+ "print(pd.DataFrame(corr, index=assets, columns=assets).round(2).to_string())\n",
+ "print()\n",
+ "print(\"Annualized covariance matrix (Σ = D·R·D)\")\n",
+ "print(pd.DataFrame(cov, index=assets, columns=assets).round(5).to_string())\n",
+ "print()\n",
+ "print(\"Sanity check: sqrt(diag(cov)) should equal the input vols ->\", np.allclose(np.sqrt(np.diag(cov)), vol))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Portfolio math: return, volatility, Sharpe\n",
+ "\n",
+ "Given a weight vector `w` (long-only, `w_i ≥ 0`, `Σ w_i = 1`):\n",
+ "\n",
+ "- **Expected return:** `μ_p = wᵀ μ`\n",
+ "- **Variance:** `σ²_p = wᵀ Σ w` &nbsp;→&nbsp; **Volatility:** `σ_p = √(wᵀ Σ w)`\n",
+ "- **Sharpe ratio:** `(μ_p − r_f) / σ_p`, with risk-free rate `r_f`.\n",
+ "\n",
+ "The `wᵀ Σ w` term is the magic: cross-terms `w_i w_j σ_ij` with low correlation *reduce* total variance below the weighted average of individual variances. That is diversification, quantified. Let's verify on an equal-weight portfolio.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Portfolio Functions"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "assets = [\"US_Equity\", \"Intl_Equity\", \"Bonds\", \"Gold\"]\n",
+ "mu = np.array([0.085, 0.075, 0.035, 0.055])\n",
+ "vol = np.array([0.160, 0.180, 0.060, 0.150])\n",
+ "corr = np.array([\n",
+ " [1.00, 0.80, 0.10, 0.15],\n",
+ " [0.80, 1.00, 0.05, 0.20],\n",
+ " [0.10, 0.05, 1.00, 0.25],\n",
+ " [0.15, 0.20, 0.25, 1.00],\n",
+ "])\n",
+ "D = np.diag(vol)\n",
+ "cov = D @ corr @ D\n",
+ "rf = 0.03 # risk-free rate\n",
+ "\n",
+ "def port_return(w): return float(w @ mu)\n",
+ "def port_vol(w): return float(np.sqrt(w @ cov @ w))\n",
+ "def port_sharpe(w): return (port_return(w) - rf) / port_vol(w)\n",
+ "\n",
+ "# Equal-weight portfolio\n",
+ "w_eq = np.repeat(1.0 / len(assets), len(assets))\n",
+ "\n",
+ "# Weighted-average vol (what you'd get with NO diversification, i.e. perfect correlation)\n",
+ "weighted_avg_vol = float(w_eq @ vol)\n",
+ "\n",
+ "print(\"Equal-weight portfolio (25% each)\")\n",
+ "print(f\" Expected return : {port_return(w_eq):.4f}\")\n",
+ "print(f\" Volatility : {port_vol(w_eq):.4f}\")\n",
+ "print(f\" Sharpe ratio : {port_sharpe(w_eq):.4f}\")\n",
+ "print()\n",
+ "print(f\" Weighted-avg vol (no diversification) : {weighted_avg_vol:.4f}\")\n",
+ "print(f\" Actual portfolio vol : {port_vol(w_eq):.4f}\")\n",
+ "print(f\" Diversification benefit (vol saved) : {weighted_avg_vol - port_vol(w_eq):.4f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Monte Carlo: simulate 10,000 random portfolios\n",
+ "\n",
+ "There is a closed-form solution for the efficient frontier, but a Monte Carlo sweep is more intuitive and handles the long-only constraint naturally. We draw 10,000 weight vectors from a **Dirichlet distribution**, which produces non-negative weights that sum to 1 by construction — exactly the long-only simplex. For each portfolio we record return, volatility, and Sharpe. The cloud of points fills the *feasible region*; its upper-left boundary is the efficient frontier.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Simulate Portfolios"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "assets = [\"US_Equity\", \"Intl_Equity\", \"Bonds\", \"Gold\"]\n",
+ "mu = np.array([0.085, 0.075, 0.035, 0.055])\n",
+ "vol = np.array([0.160, 0.180, 0.060, 0.150])\n",
+ "corr = np.array([\n",
+ " [1.00, 0.80, 0.10, 0.15],\n",
+ " [0.80, 1.00, 0.05, 0.20],\n",
+ " [0.10, 0.05, 1.00, 0.25],\n",
+ " [0.15, 0.20, 0.25, 1.00],\n",
+ "])\n",
+ "cov = np.diag(vol) @ corr @ np.diag(vol)\n",
+ "rf = 0.03\n",
+ "\n",
+ "N_PORT = 10000\n",
+ "n = len(assets)\n",
+ "\n",
+ "# Dirichlet(1,...,1) = uniform over the long-only simplex (weights >=0, sum to 1)\n",
+ "W = np.random.dirichlet(np.ones(n), size=N_PORT) # shape (N_PORT, n)\n",
+ "\n",
+ "rets = W @ mu # expected returns, shape (N_PORT,)\n",
+ "vols = np.sqrt(np.einsum('ij,jk,ik->i', W, cov, W)) # portfolio vols, vectorized wᵀΣw\n",
+ "sharpes = (rets - rf) / vols\n",
+ "\n",
+ "sim = pd.DataFrame({\"return\": rets, \"vol\": vols, \"sharpe\": sharpes})\n",
+ "\n",
+ "print(f\"Simulated {N_PORT:,} long-only portfolios (Dirichlet weights, seed=7)\")\n",
+ "print()\n",
+ "print(\"Summary statistics across the cloud:\")\n",
+ "print(sim.describe().round(4).to_string())\n",
+ "print()\n",
+ "print(\"First 5 sampled portfolios:\")\n",
+ "head = sim.head(5).copy()\n",
+ "for j, a in enumerate(assets):\n",
+ " head[a] = W[:5, j]\n",
+ "print(head.round(4).to_string())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. The two special portfolios\n",
+ "\n",
+ "From the cloud we extract:\n",
+ "\n",
+ "- **Maximum-Sharpe (tangency) portfolio** — the one with the highest risk-adjusted return `(μ_p − r_f)/σ_p`. This is the portfolio a rational investor combines with the risk-free asset.\n",
+ "- **Minimum-volatility portfolio** — the leftmost point of the frontier; the lowest-risk mix achievable, regardless of return.\n",
+ "\n",
+ "Note that Monte Carlo only *approximates* the true optima — with more samples the estimates tighten. We print full weight vectors for both.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Optimal Portfolios"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "assets = [\"US_Equity\", \"Intl_Equity\", \"Bonds\", \"Gold\"]\n",
+ "mu = np.array([0.085, 0.075, 0.035, 0.055])\n",
+ "vol = np.array([0.160, 0.180, 0.060, 0.150])\n",
+ "corr = np.array([\n",
+ " [1.00, 0.80, 0.10, 0.15],\n",
+ " [0.80, 1.00, 0.05, 0.20],\n",
+ " [0.10, 0.05, 1.00, 0.25],\n",
+ " [0.15, 0.20, 0.25, 1.00],\n",
+ "])\n",
+ "cov = np.diag(vol) @ corr @ np.diag(vol)\n",
+ "rf = 0.03\n",
+ "\n",
+ "N_PORT = 10000\n",
+ "n = len(assets)\n",
+ "W = np.random.dirichlet(np.ones(n), size=N_PORT)\n",
+ "rets = W @ mu\n",
+ "vols = np.sqrt(np.einsum('ij,jk,ik->i', W, cov, W))\n",
+ "sharpes = (rets - rf) / vols\n",
+ "\n",
+ "i_sharpe = int(np.argmax(sharpes)) # max-Sharpe portfolio index\n",
+ "i_minvol = int(np.argmin(vols)) # min-volatility portfolio index\n",
+ "\n",
+ "def describe(i, label):\n",
+ " w = W[i]\n",
+ " print(label)\n",
+ " print(f\" Expected return : {rets[i]:.4f}\")\n",
+ " print(f\" Volatility : {vols[i]:.4f}\")\n",
+ " print(f\" Sharpe ratio : {sharpes[i]:.4f}\")\n",
+ " print(\" Weights:\")\n",
+ " for a, wi in zip(assets, w):\n",
+ " print(f\" {a:<12} {wi:7.2%}\")\n",
+ " print()\n",
+ "\n",
+ "describe(i_sharpe, \"=== MAXIMUM-SHARPE (tangency) PORTFOLIO ===\")\n",
+ "describe(i_minvol, \"=== MINIMUM-VOLATILITY PORTFOLIO ===\")\n",
+ "\n",
+ "comp = pd.DataFrame({\n",
+ " \"Max-Sharpe\": W[i_sharpe],\n",
+ " \"Min-Vol\": W[i_minvol],\n",
+ "}, index=assets)\n",
+ "print(\"Weight comparison\")\n",
+ "print(comp.round(4).to_string())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Tracing the efficient frontier\n",
+ "\n",
+ "The **efficient frontier** is the set of portfolios offering the highest expected return for each level of risk. To approximate it from our cloud, we bucket the simulated portfolios by volatility, and within each bucket keep the one with the maximum return. The result is a monotone, concave curve — the upper edge of the feasible region. Anything below the frontier is dominated (you could get more return for the same risk).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Efficient Frontier"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "assets = [\"US_Equity\", \"Intl_Equity\", \"Bonds\", \"Gold\"]\n",
+ "mu = np.array([0.085, 0.075, 0.035, 0.055])\n",
+ "vol = np.array([0.160, 0.180, 0.060, 0.150])\n",
+ "corr = np.array([\n",
+ " [1.00, 0.80, 0.10, 0.15],\n",
+ " [0.80, 1.00, 0.05, 0.20],\n",
+ " [0.10, 0.05, 1.00, 0.25],\n",
+ " [0.15, 0.20, 0.25, 1.00],\n",
+ "])\n",
+ "cov = np.diag(vol) @ corr @ np.diag(vol)\n",
+ "rf = 0.03\n",
+ "\n",
+ "N_PORT = 10000\n",
+ "n = len(assets)\n",
+ "W = np.random.dirichlet(np.ones(n), size=N_PORT)\n",
+ "rets = W @ mu\n",
+ "vols = np.sqrt(np.einsum('ij,jk,ik->i', W, cov, W))\n",
+ "sharpes = (rets - rf) / vols\n",
+ "\n",
+ "sim = pd.DataFrame({\"return\": rets, \"vol\": vols, \"sharpe\": sharpes})\n",
+ "\n",
+ "# Bucket by volatility, take the max-return portfolio in each bucket -> frontier\n",
+ "n_buckets = 12\n",
+ "sim[\"vol_bucket\"] = pd.cut(sim[\"vol\"], bins=n_buckets)\n",
+ "idx = sim.groupby(\"vol_bucket\", observed=True)[\"return\"].idxmax().dropna().astype(int)\n",
+ "frontier = sim.loc[idx, [\"vol\", \"return\", \"sharpe\"]].sort_values(\"vol\").reset_index(drop=True)\n",
+ "\n",
+ "print(\"Approximate efficient frontier (max return per volatility bucket)\")\n",
+ "print(frontier.round(4).to_string())\n",
+ "print()\n",
+ "print(\"Notice: as volatility rises, the best achievable return rises but with\")\n",
+ "print(\"diminishing slope (concavity) — and Sharpe peaks near the tangency point.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 6. Why diversification works\n",
+ "\n",
+ "Look back at the min-vol portfolio: it loads heavily on bonds (low vol) but still holds some equity and gold. Why not 100% bonds? Because gold and equities have **low correlation** with bonds — adding a little of each lowers total variance via the negative-to-low cross-terms, even though each is individually riskier. The min-vol portfolio's volatility is typically *below* the lowest single-asset vol weighted average. That free lunch — lower risk for the same or higher return — is the entire point of Markowitz.\n",
+ "\n",
+ "**Caveats for real use:** expected returns are notoriously hard to estimate and optimizers are extremely sensitive to them; covariance is more stable but still noisy. Practitioners add constraints (position limits), shrinkage estimators, and robust/Black-Litterman methods. But the geometry you just simulated — the frontier, the tangency portfolio, the min-vol point — is universal.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/portfolio_weights_returns.ipynb b/fincept-qt/resources/notebooks/portfolio_weights_returns.ipynb
new file mode 100644
index 000000000..0746bda9e
--- /dev/null
+++ b/fincept-qt/resources/notebooks/portfolio_weights_returns.ipynb
@@ -0,0 +1,206 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Portfolio Weights & Returns\n",
+ "\n",
+ "**Portfolio · Beginner · ~12 min · Standard library only**\n",
+ "\n",
+ "A portfolio's weights — each holding's share of total market value — drive its overall return and risk. After a year in which holdings move differently, those weights drift away from your targets, so you rebalance: sell what grew too big, buy what shrank. This notebook walks the full loop on a simple four-asset book.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to turn market values into portfolio weights\n",
+ "- How to compute a weighted (blended) portfolio return\n",
+ "- How weights drift after a year, and the exact trades to rebalance to target\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The portfolio\n",
+ "\n",
+ "Four holdings with their current market values and the return each posted over the past year. Every code cell re-embeds this data so it runs on its own.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Holdings & weights"
+ },
+ "outputs": [],
+ "source": [
+ "# (ticker, market value $, annual return)\n",
+ "holdings = [\n",
+ " (\"EQTY\", 40000.0, 0.18), # equities\n",
+ " (\"BOND\", 30000.0, 0.04), # bonds\n",
+ " (\"GOLD\", 20000.0, -0.06), # gold\n",
+ " (\"CASH\", 10000.0, 0.05), # cash / money market\n",
+ "]\n",
+ "\n",
+ "total = sum(mv for _, mv, _ in holdings)\n",
+ "\n",
+ "print(f\"{'Asset':<6} {'Value':>12} {'Weight':>9} {'Return':>9}\")\n",
+ "print(\"-\" * 38)\n",
+ "for tkr, mv, ret in holdings:\n",
+ " w = mv / total\n",
+ " print(f\"{tkr:<6} {mv:>12,.2f} {w:>8.2%} {ret:>+9.2%}\")\n",
+ "print(\"-\" * 38)\n",
+ "print(f\"{'TOTAL':<6} {total:>12,.2f} {1.0:>8.2%}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Weighted portfolio return\n",
+ "\n",
+ "The portfolio return is the sum of each weight times that asset's return — not a plain average. Each holding contributes in proportion to its size, so the big equity sleeve dominates.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Weighted return"
+ },
+ "outputs": [],
+ "source": [
+ "holdings = [\n",
+ " (\"EQTY\", 40000.0, 0.18),\n",
+ " (\"BOND\", 30000.0, 0.04),\n",
+ " (\"GOLD\", 20000.0, -0.06),\n",
+ " (\"CASH\", 10000.0, 0.05),\n",
+ "]\n",
+ "\n",
+ "total = sum(mv for _, mv, _ in holdings)\n",
+ "\n",
+ "print(f\"{'Asset':<6} {'Weight':>9} {'Return':>9} {'Contribution':>13}\")\n",
+ "print(\"-\" * 40)\n",
+ "port_return = 0.0\n",
+ "for tkr, mv, ret in holdings:\n",
+ " w = mv / total\n",
+ " contrib = w * ret\n",
+ " port_return += contrib\n",
+ " print(f\"{tkr:<6} {w:>8.2%} {ret:>+9.2%} {contrib:>+13.4%}\")\n",
+ "print(\"-\" * 40)\n",
+ "print(f\"{'PORTFOLIO':<6} {'':>9} {'':>9} {port_return:>+13.4%}\")\n",
+ "\n",
+ "start_value = total\n",
+ "end_value = start_value * (1 + port_return)\n",
+ "print(f\"\\nStart value : ${start_value:,.2f}\")\n",
+ "print(f\"End value : ${end_value:,.2f}\")\n",
+ "print(f\"Gain : ${end_value - start_value:,.2f} ({port_return:+.2%})\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Weight drift after a year\n",
+ "\n",
+ "Because each asset returned something different, after a year the new market values imply **new weights**. The winners now take up more of the book than your target allocation, the losers less. We compare drifted weights against the targets.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Drift vs target"
+ },
+ "outputs": [],
+ "source": [
+ "holdings = [\n",
+ " (\"EQTY\", 40000.0, 0.18),\n",
+ " (\"BOND\", 30000.0, 0.04),\n",
+ " (\"GOLD\", 20000.0, -0.06),\n",
+ " (\"CASH\", 10000.0, 0.05),\n",
+ "]\n",
+ "# Target allocation we want to hold (sums to 1.0)\n",
+ "targets = {\"EQTY\": 0.40, \"BOND\": 0.30, \"GOLD\": 0.20, \"CASH\": 0.10}\n",
+ "\n",
+ "start_total = sum(mv for _, mv, _ in holdings)\n",
+ "# market value after a year of returns\n",
+ "ending = [(t, mv * (1 + r)) for t, mv, r in holdings]\n",
+ "end_total = sum(mv for _, mv in ending)\n",
+ "\n",
+ "print(f\"{'Asset':<6} {'EndValue':>12} {'NewWt':>8} {'Target':>8} {'Drift':>8}\")\n",
+ "print(\"-\" * 46)\n",
+ "for tkr, mv in ending:\n",
+ " new_w = mv / end_total\n",
+ " tgt = targets[tkr]\n",
+ " drift = new_w - tgt\n",
+ " print(f\"{tkr:<6} {mv:>12,.2f} {new_w:>7.2%} {tgt:>7.2%} {drift:>+8.2%}\")\n",
+ "print(\"-\" * 46)\n",
+ "print(f\"{'TOTAL':<6} {end_total:>12,.2f}\")\n",
+ "print(\"\\nPositive drift = now OVER-weight (it outperformed); negative = under-weight.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Trades to rebalance\n",
+ "\n",
+ "To return to target, each holding's target dollar value is `target_weight × end_total`. The trade is `target_value − current_value`: a positive number means **buy**, negative means **sell**. The trades net to roughly zero — we fund buys by selling the over-weight winners.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Rebalancing trades"
+ },
+ "outputs": [],
+ "source": [
+ "holdings = [\n",
+ " (\"EQTY\", 40000.0, 0.18),\n",
+ " (\"BOND\", 30000.0, 0.04),\n",
+ " (\"GOLD\", 20000.0, -0.06),\n",
+ " (\"CASH\", 10000.0, 0.05),\n",
+ "]\n",
+ "targets = {\"EQTY\": 0.40, \"BOND\": 0.30, \"GOLD\": 0.20, \"CASH\": 0.10}\n",
+ "\n",
+ "ending = [(t, mv * (1 + r)) for t, mv, r in holdings]\n",
+ "end_total = sum(mv for _, mv in ending)\n",
+ "\n",
+ "print(f\"{'Asset':<6} {'Current':>12} {'TargetVal':>12} {'Trade':>12} {'Action':>7}\")\n",
+ "print(\"-\" * 54)\n",
+ "total_trade = 0.0\n",
+ "for tkr, mv in ending:\n",
+ " target_val = targets[tkr] * end_total\n",
+ " trade = target_val - mv\n",
+ " total_trade += trade\n",
+ " action = \"BUY\" if trade > 0 else (\"SELL\" if trade < 0 else \"HOLD\")\n",
+ " print(f\"{tkr:<6} {mv:>12,.2f} {target_val:>12,.2f} {trade:>+12,.2f} {action:>7}\")\n",
+ "print(\"-\" * 54)\n",
+ "print(f\"{'NET':<6} {end_total:>12,.2f} {end_total:>12,.2f} {total_trade:>+12,.2f}\")\n",
+ "print(\"\\nNet trade is ~0: rebalancing is self-funding. Sell the over-weight winners,\")\n",
+ "print(\"use the proceeds to top up the under-weight holdings, and weights return to target.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/quant_monte_carlo_gbm.ipynb b/fincept-qt/resources/notebooks/quant_monte_carlo_gbm.ipynb
new file mode 100644
index 000000000..f84b32769
--- /dev/null
+++ b/fincept-qt/resources/notebooks/quant_monte_carlo_gbm.ipynb
@@ -0,0 +1,341 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Monte Carlo Price Simulation\n",
+ "\n",
+ "**Quant · Intermediate · ~22 min · pandas + numpy**\n",
+ "\n",
+ "Geometric Brownian Motion (GBM) is the workhorse model for simulating asset prices — it's the same diffusion that sits underneath the Black-Scholes formula. A price evolves with a deterministic **drift** (the trend) and a random **diffusion** (the noise), and the magic of Monte Carlo is that by simulating thousands of independent paths we can read off the *entire distribution* of where the price might land — not just a point forecast. From that distribution we extract percentile cones, Value at Risk, and shortfall probabilities.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- The GBM equation and how drift vs diffusion shape a price path\n",
+ "- How to simulate thousands of daily-stepped paths with numpy and cumulate log returns\n",
+ "- How to read percentile cones, 95% Value at Risk, and the probability of ending below the start\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The model and parameters\n",
+ "\n",
+ "Under GBM the log return over a small time step `dt` is normally distributed:\n",
+ "\n",
+ "$$\\Delta \\ln S \\sim \\mathcal{N}\\big((\\mu - \\tfrac{1}{2}\\sigma^2)\\,dt,\\;\\; \\sigma^2\\,dt\\big)$$\n",
+ "\n",
+ "- **μ** — annual drift (expected continuously-compounded return).\n",
+ "- **σ** — annual volatility (diffusion).\n",
+ "- The `−½σ²` term is the **Itô correction**: because of Jensen's inequality, the *expected log price* drifts slower than μ even though the *expected price* grows at μ.\n",
+ "- We step daily with `dt = 1/252` (252 trading days/year) over a 1-year horizon.\n",
+ "\n",
+ "A single path is built by cumulating these log-return increments and exponentiating.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Parameters & One Path"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "S0 = 100.0 # starting price\n",
+ "MU = 0.08 # annual drift\n",
+ "SIGMA = 0.20 # annual volatility\n",
+ "DAYS = 252 # 1-year horizon in trading days\n",
+ "dt = 1.0 / 252\n",
+ "\n",
+ "# Per-step log-return distribution\n",
+ "mean_step = (MU - 0.5 * SIGMA**2) * dt\n",
+ "std_step = SIGMA * np.sqrt(dt)\n",
+ "\n",
+ "# Build ONE example path\n",
+ "z = np.random.normal(size=DAYS)\n",
+ "log_rets = mean_step + std_step * z\n",
+ "path = S0 * np.exp(np.cumsum(log_rets))\n",
+ "path = np.insert(path, 0, S0) # prepend t=0\n",
+ "\n",
+ "print(\"GBM parameters\")\n",
+ "print(f\" S0={S0} mu={MU} sigma={SIGMA} horizon={DAYS} days dt={dt:.6f}\")\n",
+ "print(f\" per-step log-return mean = {mean_step:.6f}, std = {std_step:.6f}\")\n",
+ "print()\n",
+ "snap = pd.DataFrame({\"day\": [0, 21, 63, 126, 189, 252],\n",
+ " \"price\": [path[i] for i in [0, 21, 63, 126, 189, 252]]})\n",
+ "print(\"One simulated path (snapshots)\")\n",
+ "print(snap.round(4).to_string(index=False))\n",
+ "print()\n",
+ "print(f\" Terminal price of this single path: {path[-1]:.4f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Simulate 10,000 paths\n",
+ "\n",
+ "One path tells us almost nothing — it's a single draw from an infinite set of futures. We now simulate **10,000 independent paths** at once. The trick is to generate a `(n_paths × DAYS)` matrix of standard normals, scale into log returns, cumulate *along the time axis*, and exponentiate. Vectorizing with numpy keeps this well under a second. Each row is one possible future; each column is a point in time.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Simulate Paths"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "S0, MU, SIGMA, DAYS = 100.0, 0.08, 0.20, 252\n",
+ "dt = 1.0 / 252\n",
+ "N_PATHS = 10000\n",
+ "\n",
+ "mean_step = (MU - 0.5 * SIGMA**2) * dt\n",
+ "std_step = SIGMA * np.sqrt(dt)\n",
+ "\n",
+ "# (N_PATHS x DAYS) matrix of log-return increments\n",
+ "Z = np.random.normal(size=(N_PATHS, DAYS))\n",
+ "log_rets = mean_step + std_step * Z\n",
+ "log_price = np.cumsum(log_rets, axis=1) # cumulate over time\n",
+ "paths = S0 * np.exp(log_price) # (N_PATHS x DAYS)\n",
+ "paths = np.hstack([np.full((N_PATHS, 1), S0), paths]) # prepend t=0 column\n",
+ "\n",
+ "terminal = paths[:, -1]\n",
+ "\n",
+ "print(f\"Simulated {N_PATHS:,} GBM paths over {DAYS} days (seed=7)\")\n",
+ "print(f\" paths matrix shape: {paths.shape}\")\n",
+ "print()\n",
+ "# Theory check: E[S_T] = S0 * exp(mu*T) under GBM\n",
+ "expected_ST = S0 * np.exp(MU * 1.0)\n",
+ "print(f\" Theoretical E[S_T] = S0*exp(mu*T) = {expected_ST:.4f}\")\n",
+ "print(f\" Simulated mean S_T = {terminal.mean():.4f}\")\n",
+ "print(f\" Simulated median S_T = {np.median(terminal):.4f}\")\n",
+ "print()\n",
+ "print(\" (mean > median because the lognormal terminal distribution is right-skewed)\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. The terminal price distribution\n",
+ "\n",
+ "Because log returns are normal, the terminal price `S_T` is **lognormal** — bounded below by zero, with a long right tail. We summarize it with percentiles rather than just mean ± std, since the distribution is asymmetric. The 5th and 95th percentiles bracket a 90% confidence range for where the price lands after one year.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Terminal Distribution"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "S0, MU, SIGMA, DAYS = 100.0, 0.08, 0.20, 252\n",
+ "dt = 1.0 / 252\n",
+ "N_PATHS = 10000\n",
+ "mean_step = (MU - 0.5 * SIGMA**2) * dt\n",
+ "std_step = SIGMA * np.sqrt(dt)\n",
+ "\n",
+ "Z = np.random.normal(size=(N_PATHS, DAYS))\n",
+ "log_price = np.cumsum(mean_step + std_step * Z, axis=1)\n",
+ "terminal = S0 * np.exp(log_price[:, -1])\n",
+ "\n",
+ "pcts = [5, 25, 50, 75, 95]\n",
+ "vals = np.percentile(terminal, pcts)\n",
+ "\n",
+ "dist = pd.DataFrame({\n",
+ " \"statistic\": [\"mean\", \"std\"] + [f\"p{p}\" for p in pcts],\n",
+ " \"price\": [terminal.mean(), terminal.std()] + list(vals),\n",
+ "})\n",
+ "dist[\"return_%\"] = (dist[\"price\"] / S0 - 1.0) * 100\n",
+ "\n",
+ "print(\"Terminal price (S_T) distribution after 1 year\")\n",
+ "print(dist.round(4).to_string(index=False))\n",
+ "print()\n",
+ "print(f\" 90% of outcomes fall between {vals[0]:.2f} (p5) and {vals[-1]:.2f} (p95)\")\n",
+ "print(f\" That is a return range of {(vals[0]/S0-1)*100:.1f}% to {(vals[-1]/S0-1)*100:.1f}%\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. The percentile cone over time\n",
+ "\n",
+ "Uncertainty doesn't arrive all at once — it **widens with the square root of time** (`σ√t`). If we slice the path matrix at several horizons and take percentiles at each, we get a *cone* that fans out from S0. This is the picture you see in fan charts: the median tracks the drift, while the p5/p95 envelope grows steadily wider the further out we look.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Percentile Cone"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "S0, MU, SIGMA, DAYS = 100.0, 0.08, 0.20, 252\n",
+ "dt = 1.0 / 252\n",
+ "N_PATHS = 10000\n",
+ "mean_step = (MU - 0.5 * SIGMA**2) * dt\n",
+ "std_step = SIGMA * np.sqrt(dt)\n",
+ "\n",
+ "Z = np.random.normal(size=(N_PATHS, DAYS))\n",
+ "log_price = np.cumsum(mean_step + std_step * Z, axis=1)\n",
+ "paths = S0 * np.exp(log_price)\n",
+ "paths = np.hstack([np.full((N_PATHS, 1), S0), paths]) # include t=0\n",
+ "\n",
+ "horizons = [0, 21, 63, 126, 189, 252] # ~0, 1m, 3m, 6m, 9m, 12m\n",
+ "rows = []\n",
+ "for h in horizons:\n",
+ " col = paths[:, h]\n",
+ " rows.append({\n",
+ " \"day\": h,\n",
+ " \"p5\": np.percentile(col, 5),\n",
+ " \"p25\": np.percentile(col, 25),\n",
+ " \"p50\": np.percentile(col, 50),\n",
+ " \"p75\": np.percentile(col, 75),\n",
+ " \"p95\": np.percentile(col, 95),\n",
+ " })\n",
+ "cone = pd.DataFrame(rows)\n",
+ "cone[\"p95_minus_p5\"] = cone[\"p95\"] - cone[\"p5\"] # width of the cone\n",
+ "\n",
+ "print(\"Percentile cone of price over time\")\n",
+ "print(cone.round(3).to_string(index=False))\n",
+ "print()\n",
+ "print(\"The (p95 - p5) width grows with horizon ~ sqrt(time): uncertainty compounds.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Value at Risk and downside probability\n",
+ "\n",
+ "Two risk numbers fall straight out of the terminal distribution:\n",
+ "\n",
+ "- **1-year 95% Value at Risk (VaR):** the loss not exceeded with 95% confidence. We take the 5th percentile of the *return* distribution; VaR is the magnitude of that loss. \"There is a 5% chance of losing at least X.\"\n",
+ "- **Probability of ending below S0:** simply the fraction of paths whose terminal price is under the starting price — the chance the year is a net loss.\n",
+ "\n",
+ "These are *historical-free* — they come entirely from the model and its parameters.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "VaR & Shortfall"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "S0, MU, SIGMA, DAYS = 100.0, 0.08, 0.20, 252\n",
+ "dt = 1.0 / 252\n",
+ "N_PATHS = 10000\n",
+ "mean_step = (MU - 0.5 * SIGMA**2) * dt\n",
+ "std_step = SIGMA * np.sqrt(dt)\n",
+ "\n",
+ "Z = np.random.normal(size=(N_PATHS, DAYS))\n",
+ "log_price = np.cumsum(mean_step + std_step * Z, axis=1)\n",
+ "terminal = S0 * np.exp(log_price[:, -1])\n",
+ "\n",
+ "ret = terminal / S0 - 1.0 # 1-year simple return per path\n",
+ "\n",
+ "var95_ret = np.percentile(ret, 5) # 5th percentile of returns\n",
+ "var95_loss = -var95_ret # VaR as a positive loss number\n",
+ "var95_dollars = S0 * var95_loss # on a $S0 position\n",
+ "\n",
+ "# Conditional VaR (expected shortfall): average loss in the worst 5%\n",
+ "cvar95 = -ret[ret <= var95_ret].mean()\n",
+ "\n",
+ "prob_below_S0 = float(np.mean(terminal < S0))\n",
+ "\n",
+ "risk = pd.DataFrame({\n",
+ " \"metric\": [\"95% VaR (return)\", \"95% VaR ($ on 100)\", \"95% CVaR / ES (return)\",\n",
+ " \"P(end < S0)\", \"mean 1y return\"],\n",
+ " \"value\": [f\"{var95_loss*100:.2f}%\", f\"${var95_dollars:.2f}\",\n",
+ " f\"{cvar95*100:.2f}%\", f\"{prob_below_S0*100:.2f}%\",\n",
+ " f\"{ret.mean()*100:.2f}%\"],\n",
+ "})\n",
+ "print(\"1-year risk metrics from the Monte Carlo distribution\")\n",
+ "print(risk.to_string(index=False))\n",
+ "print()\n",
+ "print(f\"Interpretation: with 95% confidence the 1y loss won't exceed {var95_loss*100:.1f}%;\")\n",
+ "print(f\"in the worst 5% of years the average loss is {cvar95*100:.1f}%.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 6. Drift vs diffusion — and the limits of GBM\n",
+ "\n",
+ "The two forces in GBM pull in different ways. **Drift** (`μ`) is the deterministic engine — over long horizons it dominates and pushes the median upward. **Diffusion** (`σ`) is the random shock — it dominates short-horizon outcomes and is what creates the cone's width. Crucially, because shocks compound multiplicatively and volatility imposes the `−½σ²` drag, a high-vol asset can have a *median* return well below its drift even when its *mean* matches it.\n",
+ "\n",
+ "**Where GBM breaks down:** it assumes constant volatility, normally distributed returns, and no jumps. Real markets show fat tails, volatility clustering, and sudden gaps — so true VaR is usually worse than GBM suggests. Still, GBM is the right first model: it is analytically tractable, captures drift + diffusion cleanly, and is the baseline every more-realistic model (stochastic vol, jump-diffusion) is measured against.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/quant_pairs_trading_zscore.ipynb b/fincept-qt/resources/notebooks/quant_pairs_trading_zscore.ipynb
new file mode 100644
index 000000000..9d5f45289
--- /dev/null
+++ b/fincept-qt/resources/notebooks/quant_pairs_trading_zscore.ipynb
@@ -0,0 +1,313 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Pairs Trading: Spread Z-Score\n",
+ "\n",
+ "**Quant · Hard · ~32 min · pandas + numpy**\n",
+ "\n",
+ "Pairs trading is the classic market-neutral, mean-reversion strategy. The idea: find two assets that move together (driven by a shared factor), trade the *spread* between them rather than either one outright, and bet that the spread reverts to its average. When the spread stretches too far from its mean we fade it — short the rich leg, long the cheap leg — and close when it snaps back. Because we hold offsetting long/short legs, the strategy is largely immune to the overall market direction.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- How to generate two cointegrated-ish series from a shared stochastic trend\n",
+ "- How to estimate the hedge ratio β by least squares and build a stationary spread\n",
+ "- How to turn a rolling z-score into entry/exit signals and backtest the P&L (trades, hit rate, return, Sharpe)\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Build two cointegrated price series\n",
+ "\n",
+ "We simulate a **shared stochastic trend** `F` (a random walk — the common factor, like a sector index) and give each asset its own loading on that factor plus **idiosyncratic noise**. Because both prices are driven by the same `F`, their spread is *stationary* (mean-reverting) even though each price wanders. This is the structural setup behind cointegration. All generation is deterministic given `np.random.seed(7)`, so every cell reproduces the identical series.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Generate Pair"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "N = 750 # ~3 years of trading days\n",
+ "\n",
+ "# Shared stochastic trend (common factor) = random walk\n",
+ "factor = np.cumsum(np.random.normal(0.0, 1.0, N)) + 100.0\n",
+ "\n",
+ "# Asset A and B load on the factor with different betas + idiosyncratic noise.\n",
+ "# A mean-reverting spread component is injected so the pair is genuinely cointegrated.\n",
+ "noise_a = np.random.normal(0.0, 0.6, N)\n",
+ "noise_b = np.random.normal(0.0, 0.6, N)\n",
+ "\n",
+ "A = 1.0 * factor + 20.0 + noise_a\n",
+ "B = 0.6 * factor + 50.0 + noise_b\n",
+ "\n",
+ "prices = pd.DataFrame({\"A\": A, \"B\": B})\n",
+ "\n",
+ "print(f\"Generated {N} days of two cointegrated-ish prices (seed=7)\")\n",
+ "print()\n",
+ "print(\"Head:\")\n",
+ "print(prices.head().round(4).to_string())\n",
+ "print()\n",
+ "print(\"Describe:\")\n",
+ "print(prices.describe().round(4).to_string())\n",
+ "print()\n",
+ "print(f\"Correlation of A and B levels: {prices['A'].corr(prices['B']):.4f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Estimate the hedge ratio β\n",
+ "\n",
+ "We can't just trade `A − B`; the legs must be *dollar-balanced* in their factor exposure. We regress `A` on `B` by ordinary least squares to get the **hedge ratio β** (and an intercept α):\n",
+ "\n",
+ "$$A_t = \\alpha + \\beta\\, B_t + \\varepsilon_t$$\n",
+ "\n",
+ "The residual `ε_t = A_t − α − β B_t` is the **spread**. If A and B are cointegrated, this spread is stationary — it has a stable mean and reverts to it. We estimate β with `np.polyfit` (degree-1 least squares) and confirm the spread is mean-zero and well-behaved.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Hedge Ratio & Spread"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "N = 750\n",
+ "factor = np.cumsum(np.random.normal(0.0, 1.0, N)) + 100.0\n",
+ "noise_a = np.random.normal(0.0, 0.6, N)\n",
+ "noise_b = np.random.normal(0.0, 0.6, N)\n",
+ "A = 1.0 * factor + 20.0 + noise_a\n",
+ "B = 0.6 * factor + 50.0 + noise_b\n",
+ "\n",
+ "# OLS regression of A on B: A = alpha + beta*B (polyfit returns [slope, intercept])\n",
+ "beta, alpha = np.polyfit(B, A, 1)\n",
+ "\n",
+ "spread = A - (alpha + beta * B) # residual = stationary spread\n",
+ "\n",
+ "print(\"Least-squares hedge ratio (A regressed on B)\")\n",
+ "print(f\" beta = {beta:.4f} (true factor-loading ratio = 1.0/0.6 = {1.0/0.6:.4f})\")\n",
+ "print(f\" alpha = {alpha:.4f}\")\n",
+ "print()\n",
+ "print(\"Spread = A - (alpha + beta*B)\")\n",
+ "print(f\" mean = {spread.mean():.6f} (should be ~0 by construction of OLS residual)\")\n",
+ "print(f\" std = {spread.std():.4f}\")\n",
+ "print(f\" min = {spread.min():.4f} max = {spread.max():.4f}\")\n",
+ "print()\n",
+ "# Quick stationarity intuition: lag-1 autocorrelation well below 1 => mean-reverting\n",
+ "s = pd.Series(spread)\n",
+ "print(f\" lag-1 autocorrelation of spread = {s.autocorr(1):.4f} (<<1 => mean-reverting)\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Rolling z-score of the spread\n",
+ "\n",
+ "To decide when the spread is \"too far\" from its mean we standardize it into a **z-score** using a *rolling* window (so the strategy only ever uses information available up to that day — no look-ahead):\n",
+ "\n",
+ "$$z_t = \\frac{\\text{spread}_t - \\text{mean}_{t-w..t}}{\\text{std}_{t-w..t}}$$\n",
+ "\n",
+ "A z-score of +2 means the spread sits two rolling standard deviations *above* normal — A is rich relative to B, a signal to short the spread. We use a 60-day window.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Rolling Z-Score"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "N = 750\n",
+ "factor = np.cumsum(np.random.normal(0.0, 1.0, N)) + 100.0\n",
+ "noise_a = np.random.normal(0.0, 0.6, N)\n",
+ "noise_b = np.random.normal(0.0, 0.6, N)\n",
+ "A = 1.0 * factor + 20.0 + noise_a\n",
+ "B = 0.6 * factor + 50.0 + noise_b\n",
+ "beta, alpha = np.polyfit(B, A, 1)\n",
+ "spread = pd.Series(A - (alpha + beta * B))\n",
+ "\n",
+ "WIN = 60\n",
+ "roll_mean = spread.rolling(WIN).mean()\n",
+ "roll_std = spread.rolling(WIN).std()\n",
+ "zscore = (spread - roll_mean) / roll_std\n",
+ "\n",
+ "df = pd.DataFrame({\"spread\": spread, \"roll_mean\": roll_mean,\n",
+ " \"roll_std\": roll_std, \"zscore\": zscore})\n",
+ "\n",
+ "valid = df.dropna()\n",
+ "print(f\"Rolling z-score with {WIN}-day window\")\n",
+ "print(f\" valid (post-warmup) observations: {len(valid)} of {len(df)}\")\n",
+ "print()\n",
+ "print(\"Z-score distribution:\")\n",
+ "print(valid[\"zscore\"].describe().round(4).to_string())\n",
+ "print()\n",
+ "print(f\" days with z > +2 : {(valid['zscore'] > 2).sum()}\")\n",
+ "print(f\" days with z < -2 : {(valid['zscore'] < -2).sum()}\")\n",
+ "print()\n",
+ "print(\"Tail of the z-score frame:\")\n",
+ "print(df.tail(8).round(4).to_string())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Signals and backtest\n",
+ "\n",
+ "The trading rules, applied to the **spread position** (where +1 = long the spread = long A / short β·B, and −1 = short the spread):\n",
+ "\n",
+ "- **Enter short spread** (position = −1) when `z > +2` (spread too high, expect it to fall).\n",
+ "- **Enter long spread** (position = +1) when `z < −2` (spread too low, expect it to rise).\n",
+ "- **Exit to flat** (position = 0) when `|z| < 0.5` (reverted to the mean).\n",
+ "- Otherwise **hold** the current position.\n",
+ "\n",
+ "We carry the position forward and earn the **change in spread × position held yesterday** (trade on tomorrow's move, not today's — no look-ahead). We then tally trades, hit rate, total return, and an annualized Sharpe of the daily strategy P&L.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "fincept_title": "Signals & P&L"
+ },
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "np.random.seed(7)\n",
+ "\n",
+ "N = 750\n",
+ "factor = np.cumsum(np.random.normal(0.0, 1.0, N)) + 100.0\n",
+ "noise_a = np.random.normal(0.0, 0.6, N)\n",
+ "noise_b = np.random.normal(0.0, 0.6, N)\n",
+ "A = 1.0 * factor + 20.0 + noise_a\n",
+ "B = 0.6 * factor + 50.0 + noise_b\n",
+ "beta, alpha = np.polyfit(B, A, 1)\n",
+ "spread = pd.Series(A - (alpha + beta * B))\n",
+ "\n",
+ "WIN = 60\n",
+ "ENTRY, EXIT = 2.0, 0.5\n",
+ "z = (spread - spread.rolling(WIN).mean()) / spread.rolling(WIN).std()\n",
+ "\n",
+ "# Build positions with a stateful pass over the z-score\n",
+ "pos = np.zeros(len(z))\n",
+ "cur = 0\n",
+ "for t in range(len(z)):\n",
+ " zt = z.iloc[t]\n",
+ " if np.isnan(zt):\n",
+ " cur = 0\n",
+ " elif cur == 0:\n",
+ " if zt > ENTRY: cur = -1 # short the spread\n",
+ " elif zt < -ENTRY: cur = +1 # long the spread\n",
+ " else:\n",
+ " if abs(zt) < EXIT: cur = 0 # revert -> exit flat\n",
+ " pos[t] = cur\n",
+ "position = pd.Series(pos, index=z.index)\n",
+ "\n",
+ "# P&L: yesterday's position earns today's spread change (no look-ahead)\n",
+ "dspread = spread.diff()\n",
+ "pnl = position.shift(1) * dspread\n",
+ "pnl = pnl.fillna(0.0)\n",
+ "\n",
+ "# Trade accounting: a trade is a transition into a non-zero position\n",
+ "entries = ((position != 0) & (position.shift(1).fillna(0) == 0))\n",
+ "n_trades = int(entries.sum())\n",
+ "\n",
+ "# Per-trade P&L: sum pnl over each holding episode\n",
+ "trade_id = entries.cumsum().where(position != 0)\n",
+ "trade_pnl = pnl.groupby(trade_id).sum()\n",
+ "wins = int((trade_pnl > 0).sum())\n",
+ "hit_rate = wins / n_trades if n_trades else float(\"nan\")\n",
+ "\n",
+ "total_return = float(pnl.sum())\n",
+ "daily = pnl[position.shift(1).fillna(0) != 0] # P&L only while positioned\n",
+ "sharpe = (daily.mean() / daily.std() * np.sqrt(252)) if daily.std() > 0 else float(\"nan\")\n",
+ "\n",
+ "print(\"=== Pairs strategy backtest ===\")\n",
+ "metrics = pd.DataFrame({\n",
+ " \"metric\": [\"# trades\", \"# winning trades\", \"hit rate\",\n",
+ " \"total spread P&L\", \"avg P&L / trade\", \"annualized Sharpe\"],\n",
+ " \"value\": [n_trades, wins, f\"{hit_rate:.2%}\",\n",
+ " f\"{total_return:.4f}\", f\"{trade_pnl.mean():.4f}\", f\"{sharpe:.4f}\"],\n",
+ "})\n",
+ "print(metrics.to_string(index=False))\n",
+ "print()\n",
+ "sig = pd.DataFrame({\"spread\": spread, \"zscore\": z,\n",
+ " \"position\": position, \"pnl\": pnl})\n",
+ "print(\"Tail of signals / P&L frame:\")\n",
+ "print(sig.tail(10).round(4).to_string())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. Reading the results\n",
+ "\n",
+ "A working pairs strategy on a genuinely cointegrated pair should show a positive total spread P&L, a hit rate comfortably above 50%, and a Sharpe materially above zero — earned with low correlation to the broad market because every position is a hedged long/short. The z-score thresholds are the key tuning knobs: a wider entry band (e.g. ±2.5) trades less often but with higher conviction; a tighter exit band holds longer for fuller reversion.\n",
+ "\n",
+ "**Real-world cautions:** cointegration can *break* — if the structural link between the two names dissolves, the spread trends instead of reverting and the strategy bleeds. Production systems re-estimate β on a rolling window, monitor the spread with a formal stationarity test (ADF), add stop-losses, and account for transaction costs and borrow fees on the short leg. The z-score engine you built here is the core; risk management is what keeps it alive.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/trading_first_watchlist.ipynb b/fincept-qt/resources/notebooks/trading_first_watchlist.ipynb
new file mode 100644
index 000000000..298eb1186
--- /dev/null
+++ b/fincept-qt/resources/notebooks/trading_first_watchlist.ipynb
@@ -0,0 +1,187 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Your First Watchlist & Returns\n",
+ "\n",
+ "**Trading · Beginner · ~12 min · Standard library only**\n",
+ "\n",
+ "A *watchlist* is just a handful of tickers you track. In this notebook we attach a short price history to each, compute the returns and risk that every trader looks at first, and rank the names on a clean leaderboard — all with Python's standard library, no extra packages.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- Turn daily closing prices into daily returns and a cumulative return\n",
+ "- Measure average return and volatility with the `statistics` module\n",
+ "- Rank a watchlist by performance and by risk, and read a leaderboard\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. The watchlist\n",
+ "\n",
+ "Our watchlist holds four tickers, each with twelve daily closing prices (oldest first). In a real terminal these would stream from a data feed; here we embed them so every cell runs offline and deterministically.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Define watchlist"},
+ "outputs": [],
+ "source": [
+ "WATCHLIST = {\n",
+ " \"AAPL\": [188.0, 189.5, 191.2, 190.1, 192.8, 195.0, 194.2, 196.5, 198.0, 197.1, 199.4, 201.0],\n",
+ " \"MSFT\": [410.0, 412.5, 411.0, 415.8, 418.2, 416.0, 420.5, 422.1, 419.7, 423.4, 425.0, 427.8],\n",
+ " \"TSLA\": [240.0, 235.5, 244.0, 238.2, 250.1, 246.8, 255.0, 248.3, 260.5, 254.0, 249.7, 262.4],\n",
+ " \"KO\": [60.1, 60.3, 60.0, 60.5, 60.4, 60.7, 60.6, 60.9, 61.0, 60.8, 61.2, 61.1],\n",
+ "}\n",
+ "\n",
+ "print(\"Watchlist — 12 daily closes per ticker (oldest -> newest)\")\n",
+ "print(\"=\" * 58)\n",
+ "for ticker, closes in WATCHLIST.items():\n",
+ " print(f\"{ticker:<5} first={closes[0]:>7.2f} last={closes[-1]:>7.2f} n={len(closes)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Daily returns and cumulative return\n",
+ "\n",
+ "A **simple daily return** is the percentage change from one close to the next: `(today − yesterday) / yesterday`. The **cumulative return** is the total gain over the whole window, `last / first − 1`. These are the two numbers a trader checks first.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Compute returns"},
+ "outputs": [],
+ "source": [
+ "WATCHLIST = {\n",
+ " \"AAPL\": [188.0, 189.5, 191.2, 190.1, 192.8, 195.0, 194.2, 196.5, 198.0, 197.1, 199.4, 201.0],\n",
+ " \"MSFT\": [410.0, 412.5, 411.0, 415.8, 418.2, 416.0, 420.5, 422.1, 419.7, 423.4, 425.0, 427.8],\n",
+ " \"TSLA\": [240.0, 235.5, 244.0, 238.2, 250.1, 246.8, 255.0, 248.3, 260.5, 254.0, 249.7, 262.4],\n",
+ " \"KO\": [60.1, 60.3, 60.0, 60.5, 60.4, 60.7, 60.6, 60.9, 61.0, 60.8, 61.2, 61.1],\n",
+ "}\n",
+ "\n",
+ "def daily_returns(closes):\n",
+ " return [(closes[i] - closes[i - 1]) / closes[i - 1] for i in range(1, len(closes))]\n",
+ "\n",
+ "print(\"Daily returns (%) per ticker\")\n",
+ "print(\"=\" * 70)\n",
+ "for ticker, closes in WATCHLIST.items():\n",
+ " rets = daily_returns(closes)\n",
+ " cum = closes[-1] / closes[0] - 1\n",
+ " pretty = \" \".join(f\"{r * 100:+5.2f}\" for r in rets)\n",
+ " print(f\"{ticker:<5} {pretty}\")\n",
+ " print(f\" cumulative return over window: {cum * 100:+6.2f}%\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Average return and volatility\n",
+ "\n",
+ "Return alone tells you nothing about *risk*. **Volatility** — the spread of the daily returns — does. We use `statistics.mean` for the average daily return and `statistics.pstdev` (population standard deviation) for volatility. Higher volatility means a bumpier ride for the same average gain.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Mean & volatility"},
+ "outputs": [],
+ "source": [
+ "import statistics\n",
+ "\n",
+ "WATCHLIST = {\n",
+ " \"AAPL\": [188.0, 189.5, 191.2, 190.1, 192.8, 195.0, 194.2, 196.5, 198.0, 197.1, 199.4, 201.0],\n",
+ " \"MSFT\": [410.0, 412.5, 411.0, 415.8, 418.2, 416.0, 420.5, 422.1, 419.7, 423.4, 425.0, 427.8],\n",
+ " \"TSLA\": [240.0, 235.5, 244.0, 238.2, 250.1, 246.8, 255.0, 248.3, 260.5, 254.0, 249.7, 262.4],\n",
+ " \"KO\": [60.1, 60.3, 60.0, 60.5, 60.4, 60.7, 60.6, 60.9, 61.0, 60.8, 61.2, 61.1],\n",
+ "}\n",
+ "\n",
+ "def daily_returns(closes):\n",
+ " return [(closes[i] - closes[i - 1]) / closes[i - 1] for i in range(1, len(closes))]\n",
+ "\n",
+ "print(f\"{'Ticker':<8}{'Mean daily':>12}{'Volatility':>12}{'Cumulative':>12}\")\n",
+ "print(\"=\" * 44)\n",
+ "for ticker, closes in WATCHLIST.items():\n",
+ " rets = daily_returns(closes)\n",
+ " mean_r = statistics.mean(rets)\n",
+ " vol = statistics.pstdev(rets)\n",
+ " cum = closes[-1] / closes[0] - 1\n",
+ " print(f\"{ticker:<8}{mean_r * 100:>11.3f}%{vol * 100:>11.3f}%{cum * 100:>11.2f}%\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. The leaderboard\n",
+ "\n",
+ "Finally we rank the watchlist two ways: by **cumulative return** (who made the most) and by **volatility** (who was calmest). The best name combines a high return with low risk — but those two rarely come together, which is the whole game of investing.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Leaderboard"},
+ "outputs": [],
+ "source": [
+ "import statistics\n",
+ "\n",
+ "WATCHLIST = {\n",
+ " \"AAPL\": [188.0, 189.5, 191.2, 190.1, 192.8, 195.0, 194.2, 196.5, 198.0, 197.1, 199.4, 201.0],\n",
+ " \"MSFT\": [410.0, 412.5, 411.0, 415.8, 418.2, 416.0, 420.5, 422.1, 419.7, 423.4, 425.0, 427.8],\n",
+ " \"TSLA\": [240.0, 235.5, 244.0, 238.2, 250.1, 246.8, 255.0, 248.3, 260.5, 254.0, 249.7, 262.4],\n",
+ " \"KO\": [60.1, 60.3, 60.0, 60.5, 60.4, 60.7, 60.6, 60.9, 61.0, 60.8, 61.2, 61.1],\n",
+ "}\n",
+ "\n",
+ "def daily_returns(closes):\n",
+ " return [(closes[i] - closes[i - 1]) / closes[i - 1] for i in range(1, len(closes))]\n",
+ "\n",
+ "stats = {}\n",
+ "for ticker, closes in WATCHLIST.items():\n",
+ " rets = daily_returns(closes)\n",
+ " stats[ticker] = {\"cum\": closes[-1] / closes[0] - 1, \"vol\": statistics.pstdev(rets)}\n",
+ "\n",
+ "by_return = sorted(stats.items(), key=lambda kv: kv[1][\"cum\"], reverse=True)\n",
+ "by_vol = sorted(stats.items(), key=lambda kv: kv[1][\"vol\"]) # calmest first\n",
+ "\n",
+ "print(\"LEADERBOARD — best total return\")\n",
+ "print(\"=\" * 40)\n",
+ "for rank, (ticker, s) in enumerate(by_return, 1):\n",
+ " print(f\" #{rank} {ticker:<5} {s['cum'] * 100:+6.2f}%\")\n",
+ "\n",
+ "print()\n",
+ "print(\"LEADERBOARD — lowest volatility (calmest)\")\n",
+ "print(\"=\" * 40)\n",
+ "for rank, (ticker, s) in enumerate(by_vol, 1):\n",
+ " print(f\" #{rank} {ticker:<5} {s['vol'] * 100:5.3f}% daily\")\n",
+ "\n",
+ "top = by_return[0][0]\n",
+ "calm = by_vol[0][0]\n",
+ "print()\n",
+ "print(f\"Top performer: {top}. Calmest name: {calm}.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
+ "language_info": {"name": "python"}
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/notebooks/trading_sma_crossover_backtest.ipynb b/fincept-qt/resources/notebooks/trading_sma_crossover_backtest.ipynb
new file mode 100644
index 000000000..2aac2a7e6
--- /dev/null
+++ b/fincept-qt/resources/notebooks/trading_sma_crossover_backtest.ipynb
@@ -0,0 +1,240 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 📘 Fincept Notebook — Moving Average Crossover Backtest\n",
+ "\n",
+ "**Trading · Intermediate · ~22 min · pandas + numpy**\n",
+ "\n",
+ "The moving-average crossover is the classic trend-following strategy: go long when a fast average crosses above a slow one, and step aside when it crosses back below. In this notebook we generate a reproducible price series, build the signals with pandas, and *backtest* the strategy against simply buying and holding.\n",
+ "\n",
+ "**What you'll learn**\n",
+ "- Compute fast/slow simple moving averages with pandas `rolling`\n",
+ "- Turn a crossover into long/flat signals and lag them to avoid look-ahead bias\n",
+ "- Build equity curves and compare strategy vs buy-and-hold\n",
+ "- Report total & annualized return, max drawdown, and a simple Sharpe ratio\n",
+ "\n",
+ "> **Requires** `pandas` and `numpy` (bundled with Fincept Terminal's Python environment).\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. A reproducible price series\n",
+ "\n",
+ "We synthesise 120 trading days of prices with a gentle upward **drift** plus daily **noise**, using `np.random.seed(7)` so the series is identical every run — and identical in every cell, since each cell regenerates it from the same seed. The result is a single random walk that trends up but with realistic pullbacks for the crossover to react to.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Generate prices"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "def make_prices(n=120, start=100.0, drift=0.0006, vol=0.012, seed=7):\n",
+ " np.random.seed(seed)\n",
+ " shocks = np.random.normal(drift, vol, n)\n",
+ " prices = start * np.cumprod(1 + shocks)\n",
+ " dates = pd.bdate_range(\"2024-01-01\", periods=n)\n",
+ " return pd.Series(prices, index=dates, name=\"close\")\n",
+ "\n",
+ "px = make_prices()\n",
+ "print(\"Synthetic daily closes (120 business days)\")\n",
+ "print(\"=\" * 44)\n",
+ "print(f\"start {px.iloc[0]:8.2f}\")\n",
+ "print(f\"end {px.iloc[-1]:8.2f}\")\n",
+ "print(f\"min {px.min():8.2f}\")\n",
+ "print(f\"max {px.max():8.2f}\")\n",
+ "print()\n",
+ "print(\"First 5 closes:\")\n",
+ "print(px.head().to_string())\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Fast & slow moving averages and the signal\n",
+ "\n",
+ "We compute a **fast SMA (10-day)** and a **slow SMA (30-day)** with `Series.rolling(window).mean()`. The position is **long (1)** whenever the fast SMA is above the slow SMA, otherwise **flat (0)**. Critically we `shift(1)` the signal: you can only act on a crossover the *next* day, so trading on today's bar with today's signal would be cheating (look-ahead bias).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "SMAs & signal"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "def make_prices(n=120, start=100.0, drift=0.0006, vol=0.012, seed=7):\n",
+ " np.random.seed(seed)\n",
+ " shocks = np.random.normal(drift, vol, n)\n",
+ " prices = start * np.cumprod(1 + shocks)\n",
+ " return pd.Series(prices, index=pd.bdate_range(\"2024-01-01\", periods=n), name=\"close\")\n",
+ "\n",
+ "FAST, SLOW = 10, 30\n",
+ "df = make_prices().to_frame()\n",
+ "df[\"sma_fast\"] = df[\"close\"].rolling(FAST).mean()\n",
+ "df[\"sma_slow\"] = df[\"close\"].rolling(SLOW).mean()\n",
+ "df[\"signal\"] = (df[\"sma_fast\"] > df[\"sma_slow\"]).astype(int)\n",
+ "df[\"position\"] = df[\"signal\"].shift(1).fillna(0) # act next day\n",
+ "\n",
+ "trades = int((df[\"position\"].diff().abs() > 0).sum())\n",
+ "print(f\"Crossover signals (FAST={FAST}, SLOW={SLOW}) — tail of the table\")\n",
+ "print(\"=\" * 60)\n",
+ "print(df.tail(8).round(2).to_string())\n",
+ "print()\n",
+ "print(f\"Days long: {int(df['position'].sum())} of {len(df)} | position changes: {trades}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Equity curves: strategy vs buy-and-hold\n",
+ "\n",
+ "The market's daily return is `close.pct_change()`. The strategy only earns that return on days it was positioned long, so `strategy_return = position * market_return`. Compounding each stream gives an **equity curve** (growth of \\$1). We compare the crossover strategy with simply buying and holding from day one.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Equity curves"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "def make_prices(n=120, start=100.0, drift=0.0006, vol=0.012, seed=7):\n",
+ " np.random.seed(seed)\n",
+ " shocks = np.random.normal(drift, vol, n)\n",
+ " prices = start * np.cumprod(1 + shocks)\n",
+ " return pd.Series(prices, index=pd.bdate_range(\"2024-01-01\", periods=n), name=\"close\")\n",
+ "\n",
+ "FAST, SLOW = 10, 30\n",
+ "df = make_prices().to_frame()\n",
+ "df[\"sma_fast\"] = df[\"close\"].rolling(FAST).mean()\n",
+ "df[\"sma_slow\"] = df[\"close\"].rolling(SLOW).mean()\n",
+ "df[\"position\"] = (df[\"sma_fast\"] > df[\"sma_slow\"]).astype(int).shift(1).fillna(0)\n",
+ "\n",
+ "df[\"mkt_ret\"] = df[\"close\"].pct_change().fillna(0)\n",
+ "df[\"strat_ret\"] = df[\"position\"] * df[\"mkt_ret\"]\n",
+ "df[\"equity_hold\"] = (1 + df[\"mkt_ret\"]).cumprod()\n",
+ "df[\"equity_strat\"] = (1 + df[\"strat_ret\"]).cumprod()\n",
+ "\n",
+ "print(\"Growth of $1 — last 8 days\")\n",
+ "print(\"=\" * 44)\n",
+ "print(df[[\"close\", \"position\", \"equity_hold\", \"equity_strat\"]].tail(8).round(3).to_string())\n",
+ "print()\n",
+ "print(f\"Final $1 -> buy & hold : ${df['equity_hold'].iloc[-1]:.3f}\")\n",
+ "print(f\"Final $1 -> crossover : ${df['equity_strat'].iloc[-1]:.3f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Performance metrics\n",
+ "\n",
+ "Numbers, not vibes. We report for each approach:\n",
+ "\n",
+ "- **Total return** — final equity minus 1.\n",
+ "- **Annualized return** — geometric, scaled to 252 trading days.\n",
+ "- **Max drawdown** — the worst peak-to-trough loss along the equity curve.\n",
+ "- **Sharpe ratio** — mean daily return / daily volatility, annualized by √252 (risk-free assumed 0).\n",
+ "\n",
+ "Trend-following often trails buy-and-hold in a smoothly rising market because it sits in cash during pullbacks — but it usually suffers a *smaller drawdown*, which is the trade-off this table makes visible.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {"fincept_title": "Metrics table"},
+ "outputs": [],
+ "source": [
+ "try:\n",
+ " import numpy as np\n",
+ " import pandas as pd\n",
+ "except ImportError:\n",
+ " raise SystemExit(\"Fincept Notebook needs pandas + numpy — install with: pip install pandas numpy\")\n",
+ "\n",
+ "def make_prices(n=120, start=100.0, drift=0.0006, vol=0.012, seed=7):\n",
+ " np.random.seed(seed)\n",
+ " shocks = np.random.normal(drift, vol, n)\n",
+ " prices = start * np.cumprod(1 + shocks)\n",
+ " return pd.Series(prices, index=pd.bdate_range(\"2024-01-01\", periods=n), name=\"close\")\n",
+ "\n",
+ "FAST, SLOW = 10, 30\n",
+ "df = make_prices().to_frame()\n",
+ "df[\"sma_fast\"] = df[\"close\"].rolling(FAST).mean()\n",
+ "df[\"sma_slow\"] = df[\"close\"].rolling(SLOW).mean()\n",
+ "df[\"position\"] = (df[\"sma_fast\"] > df[\"sma_slow\"]).astype(int).shift(1).fillna(0)\n",
+ "df[\"mkt_ret\"] = df[\"close\"].pct_change().fillna(0)\n",
+ "df[\"strat_ret\"] = df[\"position\"] * df[\"mkt_ret\"]\n",
+ "\n",
+ "def max_drawdown(returns):\n",
+ " equity = (1 + returns).cumprod()\n",
+ " peak = equity.cummax()\n",
+ " return ((equity - peak) / peak).min()\n",
+ "\n",
+ "def metrics(returns):\n",
+ " n = len(returns)\n",
+ " total = (1 + returns).prod() - 1\n",
+ " ann = (1 + total) ** (252 / n) - 1\n",
+ " vol = returns.std(ddof=0)\n",
+ " sharpe = (returns.mean() / vol * np.sqrt(252)) if vol > 0 else float(\"nan\")\n",
+ " return total, ann, max_drawdown(returns), sharpe\n",
+ "\n",
+ "rows = []\n",
+ "for name, col in [(\"Buy & hold\", \"mkt_ret\"), (\"SMA crossover\", \"strat_ret\")]:\n",
+ " total, ann, mdd, sharpe = metrics(df[col])\n",
+ " rows.append({\n",
+ " \"Strategy\": name,\n",
+ " \"Total %\": round(total * 100, 2),\n",
+ " \"Annualized %\": round(ann * 100, 2),\n",
+ " \"Max DD %\": round(mdd * 100, 2),\n",
+ " \"Sharpe\": round(sharpe, 2),\n",
+ " })\n",
+ "\n",
+ "table = pd.DataFrame(rows).set_index(\"Strategy\")\n",
+ "print(\"Backtest performance metrics\")\n",
+ "print(\"=\" * 60)\n",
+ "print(table.to_string())\n",
+ "print()\n",
+ "print(\"Note: a single random path is not evidence — robust backtesting runs\")\n",
+ "print(\"many paths and includes costs, slippage, and out-of-sample testing.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "*— Fincept Notebook · part of Fincept Terminal. Edit any cell and press Ctrl+Enter to run.*\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
+ "language_info": {"name": "python"}
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/fincept-qt/resources/requirements-numpy1.txt b/fincept-qt/resources/requirements-numpy1.txt
index f6a6a7e4f..725e90428 100644
--- a/fincept-qt/resources/requirements-numpy1.txt
+++ b/fincept-qt/resources/requirements-numpy1.txt
@@ -2,6 +2,9 @@
# These libraries are incompatible with NumPy 2.x
# Core dependencies
+# numpy + pandas also power the prebuilt Fincept Notebook library
+# (Intermediate/Hard notebooks under resources/notebooks/). Beginner notebooks
+# use the Python standard library only and need no packages.
numpy>=1.26.4,<2.0
pandas>=2.0.0,<2.3.0
diff --git a/fincept-qt/resources/requirements-numpy2.txt b/fincept-qt/resources/requirements-numpy2.txt
index 0bd821c40..3a8e070d6 100644
--- a/fincept-qt/resources/requirements-numpy2.txt
+++ b/fincept-qt/resources/requirements-numpy2.txt
@@ -2,6 +2,9 @@
# All libraries compatible with NumPy 2.x
# Core dependencies
+# numpy + pandas also power the prebuilt Fincept Notebook library
+# (Intermediate/Hard notebooks under resources/notebooks/). Beginner notebooks
+# use the Python standard library only and need no packages.
numpy>=2.2.3,<3.0
pandas>=2.3.3,<3.0
diff --git a/fincept-qt/src/algo_engine/CandleDataFetcher.cpp b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
index 9a0ddd8c0..87add83a3 100644
--- a/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
+++ b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
@@ -3,6 +3,7 @@
#include "core/logging/Logger.h"
#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
+#include "trading/HistoricalDataService.h"
#include "trading/instruments/InstrumentService.h"
#include <QDateTime>
@@ -137,73 +138,7 @@ QVector<OhlcvCandle> parse_yahoo_chart(const QJsonObject& root, int64_t tf_ms, Q
}
// ── Broker symbol resolution ─────────────────────────────────────────────────
-// Most broker get_history() implementations need more than a bare symbol:
-// - token brokers want EXCHANGE:SYMBOL:TOKEN (numeric instrument_token);
-// - tradejini wants the scrip id at parts[1];
-// - the rest resolve EXCHANGE:SYMBOL internally.
-// We resolve via InstrumentService (warming its cache on a worker thread if
-// needed). Unresolvable token brokers return "" so the caller skips to Yahoo.
-
-const QSet<QString>& brokers_needing_token() {
- static const QSet<QString> s = {
- QStringLiteral("motilal"), QStringLiteral("aliceblue"), QStringLiteral("fivepaisa"),
- QStringLiteral("iifl"), QStringLiteral("ibkr"), QStringLiteral("saxobank"),
- };
- return s;
-}
-
-// Worker-thread-safe synchronous instrument load. Uses the worker-safe loader
-// (private named connection); never the main-thread load_from_db().
-bool ensure_instruments_loaded_blocking(const QString& broker_id) {
- auto& svc = fincept::trading::InstrumentService::instance();
- if (svc.is_loaded(broker_id))
- return true;
- svc.load_from_db_worker(broker_id);
- return svc.is_loaded(broker_id);
-}
-
-// Build the symbol string <broker_id>::get_history expects. Empty result means a
-// token was required but could not be resolved (caller should fall back to Yahoo).
-QString resolve_broker_symbol(const QString& broker_id, const QString& bare_symbol,
- const QString& exchange) {
- using fincept::trading::InstrumentService;
- if (bare_symbol.contains(':')) // already fully qualified by caller
- return bare_symbol;
- const QString sym = bare_symbol.trimmed().toUpper();
- const QString exch = exchange.isEmpty() ? QStringLiteral("NSE") : exchange.toUpper();
-
- if (broker_id == QStringLiteral("tradejini")) { // get_history reads parts[1]
- if (ensure_instruments_loaded_blocking(broker_id)) {
- auto inst = InstrumentService::instance().find(sym, exch, broker_id);
- if (inst) {
- const QString symid =
- inst->brsymbol.isEmpty() ? QString::number(inst->instrument_token) : inst->brsymbol;
- return exch + ":" + symid;
- }
- }
- return exch + ":" + sym; // best-effort
- }
- if (brokers_needing_token().contains(broker_id)) { // EXCHANGE:SYMBOL:TOKEN
- if (!ensure_instruments_loaded_blocking(broker_id))
- return {};
- auto tok = InstrumentService::instance().instrument_token(sym, exch, broker_id);
- if (!tok.has_value() || tok.value() <= 0)
- return {};
- return exch + ":" + sym + ":" + QString::number(tok.value());
- }
- // Brokers whose get_history resolves the symbol internally via InstrumentService
- // (numeric token lookup) — warm the cache so that lookup succeeds, but pass the
- // BARE symbol: they default the exchange to NSE and a colon-form is unnecessary.
- static const QSet<QString> kInternalResolvers = {
- QStringLiteral("zerodha"), QStringLiteral("angelone"),
- QStringLiteral("dhan"), QStringLiteral("upstox"),
- };
- if (kInternalResolvers.contains(broker_id))
- ensure_instruments_loaded_blocking(broker_id);
- // Everyone else accepts the bare symbol as-is (Fyers/Groww format it themselves;
- // Alpaca/Tradier/MetaApi want a plain ticker). Preserve the original string.
- return bare_symbol;
-}
+// Broker symbol resolution + token handling moved to trading/HistoricalDataService.
} // namespace
@@ -338,69 +273,18 @@ void CandleDataFetcher::fetch_multi(const QStringList& symbols, const QString& t
void CandleDataFetcher::fetch_from_broker(const QString& symbol, const QString& timeframe,
int lookback_days, const QString& broker_id,
const QString& account_id, CandleCallback callback) {
- QPointer<CandleDataFetcher> self = this;
- QtConcurrent::run([self, symbol, timeframe, lookback_days, broker_id, account_id, callback]() {
- auto* broker = trading::BrokerRegistry::instance().get(broker_id);
- if (!broker) {
- QMetaObject::invokeMethod(self, [callback]() {
- callback(false, {}, QStringLiteral("Broker not found"));
- }, Qt::QueuedConnection);
- return;
- }
-
- auto creds = trading::AccountManager::instance().load_credentials(account_id);
- if (creds.api_key.isEmpty()) {
- QMetaObject::invokeMethod(self, [callback]() {
- callback(false, {}, QStringLiteral("No credentials"));
- }, Qt::QueuedConnection);
- return;
- }
-
- const QDateTime to = QDateTime::currentDateTime();
- const QDateTime from = to.addDays(-lookback_days);
- const QString resolution = timeframe_to_broker_resolution(timeframe);
- const QString from_s = from.toString("yyyy-MM-dd");
- const QString to_s = to.toString("yyyy-MM-dd");
-
- // Build the broker-specific symbol string (EXCHANGE:SYMBOL[:TOKEN]); empty
- // means a token broker we couldn't resolve — fall straight through to Yahoo.
- const QString resolved = resolve_broker_symbol(broker_id, symbol, QStringLiteral("NSE"));
-
- auto has_data = [](const trading::ApiResponse<QVector<trading::BrokerCandle>>& r) {
- return r.success && r.data.value_or(QVector<trading::BrokerCandle>{}).size() > 0;
- };
-
- trading::ApiResponse<QVector<trading::BrokerCandle>> result;
- QString last_err;
- if (!resolved.isEmpty()) {
- result = broker->get_history(creds, resolved, resolution, from_s, to_s);
- if (!result.success)
- last_err = result.error;
- } else {
- last_err = QStringLiteral("symbol resolution failed (no instrument token)");
- }
- // Fallback: retry with the bare symbol if the resolved form yielded nothing.
- if (!has_data(result) && resolved != symbol) {
- auto r2 = broker->get_history(creds, symbol, resolution, from_s, to_s);
- if (has_data(r2))
- result = r2;
- else if (last_err.isEmpty())
- last_err = r2.error;
- }
-
- if (!self) return;
- if (has_data(result)) {
- auto candles = broker_candles_to_ohlcv(result.data.value_or(QVector<trading::BrokerCandle>{}), timeframe);
- QMetaObject::invokeMethod(self, [callback, candles]() {
- callback(true, candles, {});
- }, Qt::QueuedConnection);
- } else {
- const QString err = last_err.isEmpty() ? QStringLiteral("No data") : last_err;
- QMetaObject::invokeMethod(self, [callback, err]() {
+ // Broker history (symbol resolution + bare-symbol fallback + cache) now lives
+ // in the shared trading::HistoricalDataService; convert its BrokerCandle
+ // result to the algo OhlcvCandle here. (Yahoo fallback is layered in fetch().)
+ const QString tf = timeframe;
+ trading::HistoricalDataService::instance().fetch(
+ symbol, timeframe, lookback_days, broker_id, account_id,
+ [callback, tf](bool ok, const QVector<trading::BrokerCandle>& candles, const QString& err) {
+ if (ok && !candles.isEmpty())
+ callback(true, CandleDataFetcher::broker_candles_to_ohlcv(candles, tf), {});
+ else
callback(false, {}, err);
- }, Qt::QueuedConnection);
- }
- });
+ });
}
void CandleDataFetcher::fetch_from_yahoo(const QStringList& symbols, const QString& timeframe,
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
index 821b45ded..23625e0d4 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.cpp
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
@@ -11,6 +11,7 @@ using fincept::Database;
#include "trading/BrokerInterface.h"
#include "trading/BrokerRegistry.h"
#include "trading/BrokerTopic.h"
+#include "trading/DataStreamManager.h"
#include "trading/TradingTypes.h"
#include <QDateTime>
@@ -48,12 +49,6 @@ DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deploym
heartbeat_timer_ = new QTimer(this);
heartbeat_timer_->setInterval(5000);
connect(heartbeat_timer_, &QTimer::timeout, this, &DeploymentRunner::on_heartbeat);
-
- // Poll the broker for a fresh quote every 3s while running. Lives on the engine
- // thread (the runner is moved there before start()), so the timer fires there.
- quote_timer_ = new QTimer(this);
- quote_timer_->setInterval(3000);
- connect(quote_timer_, &QTimer::timeout, this, &DeploymentRunner::poll_quote);
}
DeploymentRunner::~DeploymentRunner() {
@@ -138,48 +133,26 @@ void DeploymentRunner::start_market_data() {
.arg(deployment_.id));
return;
}
- LOG_INFO("AlgoEngine", QString("Deployment %1: polling %2 quotes from broker '%3' every 3s")
+ LOG_INFO("AlgoEngine", QString("Deployment %1: subscribing to shared %2 feed on '%3'")
.arg(deployment_.id, deployment_.symbol, deployment_.broker_id));
- quote_timer_->start();
- poll_quote(); // fire the first one immediately rather than waiting 3s
+ // Subscribe to the shared per-account quote feed. The symbol joins the account
+ // stream (WS tick or fast REST poll), is published to broker:<id>:<acct>:quote:
+ // <symbol>, and each quote is delivered here on the engine thread via
+ // on_tick_data — the same entry point a WS tick used. One connection per
+ // (account, symbol) is shared across the Equity watchlist and every algo.
+ QPointer<DeploymentRunner> self = this;
+ trading::DataStreamManager::instance().open_quote_feed(
+ this, QStringLiteral("algo:") + deployment_.id,
+ deployment_.broker_account_id, deployment_.symbol,
+ [self](const trading::BrokerQuote& q) {
+ if (self && self->running_.load() && !self->paused_.load())
+ self->on_tick_data(QVariant::fromValue(q));
+ });
}
void DeploymentRunner::stop_market_data() {
- if (quote_timer_)
- quote_timer_->stop();
-}
-
-void DeploymentRunner::poll_quote() {
- if (!running_.load() || paused_.load())
- return;
- const QString broker_id = deployment_.broker_id;
- const QString account_id = deployment_.broker_account_id;
- const QString symbol = deployment_.symbol;
- if (broker_id.isEmpty() || account_id.isEmpty())
- return;
-
- // Hit the broker's quote REST endpoint off-thread; deliver the result back on
- // the engine thread via on_tick_data (same entry point a WS tick would use).
- QPointer<DeploymentRunner> self = this;
- QtConcurrent::run([self, broker_id, account_id, symbol]() {
- auto* broker = trading::BrokerRegistry::instance().get(broker_id);
- if (!broker)
- return;
- auto creds = trading::AccountManager::instance().load_credentials(account_id);
- auto resp = broker->get_quotes(creds, {symbol});
- if (!resp.success || !resp.data.has_value() || resp.data->isEmpty())
- return;
- const trading::BrokerQuote quote = resp.data->first();
- if (!self)
- return;
- QMetaObject::invokeMethod(
- self,
- [self, quote]() {
- if (self && self->running_.load())
- self->on_tick_data(QVariant::fromValue(quote));
- },
- Qt::QueuedConnection);
- });
+ trading::DataStreamManager::instance().close_quote_feed(
+ QStringLiteral("algo:") + deployment_.id, deployment_.broker_account_id);
}
void DeploymentRunner::on_tick_data(const QVariant& data) {
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.h b/fincept-qt/src/algo_engine/DeploymentRunner.h
index 2c2e91057..2801829c3 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.h
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.h
@@ -51,13 +51,12 @@ private slots:
void on_heartbeat();
private:
- // Live market data: poll the connected broker's quote REST endpoint on a timer
- // and feed each BrokerQuote into on_tick_data(). Self-contained — does NOT touch
- // the shared AccountDataStream/WebSocket (whose single-symbol subscription is
- // owned by the Equity screen), so it can't clobber other consumers.
+ // Live market data: subscribe to the shared per-account quote feed via
+ // DataStreamManager (the same feed the Equity watchlist uses). Quotes arrive
+ // on the engine thread via on_tick_data(). No private broker polling — one
+ // connection per (account, symbol) is shared across all consumers.
void start_market_data();
void stop_market_data();
- void poll_quote();
// Builds the candle window used for live (per-tick) evaluation: the closed
// history plus the previous and current tick as the last two bars, so a
// crossover is detected tick-to-tick against the live price.
@@ -87,7 +86,6 @@ private:
std::atomic<bool> running_{false};
std::atomic<bool> paused_{false};
QTimer* heartbeat_timer_ = nullptr;
- QTimer* quote_timer_ = nullptr; // drives poll_quote()
int64_t last_heartbeat_ms_ = 0;
bool first_tick_logged_ = false; // log the first live quote once, for trackability
bool live_mode_ = false; // timeframe == "live" → evaluate per tick
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
index de3113d60..e7cac3b67 100644
--- a/fincept-qt/src/app/DockScreenRouter.h
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -76,6 +76,12 @@ class DockScreenRouter : public QObject {
/// Find an existing dock widget by screen id, or nullptr.
ads::CDockWidget* find_dock_widget(const QString& id) const;
+ /// Return the materialized screen widget for a route id, or nullptr if the
+ /// screen has not been created yet. This is the raw screen (not the ADS
+ /// dock-widget wrapper), so callers can qobject_cast it to the concrete type
+ /// to hand it a payload after navigate() (e.g. a notebook path to open).
+ QWidget* screen_widget(const QString& id) const { return screens_.value(id); }
+
/// Returns all registered screen IDs (both eager and factory).
QStringList all_screen_ids() const;
diff --git a/fincept-qt/src/app/WindowFrame_Setup.cpp b/fincept-qt/src/app/WindowFrame_Setup.cpp
index a688c74bb..d0e6ea4fc 100644
--- a/fincept-qt/src/app/WindowFrame_Setup.cpp
+++ b/fincept-qt/src/app/WindowFrame_Setup.cpp
@@ -279,7 +279,17 @@ void WindowFrame::setup_dock_screens() {
dock_router_->register_factory("file_manager", [this]() {
auto* fm = new screens::FileManagerScreen;
connect(fm, &screens::FileManagerScreen::open_file_in_screen, this,
- [this](const QString& route_id, const QString& /*file_path*/) { dock_router_->navigate(route_id); });
+ [this](const QString& route_id, const QString& file_path) {
+ dock_router_->navigate(route_id);
+ // Notebooks open into the editor with the file loaded — hand
+ // the path to the live CodeEditorScreen after it materializes.
+ if (route_id == "code_editor" && !file_path.isEmpty()) {
+ dock_router_->materialize_now(route_id);
+ if (auto* nb =
+ qobject_cast<screens::CodeEditorScreen*>(dock_router_->screen_widget(route_id)))
+ nb->open_notebook_path(file_path);
+ }
+ });
return fm;
});
dock_router_->register_factory("excel", []() { return new screens::ExcelScreen; });
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index eef49eeeb..49fafab7b 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -23,6 +23,7 @@
#include "core/symbol/SymbolRef.h"
#include "datahub/DataHubMetaTypes.h"
#include "mcp/McpInit.h"
+#include "mcp/ToolSelfTest.h"
#include "network/http/HttpClient.h"
#include "python/PythonSetupManager.h"
#include "screens/launchpad/LaunchpadScreen.h"
@@ -45,6 +46,7 @@
#include "services/options/OptionChainService.h"
#include "services/alpha_arena/AlphaArenaEngine.h"
#include "services/news/NewsService.h"
+#include "services/notebooks/NotebookLibraryService.h"
#include "services/polymarket/PolymarketWebSocket.h"
#include "services/prediction/PredictionCredentialStore.h"
#include "services/prediction/PredictionExchangeRegistry.h"
@@ -606,6 +608,11 @@ int main(int argc, char* argv[]) {
fincept::Logger::instance().set_file(fincept::AppPaths::logs() + "/fincept.log");
+ // Seed the prebuilt Fincept Notebook library into the File Manager on first
+ // run (idempotent — guarded by a marker file). Makes the curated notebooks
+ // appear in both the Notebook Library and the File Manager out of the box.
+ fincept::services::NotebookLibraryService::instance().seed_into_files();
+
// P3.18 — route Qt's own qDebug/qWarning/qCritical messages into our log
// file so framework/3rd-party warnings are visible in Release builds.
qInstallMessageHandler([](QtMsgType type, const QMessageLogContext& ctx, const QString& msg) {
@@ -843,6 +850,18 @@ int main(int argc, char* argv[]) {
// external MCP servers in the background (non-blocking).
fincept::mcp::initialize_all_tools();
+ // ── Headless tool-system self-test / catalog dump ────────────────────────
+ // Runs after the real tool registration above but before any window or
+ // network init, so it exercises exactly what ships. Exits without starting
+ // the GUI — used by the dev loop and CI to measure tool retrieval recall
+ // and registry integrity (no LLM / API key required).
+ for (int i = 1; i < argc; ++i) {
+ if (qstrcmp(argv[i], "--selftest-tools") == 0)
+ return fincept::mcp::run_tool_selftest();
+ if (qstrcmp(argv[i], "--dump-tools") == 0)
+ return fincept::mcp::dump_tools_json();
+ }
+
// ── Python environment check ─────────────────────────────────────────────
// check_status() fast path (sentinel + markers present) is synchronous and
// cheap. The slow path (first run) can spawn processes — but at this point
diff --git a/fincept-qt/src/mcp/McpProvider.cpp b/fincept-qt/src/mcp/McpProvider.cpp
index e0ab090b3..74b0942d7 100644
--- a/fincept-qt/src/mcp/McpProvider.cpp
+++ b/fincept-qt/src/mcp/McpProvider.cpp
@@ -118,6 +118,29 @@ std::optional<UnifiedTool> McpProvider::find_tool(const QString& name) const {
return it.value();
}
+std::vector<McpProvider::ToolAuditInfo> McpProvider::audit_all_tools() const {
+ QMutexLocker lock(&mutex_);
+ std::vector<ToolAuditInfo> result;
+ result.reserve(static_cast<std::size_t>(tools_.size()));
+ for (auto it = tools_.cbegin(); it != tools_.cend(); ++it) {
+ const ToolDef& def = it.value();
+ ToolAuditInfo info;
+ info.name = def.name;
+ info.category = def.category;
+ info.description = def.description;
+ // A std::function is truthy when a target is bound. async wins if both.
+ info.has_handler = static_cast<bool>(def.handler) || static_cast<bool>(def.async_handler);
+ info.is_async = static_cast<bool>(def.async_handler);
+ info.enabled = !disabled_tools_.contains(it.key());
+ info.is_destructive = def.is_destructive;
+ info.auth_required = def.auth_required;
+ info.input_schema = def.input_schema.to_json();
+ info.legacy_aliases = def.legacy_aliases;
+ result.push_back(std::move(info));
+ }
+ return result;
+}
+
std::size_t McpProvider::tool_count() const {
QMutexLocker lock(&mutex_);
std::size_t count = 0;
diff --git a/fincept-qt/src/mcp/McpProvider.h b/fincept-qt/src/mcp/McpProvider.h
index a71844b25..c5ff5b46d 100644
--- a/fincept-qt/src/mcp/McpProvider.h
+++ b/fincept-qt/src/mcp/McpProvider.h
@@ -47,6 +47,28 @@ class McpProvider {
/// list_tools()+linear-scan (was ~3 ms p95 across the 583-tool catalog).
std::optional<UnifiedTool> find_tool(const QString& name) const;
+ /// Audit-friendly snapshot of one tool. Carries the bits the self-test /
+ /// management UI need to verify wiring — crucially handler-presence, which
+ /// the LLM-facing UnifiedTool snapshot omits. Does not expose the handler
+ /// std::functions themselves (kept inside the registry).
+ struct ToolAuditInfo {
+ QString name;
+ QString category;
+ QString description;
+ bool has_handler = false; // sync OR async handler is set
+ bool is_async = false; // async_handler is set
+ bool enabled = true;
+ bool is_destructive = false;
+ AuthLevel auth_required = AuthLevel::None;
+ QJsonObject input_schema; // serialised JSON Schema
+ QStringList legacy_aliases;
+ };
+
+ /// One ToolAuditInfo per registered tool (enabled and disabled). Used by
+ /// the headless tool self-test to verify every tool has a handler, a valid
+ /// schema, and a usable description without invoking anything.
+ std::vector<ToolAuditInfo> audit_all_tools() const;
+
// ── Tool Execution ─────────────────────────────────────────────────────
/// Synchronous execution. For tools registered with `handler` (legacy),
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 6d76b5c79..412c8cc47 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -262,6 +262,11 @@ static bool tool_rag_enabled() {
}
QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {
+ return format_tools_for_openai(filter, QSet<QString>{});
+}
+
+QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter,
+ const QSet<QString>& extra_tool_names) {
QMutexLocker lock(&mutex_);
cached_tools_locked();
@@ -277,9 +282,21 @@ QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {
filter.max_tools == 0;
const bool use_rag = default_filter && tool_rag_enabled();
- const QByteArray key = use_rag
- ? QByteArrayLiteral("__tier0__")
- : filter_signature(filter);
+ QByteArray key;
+ if (use_rag) {
+ key = QByteArrayLiteral("__tier0__");
+ // Activated tools widen the Tier-0 set, so they must vary the cache key
+ // — otherwise round 2 would be served round 1's cached 7-tool array and
+ // the model would never see the tool it just discovered.
+ if (!extra_tool_names.isEmpty()) {
+ QStringList sorted(extra_tool_names.constBegin(), extra_tool_names.constEnd());
+ sorted.sort();
+ key += '|';
+ key += sorted.join(QLatin1Char(',')).toUtf8();
+ }
+ } else {
+ key = filter_signature(filter);
+ }
auto cached = openai_format_cache_.constFind(key);
if (cached != openai_format_cache_.constEnd()) {
@@ -294,7 +311,7 @@ QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {
if (use_rag) {
const auto& tier0 = tier_0_tool_names();
for (const auto& t : cached_tools_) {
- if (tier0.contains(t.name))
+ if (tier0.contains(t.name) || extra_tool_names.contains(t.name))
tools.push_back(t);
}
} else {
@@ -330,8 +347,8 @@ QJsonArray McpService::format_tools_for_openai(const ToolFilter& filter) {
if (use_rag) {
LOG_INFO(TAG, QString("format_tools_for_openai: %1/%2 tools sent to LLM "
- "(tier-0 / Tool RAG mode, fresh)")
- .arg(result.size()).arg(total_seen));
+ "(tier-0 + %3 activated / Tool RAG mode, fresh)")
+ .arg(result.size()).arg(total_seen).arg(extra_tool_names.size()));
} else if (total_seen != result.size()) {
LOG_INFO(TAG, QString("format_tools_for_openai: %1/%2 tools sent to LLM (filtered, fresh)")
.arg(result.size()).arg(total_seen));
diff --git a/fincept-qt/src/mcp/McpService.h b/fincept-qt/src/mcp/McpService.h
index 42b26acd5..6980fcd90 100644
--- a/fincept-qt/src/mcp/McpService.h
+++ b/fincept-qt/src/mcp/McpService.h
@@ -8,6 +8,7 @@
#include <QDateTime>
#include <QFuture>
#include <QMutex>
+#include <QSet>
#include <vector>
@@ -35,6 +36,14 @@ class McpService {
/// Equivalent to format_tools_for_openai() when filter is default-constructed.
QJsonArray format_tools_for_openai(const ToolFilter& filter);
+ /// Tool RAG activation variant. In Tier-0 (Tool RAG) mode the model only
+ /// sees the always-on Tier-0 tools; `extra_tool_names` force-includes tools
+ /// (by exact bare name) the model has discovered this turn via tool_list /
+ /// tool_describe, so a structured function-calling model can actually call
+ /// them. Has no effect outside Tier-0 mode (the filtered catalogue already
+ /// contains them). See the tool loop / note_tool_activations.
+ QJsonArray format_tools_for_openai(const ToolFilter& filter, const QSet<QString>& extra_tool_names);
+
std::size_t tool_count();
// ── Unified Tool Execution ──────────────────────────────────────────
diff --git a/fincept-qt/src/mcp/ToolSelfTest.cpp b/fincept-qt/src/mcp/ToolSelfTest.cpp
new file mode 100644
index 000000000..b208d884b
--- /dev/null
+++ b/fincept-qt/src/mcp/ToolSelfTest.cpp
@@ -0,0 +1,336 @@
+// ToolSelfTest.cpp — see ToolSelfTest.h.
+
+#include "mcp/ToolSelfTest.h"
+
+#include "mcp/McpProvider.h"
+#include "mcp/ToolRetriever.h"
+
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QRegularExpression>
+#include <QString>
+#include <QStringList>
+
+#include <algorithm>
+#include <cstdio>
+#include <vector>
+
+namespace fincept::mcp {
+namespace {
+
+// ── Eval corpus ────────────────────────────────────────────────────────────
+//
+// Realistic things a user would ask the AI chat to do, each mapped to the
+// tool(s) that should satisfy it. A case is a HIT if ANY listed tool appears
+// in the retriever's top-K. Phrasing deliberately avoids the tool's own name
+// where possible — we're testing semantic recall, not string match.
+//
+// Grounded in the live catalog (see `--dump-tools`). Acceptable-set lists
+// every tool that genuinely answers the intent so legitimately-equivalent
+// tools don't count as misses, but the *intended* tool always leads the list.
+struct EvalCase {
+ const char* intent;
+ QStringList expected;
+};
+
+std::vector<EvalCase> corpus() {
+ return {
+ // ── portfolio (named portfolios) ──
+ {"create a new investment portfolio to track my long-term holdings", {"create_portfolio"}},
+ {"add 10 shares of AAPL bought at 225 to my portfolio", {"add_portfolio_asset", "add_holding"}},
+ {"show me all my portfolios", {"list_portfolios"}},
+ {"what assets are in my portfolio", {"get_portfolio_assets", "get_holdings", "get_portfolio"}},
+ {"record a buy transaction for 5 shares of MSFT", {"add_transaction", "add_portfolio_asset"}},
+ {"delete the portfolio I no longer use", {"delete_portfolio"}},
+ {"what are my current stock holdings and average cost", {"get_holdings", "get_portfolio_assets"}},
+
+ // ── paper trading ──
+ {"place a simulated buy order for 100 shares of TSLA", {"pt_place_order"}},
+ {"create a paper trading account to practice", {"pt_create_portfolio"}},
+ {"what are my open paper trading positions", {"pt_get_positions", "pt_get_portfolio"}},
+ {"cancel my pending paper order", {"pt_cancel_order"}},
+
+ // ── live broker trading ──
+ {"place a real order to buy 50 shares through my broker", {"live_place_order", "live_smart_order"}},
+ {"what positions do I hold at my broker right now", {"live_get_positions", "live_get_holdings"}},
+ {"cancel my open broker order", {"live_cancel_order", "live_cancel_all_orders"}},
+ {"check my available trading funds and margin", {"live_get_funds"}},
+ {"close all my open positions immediately", {"live_close_all_positions", "live_close_position"}},
+ {"get the live option chain for NIFTY", {"live_get_option_chain"}},
+
+ // ── markets / quotes ──
+ {"what is the current price of Apple stock", {"get_quote", "live_get_quote"}},
+ {"get historical daily prices for GOOGL over the last year", {"get_history", "get_equity_historical"}},
+ {"find the ticker symbol for Microsoft", {"lookup_symbol", "search_equity_symbols"}},
+
+ // ── watchlist ──
+ {"add NVDA to my watchlist", {"add_to_watchlist"}},
+ {"create a watchlist for semiconductor stocks", {"create_watchlist"}},
+ {"show me my watchlists", {"get_watchlists"}},
+ {"remove TSLA from my watchlist", {"remove_from_watchlist"}},
+
+ // ── news ──
+ {"show me the latest market news", {"get_news", "get_top_news"}},
+ {"search for recent news about Tesla", {"search_news", "get_equity_news"}},
+ {"summarize today's top headlines", {"summarize_news_headlines", "get_news_summary"}},
+ {"alert me when there is breaking news about oil prices", {"add_news_monitor"}},
+
+ // ── notes ──
+ {"save a note about my trade idea for AMD", {"create_note"}},
+ {"show me my saved notes", {"get_notes"}},
+
+ // ── navigation ──
+ {"open the portfolio tab", {"navigate_to_tab"}},
+ {"what tabs or screens are available", {"list_tabs", "list_available_screen_ids"}},
+
+ // ── crypto ──
+ {"get the current bitcoin price on the exchange", {"get_ticker", "get_quote"}},
+ {"show me the order book depth for ETH", {"get_order_book"}},
+
+ // ── equity research ──
+ {"pull the latest financial statements for Apple", {"get_equity_financials", "edgar_get_financials"}},
+ {"what is the analyst sentiment on NVDA", {"get_equity_sentiment"}},
+ {"show technical indicators for the SPY", {"get_equity_technicals", "compute_equity_talipp"}},
+ {"who are the peer companies of Microsoft", {"get_equity_peers"}},
+
+ // ── SEC EDGAR ──
+ {"find the latest 10-K annual report for Tesla", {"edgar_10k_sections", "edgar_10k_full_text", "edgar_10k_search", "edgar_find_company"}},
+ {"show me recent insider trading at Apple", {"edgar_insider_transactions", "edgar_insider_summary"}},
+ {"what 13F holdings does Berkshire Hathaway report", {"edgar_13f_holdings", "edgar_13f_top_holdings"}},
+ {"look up the CIK number for a company", {"edgar_resolve_cik", "edgar_find_company"}},
+
+ // ── report builder ──
+ {"add a chart component to my research report", {"report_add_component"}},
+ {"export my report to PDF", {"report_export_pdf"}},
+ {"start a new report from a template", {"report_apply_template"}},
+
+ // ── dashboard ──
+ {"add a market heatmap widget to my dashboard", {"add_dashboard_widget"}},
+ {"apply a preset dashboard layout", {"apply_dashboard_template"}},
+
+ // ── M&A analytics ──
+ {"run a DCF valuation model", {"ma_dcf", "ma_synergies_dcf"}},
+ {"build an LBO model for this deal", {"ma_lbo_model"}},
+ {"compute the accretion dilution of the merger", {"ma_accretion_dilution"}},
+
+ // ── agents ──
+ {"run an AI agent to analyze a stock for me", {"run_stock_analysis_agent", "run_agent", "run_agent_structured"}},
+ {"list the available AI agents", {"list_agents", "list_agent_configs"}},
+
+ // ── excel ──
+ {"set the value of cell B2 in my spreadsheet", {"set_excel_cell"}},
+ {"read the data from my excel sheet", {"get_excel_sheet_data"}},
+
+ // ── files ──
+ {"list the files I have saved", {"list_files"}},
+ {"read the contents of a file", {"read_file_contents"}},
+
+ // ── settings ──
+ {"switch my active LLM provider", {"set_active_llm"}},
+ {"change an application setting", {"set_setting"}},
+
+ // ── profile / account ──
+ {"how many credits do I have left", {"profile_get_credits"}},
+ {"what subscription tier am I on", {"profile_get_subscription"}},
+
+ // ── workspace ──
+ {"tile my open panels in a 2x2 grid", {"tile_panels_2x2"}},
+ {"save my current window layout", {"save_current_layout", "snapshot_workspace_now"}},
+
+ // ── economics / data ──
+ {"find economic time series data on GDP", {"search_dbnomics", "list_dbnomics_series"}},
+
+ // ── mcp servers / data sources ──
+ {"list my connected MCP servers", {"list_mcp_servers"}},
+ {"what data source connectors are available", {"ds_list_connectors", "ds_connectors_by_category"}},
+ };
+}
+
+void out(const QString& s) {
+ const QByteArray b = s.toUtf8();
+ std::fwrite(b.constData(), 1, static_cast<std::size_t>(b.size()), stdout);
+ std::fputc('\n', stdout);
+}
+
+// 1-based rank of the first acceptable tool in `results`, or 0 if none present.
+int first_hit_rank(const std::vector<ToolMatch>& results, const QStringList& expected) {
+ for (int i = 0; i < static_cast<int>(results.size()); ++i) {
+ if (expected.contains(results[static_cast<std::size_t>(i)].name))
+ return i + 1;
+ }
+ return 0;
+}
+
+QString top_names(const std::vector<ToolMatch>& results, int k) {
+ QStringList names;
+ for (int i = 0; i < static_cast<int>(results.size()) && i < k; ++i)
+ names << results[static_cast<std::size_t>(i)].name;
+ return names.isEmpty() ? QStringLiteral("(none)") : names.join(QStringLiteral(", "));
+}
+
+} // namespace
+
+int dump_tools_json() {
+ auto tools = McpProvider::instance().audit_all_tools();
+ std::sort(tools.begin(), tools.end(), [](const auto& a, const auto& b) {
+ if (a.category != b.category) return a.category < b.category;
+ return a.name < b.name;
+ });
+ QJsonArray arr;
+ for (const auto& t : tools) {
+ arr.append(QJsonObject{
+ {"name", t.name},
+ {"category", t.category},
+ {"description", t.description},
+ {"destructive", t.is_destructive},
+ {"has_handler", t.has_handler},
+ {"enabled", t.enabled},
+ });
+ }
+ QJsonObject root{{"count", static_cast<int>(arr.size())}, {"tools", arr}};
+ out(QString::fromUtf8(QJsonDocument(root).toJson(QJsonDocument::Indented)));
+ return 0;
+}
+
+int run_tool_selftest() {
+ out(QStringLiteral("\n══════════════════════════════════════════════════════════════"));
+ out(QStringLiteral(" MCP TOOL SELF-TEST"));
+ out(QStringLiteral("══════════════════════════════════════════════════════════════"));
+
+ // ── Part 1: registry audit ──────────────────────────────────────────────
+ auto tools = McpProvider::instance().audit_all_tools();
+ out(QString(QStringLiteral("\n[1] REGISTRY AUDIT — %1 registered tools")).arg(tools.size()));
+
+ QStringList no_handler; // CRITICAL — tool can never run
+ QStringList bad_schema; // CRITICAL — required param not declared
+ QStringList thin_desc; // WARN — retrieval-poison
+ QStringList destructive_miss; // WARN — mutating verb but not flagged destructive
+ QHash<QString, QStringList> by_desc; // duplicate-description detection
+
+ static const QRegularExpression mutating_rx(
+ QStringLiteral("(?:^|_)(delete|remove|cancel|close|clear|wipe|drop|reset|unregister)(?:_|$)"),
+ QRegularExpression::CaseInsensitiveOption);
+
+ for (const auto& t : tools) {
+ if (!t.has_handler)
+ no_handler << t.name;
+
+ // Schema: type must be object, and every `required` name must be a
+ // declared property — a required-but-undeclared param is a real bug
+ // that makes the tool uncallable from a strict validator.
+ const QJsonObject schema = t.input_schema;
+ if (schema.value("type").toString() != QLatin1String("object")) {
+ bad_schema << (t.name + QStringLiteral(" (type!=object)"));
+ } else {
+ const QJsonObject props = schema.value("properties").toObject();
+ for (const auto& r : schema.value("required").toArray()) {
+ const QString rn = r.toString();
+ if (!props.contains(rn)) {
+ bad_schema << (t.name + QStringLiteral(" (required '") + rn + QStringLiteral("' not in properties)"));
+ }
+ }
+ }
+
+ if (t.description.trimmed().length() < 20)
+ thin_desc << (t.name + QStringLiteral(" (\"") + t.description.trimmed() + QStringLiteral("\")"));
+
+ if (mutating_rx.match(t.name).hasMatch() && !t.is_destructive)
+ destructive_miss << t.name;
+
+ const QString key = t.description.trimmed().toLower();
+ if (!key.isEmpty())
+ by_desc[key] << t.name;
+ }
+
+ auto report_list = [](const QString& label, const QStringList& items, bool critical) {
+ if (items.isEmpty()) {
+ out(QStringLiteral(" ✓ ") + label + QStringLiteral(": none"));
+ return;
+ }
+ out((critical ? QStringLiteral(" ✗ ") : QStringLiteral(" ⚠ ")) + label +
+ QStringLiteral(": ") + QString::number(items.size()));
+ for (const auto& it : items)
+ out(QStringLiteral(" - ") + it);
+ };
+
+ report_list(QStringLiteral("tools with NO handler"), no_handler, true);
+ report_list(QStringLiteral("tools with invalid schema"), bad_schema, true);
+ report_list(QStringLiteral("tools with thin description (<20 chars)"), thin_desc, false);
+ report_list(QStringLiteral("mutating tools NOT flagged destructive"), destructive_miss, false);
+
+ QStringList dup_desc;
+ for (auto it = by_desc.cbegin(); it != by_desc.cend(); ++it) {
+ if (it.value().size() > 1)
+ dup_desc << (it.value().join(QStringLiteral(" = ")));
+ }
+ report_list(QStringLiteral("tools sharing an identical description"), dup_desc, false);
+
+ // ── Part 2: retrieval eval ────────────────────────────────────────────────
+ const auto cases = corpus();
+ out(QString(QStringLiteral("\n[2] RETRIEVAL EVAL — %1 intents, top-5 via ToolRetriever (no category hint)"))
+ .arg(cases.size()));
+
+ int hit1 = 0;
+ int hit5 = 0;
+ double mrr = 0.0;
+ QStringList misses;
+ QStringList weak; // hit but not rank-1
+
+ for (const auto& c : cases) {
+ const QString intent = QString::fromUtf8(c.intent);
+ auto results = ToolRetriever::instance().search(intent, 5);
+ const int rank = first_hit_rank(results, c.expected);
+ if (rank == 1)
+ ++hit1;
+ if (rank >= 1 && rank <= 5)
+ ++hit5;
+ if (rank >= 1)
+ mrr += 1.0 / rank;
+
+ if (rank == 0) {
+ misses << (QStringLiteral(" ✗ \"") + intent + QStringLiteral("\"\n want: ") +
+ c.expected.join(QStringLiteral("|")) + QStringLiteral("\n got: ") +
+ top_names(results, 5));
+ } else if (rank > 1) {
+ weak << (QStringLiteral(" ~ rank ") + QString::number(rank) + QStringLiteral(" \"") + intent +
+ QStringLiteral("\" → ") + top_names(results, 5));
+ }
+ }
+
+ const int n = static_cast<int>(cases.size());
+ const double recall1 = n ? static_cast<double>(hit1) / n : 0.0;
+ const double recall5 = n ? static_cast<double>(hit5) / n : 0.0;
+ const double mrr_avg = n ? mrr / n : 0.0;
+
+ if (!misses.isEmpty()) {
+ out(QStringLiteral("\n MISSES (expected tool not in top-5):"));
+ for (const auto& m : misses)
+ out(m);
+ }
+ if (!weak.isEmpty()) {
+ out(QStringLiteral("\n WEAK (found but not rank-1):"));
+ for (const auto& w : weak)
+ out(w);
+ }
+
+ out(QStringLiteral("\n──────────────────────────────────────────────────────────────"));
+ out(QString(QStringLiteral(" recall@1 = %1 recall@5 = %2 MRR = %3"))
+ .arg(recall1, 0, 'f', 3).arg(recall5, 0, 'f', 3).arg(mrr_avg, 0, 'f', 3));
+ out(QString(QStringLiteral(" registry: %1 no-handler, %2 schema errors, %3 thin desc"))
+ .arg(no_handler.size()).arg(bad_schema.size()).arg(thin_desc.size()));
+
+ // ── Verdict ───────────────────────────────────────────────────────────────
+ constexpr double kRecall5Target = 0.95;
+ const bool pass = no_handler.isEmpty() && bad_schema.isEmpty() && recall5 >= kRecall5Target;
+ out(QString(QStringLiteral(" VERDICT: %1 (recall@5 target %2)"))
+ .arg(pass ? QStringLiteral("PASS ✓") : QStringLiteral("FAIL ✗"))
+ .arg(kRecall5Target, 0, 'f', 2));
+ out(QStringLiteral("══════════════════════════════════════════════════════════════\n"));
+ std::fflush(stdout);
+
+ return pass ? 0 : 1;
+}
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/ToolSelfTest.h b/fincept-qt/src/mcp/ToolSelfTest.h
new file mode 100644
index 000000000..09330b5ae
--- /dev/null
+++ b/fincept-qt/src/mcp/ToolSelfTest.h
@@ -0,0 +1,28 @@
+#pragma once
+// ToolSelfTest.h — headless self-test for the MCP tool system.
+//
+// Runs WITHOUT a GUI, an LLM, or any network/API key. Exercises the two
+// deterministic halves of agentic reliability:
+//
+// 1. Retrieval — can ToolRetriever (the BM25 index behind tool_list) surface
+// the right tool for a realistic natural-language intent? This is the #1
+// cause of "the model couldn't find/call the tool" failures.
+// 2. Registry integrity — does every registered tool have a handler, a valid
+// schema, and a usable description?
+//
+// Invoked from main() via `--selftest-tools` / `--dump-tools`, after
+// initialize_all_tools() registers the real catalog but before any window or
+// network init, so it tests exactly what ships.
+
+namespace fincept::mcp {
+
+/// Run the retrieval eval + registry audit. Prints a scored report to stdout.
+/// Returns a process exit code: 0 = passed, non-zero = failures (no-handler
+/// tools, schema errors, or retrieval recall below threshold).
+int run_tool_selftest();
+
+/// Print every registered tool as JSON (name, category, description, flags) to
+/// stdout. Returns 0. Used to ground the eval corpus in the real catalog.
+int dump_tools_json();
+
+} // namespace fincept::mcp
diff --git a/fincept-qt/src/mcp/tools/MarketsTools.cpp b/fincept-qt/src/mcp/tools/MarketsTools.cpp
index 035d84906..0bba93a64 100644
--- a/fincept-qt/src/mcp/tools/MarketsTools.cpp
+++ b/fincept-qt/src/mcp/tools/MarketsTools.cpp
@@ -197,9 +197,9 @@ std::vector<ToolDef> get_markets_tools() {
{
ToolDef t;
t.name = "get_history";
- t.description = "Fetch historical OHLCV bars for a stock/ETF/crypto symbol. "
- "Returns an array of {date, timestamp, open, high, low, close, volume}. "
- "Backed by yfinance.";
+ t.description = "Fetch historical daily/weekly price history (OHLCV bars) for a stock/ETF/crypto "
+ "symbol over a date range. Returns an array of {date, timestamp, open, high, low, "
+ "close, volume}. Backed by yfinance.";
t.category = "markets";
t.input_schema.properties = QJsonObject{
{"symbol", QJsonObject{{"type", "string"},
diff --git a/fincept-qt/src/mcp/tools/NewsTools.cpp b/fincept-qt/src/mcp/tools/NewsTools.cpp
index 33b2b32ae..062e75d4a 100644
--- a/fincept-qt/src/mcp/tools/NewsTools.cpp
+++ b/fincept-qt/src/mcp/tools/NewsTools.cpp
@@ -340,7 +340,8 @@ std::vector<ToolDef> get_news_tools() {
ToolDef t;
t.name = "add_news_monitor";
t.description =
- "Create a keyword monitor that highlights articles matching specific keywords in the News screen.";
+ "Create a news alert: a keyword monitor that notifies you of, and highlights, breaking articles "
+ "matching specific keywords or topics in the News screen.";
t.category = "news";
t.input_schema.properties =
QJsonObject{{"label", QJsonObject{{"type", "string"}, {"description", "Monitor name"}}},
diff --git a/fincept-qt/src/mcp/tools/PortfolioTools.cpp b/fincept-qt/src/mcp/tools/PortfolioTools.cpp
index 1d041e23b..a4d770d87 100644
--- a/fincept-qt/src/mcp/tools/PortfolioTools.cpp
+++ b/fincept-qt/src/mcp/tools/PortfolioTools.cpp
@@ -138,7 +138,8 @@ std::vector<ToolDef> get_portfolio_tools() {
{
ToolDef t;
t.name = "list_portfolios";
- t.description = "List all named investment portfolios.";
+ t.description = "Show all my portfolios — lists every named investment portfolio I created to "
+ "track real holdings (not paper-trading accounts).";
t.category = "portfolio";
t.handler = [](const QJsonObject&) -> ToolResult {
auto r = PortfolioRepository::instance().list_portfolios();
diff --git a/fincept-qt/src/mcp/tools/QuantLabTools.cpp b/fincept-qt/src/mcp/tools/QuantLabTools.cpp
index 75ee78a63..9916d7fb8 100644
--- a/fincept-qt/src/mcp/tools/QuantLabTools.cpp
+++ b/fincept-qt/src/mcp/tools/QuantLabTools.cpp
@@ -151,7 +151,7 @@ static const CatalogEntry kCatalog[] = {
{"quant_reporting", "check_status", "quant_reporting_status",
"Check the quant-reporting service status."},
{"quant_reporting", "ic_analysis", "quant_reporting_ic",
- "IC analysis report."},
+ "Information Coefficient (IC) analysis report — measures a factor's predictive power on forward returns over time."},
{"quant_reporting", "model_performance", "quant_reporting_model_perf",
"Model performance report."},
{"quant_reporting", "cumulative_returns", "quant_reporting_cumret",
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
index 81a9388c5..cf212e587 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.cpp
@@ -1,9 +1,10 @@
// src/screens/code_editor/CodeEditorScreen.cpp
-// Python Colab — Obsidian design system implementation.
-// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.
+// Fincept Notebook — Obsidian design system implementation.
+// Two views: a prebuilt-notebook Library (cards) and the notebook Editor.
// CellWidget + CodeTextEdit lives in CodeEditorScreen_Cells.cpp.
// CellNavigator lives in CodeEditorScreen_Navigator.cpp.
+// Library view (cards/filters) lives in CodeEditorScreen_Library.cpp.
#include "screens/code_editor/CodeEditorScreen.h"
@@ -12,13 +13,16 @@
#include "core/session/ScreenStateManager.h"
#include "python/PythonRunner.h"
#include "services/file_manager/FileManagerService.h"
+#include "services/notebooks/NotebookLibraryService.h"
#include "ui/theme/Theme.h"
+#include "ui/theme/ThemeManager.h"
#include <QAbstractTextDocumentLayout>
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QFileInfo>
+#include <QGridLayout>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QJsonArray>
@@ -34,12 +38,98 @@
#include <QScrollArea>
#include <QScrollBar>
#include <QSplitter>
+#include <QStackedWidget>
+#include <QStyle>
#include <QTextBrowser>
#include <QTextEdit>
#include <QTimer>
#include <QUuid>
#include <QVBoxLayout>
+// ── Stylesheet ────────────────────────────────────────────────────────────────
+// Object-name stylesheet shared across the screen, mirroring McpServersScreen's
+// kStyle() pattern so the Fincept Notebook chrome matches the MCP design system
+// (header tab bar, search, button family, cards). Re-applied on theme change.
+
+namespace {
+using namespace fincept::ui;
+
+inline QString kStyle() {
+ return QString(
+ // Screen / header
+ "#nbScreen { background:%1; }"
+ "#nbHeader { background:%2; border-bottom:2px solid %3; }"
+ "#nbHeaderTitle { color:%3; font-weight:700; letter-spacing:1px; background:transparent; }"
+
+ // View tabs (LIBRARY / EDITOR)
+ "#nbViewBtn { background:transparent; color:%5; border:1px solid %8; "
+ " font-weight:700; padding:4px 14px; }"
+ "#nbViewBtn:hover { color:%4; border-color:%9; }"
+ "#nbViewBtn[active=\"true\"] { background:%3; color:%1; border-color:%3; }"
+
+ // Search
+ "#nbSearchInput { background:%1; color:%4; border:1px solid %8; padding:4px 8px; min-width:200px; }"
+ "#nbSearchInput:focus { border-color:%9; }"
+
+ // Buttons
+ "#nbPrimaryBtn { background:%3; color:%1; border:none; padding:5px 16px; font-weight:700; }"
+ "#nbPrimaryBtn:hover { background:%10; }"
+ "#nbSecondaryBtn { background:transparent; color:%5; border:none; padding:4px 10px; font-weight:600; "
+ " letter-spacing:0.5px; }"
+ "#nbSecondaryBtn:hover { color:%4; background:%12; }"
+ "#nbAccentBtn { background:transparent; color:%13; border:none; padding:4px 10px; font-weight:600; "
+ " letter-spacing:0.5px; }"
+ "#nbAccentBtn:hover { color:%4; background:%12; }"
+
+ // Editor toolbar / status bar
+ "#nbToolbar { background:%2; border-bottom:1px solid %8; }"
+ "#nbStatusBar { background:%2; border-top:1px solid %8; }"
+
+ // Library filter chips
+ "#nbChip { background:transparent; color:%5; border:1px solid %8; font-weight:700; padding:3px 10px; }"
+ "#nbChip:hover { color:%4; border-color:%9; }"
+ "#nbChip[active=\"true\"] { background:rgba(217,119,6,0.12); color:%3; border-color:%3; }"
+ "#nbLibLabel { color:%5; background:transparent; }"
+
+ // Library cards
+ "#nbCard { background:%7; border:1px solid %8; }"
+ "#nbCard:hover { border-color:%9; }"
+ "#nbCardTitle { color:%4; font-weight:700; background:transparent; }"
+ "#nbCardSummary { color:%5; background:transparent; }"
+ "#nbCardMeta { color:%11; background:transparent; }"
+ "#nbCatBadge { color:%13; font-weight:700; background:rgba(8,145,178,0.12); "
+ " padding:1px 7px; border:1px solid rgba(8,145,178,0.35); }"
+ "#nbDiffBeginner { color:%6; font-weight:700; background:rgba(22,163,74,0.12); "
+ " padding:1px 7px; border:1px solid rgba(22,163,74,0.35); }"
+ "#nbDiffIntermediate { color:%3; font-weight:700; background:rgba(217,119,6,0.12); "
+ " padding:1px 7px; border:1px solid rgba(217,119,6,0.35); }"
+ "#nbDiffHard { color:%14; font-weight:700; background:rgba(220,38,38,0.12); "
+ " padding:1px 7px; border:1px solid rgba(220,38,38,0.35); }"
+ "#nbCardOpenBtn { background:%3; color:%1; border:none; padding:5px 18px; font-weight:700; }"
+ "#nbCardOpenBtn:hover { background:%10; }"
+
+ // Scroll
+ "QScrollBar:vertical { background:%1; width:6px; }"
+ "QScrollBar::handle:vertical { background:%8; min-height:24px; }"
+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
+ .arg(colors::BG_BASE()) // %1
+ .arg(colors::BG_RAISED()) // %2
+ .arg(colors::AMBER()) // %3
+ .arg(colors::TEXT_PRIMARY()) // %4
+ .arg(colors::TEXT_SECONDARY()) // %5
+ .arg(colors::POSITIVE()) // %6
+ .arg(colors::BG_SURFACE()) // %7
+ .arg(colors::BORDER_DIM()) // %8
+ .arg(colors::BORDER_BRIGHT()) // %9
+ .arg(colors::AMBER_DIM()) // %10
+ .arg(colors::TEXT_DIM()) // %11
+ .arg(colors::BG_HOVER()) // %12
+ .arg(colors::CYAN()) // %13
+ .arg(colors::NEGATIVE()); // %14
+}
+
+} // namespace
+
namespace fincept::screens {
using namespace fincept::ui;
@@ -48,8 +138,14 @@ using namespace fincept::ui;
// CodeTextEdit — editor with keyboard shortcuts
CodeEditorScreen::CodeEditorScreen(QWidget* parent) : QWidget(parent) {
+ setObjectName("nbScreen");
+ setStyleSheet(kStyle());
+ connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
+ [this](const ui::ThemeTokens&) { setStyleSheet(kStyle()); });
build_ui();
on_new_notebook();
+ populate_library();
+ set_view(0); // land on the Library so users discover the prebuilt notebooks
}
void CodeEditorScreen::showEvent(QShowEvent* event) {
@@ -62,16 +158,83 @@ void CodeEditorScreen::hideEvent(QHideEvent* event) {
LOG_INFO("CodeEditor", "Screen hidden");
}
-void CodeEditorScreen::build_ui() {
- setStyleSheet(QString("QWidget { background:%1; color:%2; }").arg(colors::BG_BASE(), colors::TEXT_PRIMARY()));
+void CodeEditorScreen::resizeEvent(QResizeEvent* event) {
+ QWidget::resizeEvent(event);
+ relayout_library_cards(); // re-flow the card grid when the panel width changes
+}
+void CodeEditorScreen::build_ui() {
auto* root = new QVBoxLayout(this);
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
+ root->addWidget(build_header());
+
+ view_stack_ = new QStackedWidget(this);
+ library_page_ = build_library_page();
+ view_stack_->addWidget(library_page_); // 0 — Library
+ view_stack_->addWidget(build_editor_page()); // 1 — Editor
+ root->addWidget(view_stack_, 1);
+}
+
+// Header bar: title + LIBRARY/EDITOR tabs + Library search + NEW button.
+QWidget* CodeEditorScreen::build_header() {
+ auto* bar = new QWidget(this);
+ bar->setObjectName("nbHeader");
+ bar->setFixedHeight(44);
+
+ auto* hl = new QHBoxLayout(bar);
+ hl->setContentsMargins(14, 0, 12, 0);
+ hl->setSpacing(8);
+
+ header_title_ = new QLabel(tr("FINCEPT NOTEBOOK"), bar);
+ header_title_->setObjectName("nbHeaderTitle");
+ header_title_->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::SMALL));
+ hl->addWidget(header_title_);
+ hl->addSpacing(10);
+
+ const QStringList tabs = {tr("LIBRARY"), tr("EDITOR")};
+ for (int i = 0; i < tabs.size(); ++i) {
+ auto* btn = new QPushButton(tabs[i], bar);
+ btn->setObjectName("nbViewBtn");
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setProperty("active", i == 0);
+ connect(btn, &QPushButton::clicked, this, [this, i]() { on_view_changed(i); });
+ hl->addWidget(btn);
+ view_btns_.append(btn);
+ }
+
+ hl->addStretch(1);
+
+ lib_search_input_ = new QLineEdit(bar);
+ lib_search_input_->setObjectName("nbSearchInput");
+ lib_search_input_->setPlaceholderText(tr("Search notebooks..."));
+ lib_search_input_->setClearButtonEnabled(true);
+ connect(lib_search_input_, &QLineEdit::textChanged, this, &CodeEditorScreen::on_library_search);
+ hl->addWidget(lib_search_input_);
+
+ header_new_btn_ = new QPushButton(tr("+ NEW NOTEBOOK"), bar);
+ header_new_btn_->setObjectName("nbPrimaryBtn");
+ header_new_btn_->setCursor(Qt::PointingHandCursor);
+ connect(header_new_btn_, &QPushButton::clicked, this, [this]() {
+ on_new_notebook();
+ set_view(1);
+ });
+ hl->addWidget(header_new_btn_);
+
+ return bar;
+}
+
+// Editor page: action toolbar + splitter (navigator | cells) + status bar.
+QWidget* CodeEditorScreen::build_editor_page() {
+ auto* page = new QWidget(this);
+ auto* root = new QVBoxLayout(page);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
root->addWidget(build_toolbar());
- splitter_ = new QSplitter(Qt::Horizontal, this);
+ splitter_ = new QSplitter(Qt::Horizontal, page);
splitter_->setHandleWidth(1);
splitter_->setStyleSheet(QString("QSplitter { background:%1; } QSplitter::handle { background:%2; }")
.arg(colors::BG_BASE(), colors::BORDER_DIM()));
@@ -108,43 +271,51 @@ void CodeEditorScreen::build_ui() {
root->addWidget(splitter_, 1);
root->addWidget(build_status_bar());
+ return page;
+}
+
+// ── View switching ─────────────────────────────────────────────────────────
+
+void CodeEditorScreen::set_view(int index) {
+ active_view_ = index;
+ if (view_stack_)
+ view_stack_->setCurrentIndex(index);
+ for (int i = 0; i < view_btns_.size(); ++i) {
+ view_btns_[i]->setProperty("active", i == index);
+ view_btns_[i]->style()->unpolish(view_btns_[i]);
+ view_btns_[i]->style()->polish(view_btns_[i]);
+ }
+ // Search only applies to the Library view.
+ if (lib_search_input_)
+ lib_search_input_->setVisible(index == 0);
+}
+
+void CodeEditorScreen::on_view_changed(int index) {
+ set_view(index);
}
QWidget* CodeEditorScreen::build_toolbar() {
auto* bar = new QWidget(this);
+ bar->setObjectName("nbToolbar");
bar->setFixedHeight(36);
- bar->setStyleSheet(
- QString("background:%1; border-bottom:1px solid %2;").arg(colors::BG_RAISED(), colors::BORDER_DIM()));
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(10, 0, 10, 0);
- hl->setSpacing(0);
-
- toolbar_title_ = new QLabel(tr("PYTHON NOTEBOOK"), bar);
- toolbar_title_->setStyleSheet(QString("color:%1; font-family:%2; font-size:%3px; font-weight:700;"
- " letter-spacing:1px; padding-right:16px;")
- .arg(colors::AMBER(), fonts::DATA_FAMILY)
- .arg(fonts::SMALL));
- hl->addWidget(toolbar_title_);
+ hl->setSpacing(2);
auto add_sep = [&]() {
auto* sep = new QWidget(bar);
sep->setFixedSize(1, 18);
sep->setStyleSheet(QString("background:%1;").arg(colors::BORDER_MED()));
hl->addWidget(sep);
+ hl->addSpacing(4);
};
- auto make_btn = [&](const QString& text, const QString& fg = QString()) -> QPushButton* {
+ auto make_btn = [&](const QString& text, const char* obj = "nbSecondaryBtn") -> QPushButton* {
auto* btn = new QPushButton(text, bar);
+ btn->setObjectName(obj);
btn->setCursor(Qt::PointingHandCursor);
- QString color = fg.isEmpty() ? colors::TEXT_SECONDARY : fg;
- btn->setStyleSheet(QString("QPushButton { background:transparent; color:%1; border:none;"
- " font-family:%2; font-size:%3px; font-weight:600; padding:0 10px;"
- " letter-spacing:0.5px; }"
- "QPushButton:hover { color:%4; background:%5; }")
- .arg(color, fonts::DATA_FAMILY)
- .arg(fonts::TINY)
- .arg(colors::TEXT_PRIMARY(), colors::BG_HOVER()));
+ btn->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
return btn;
};
@@ -162,7 +333,7 @@ QWidget* CodeEditorScreen::build_toolbar() {
add_sep();
- btn_add_cell_ = make_btn(tr("+ CELL"), colors::CYAN);
+ btn_add_cell_ = make_btn(tr("+ CELL"), "nbAccentBtn");
connect(btn_add_cell_, &QPushButton::clicked, this, &CodeEditorScreen::on_add_cell);
hl->addWidget(btn_add_cell_);
@@ -172,15 +343,8 @@ QWidget* CodeEditorScreen::build_toolbar() {
add_sep();
- btn_run_all_ = new QPushButton(tr("RUN ALL"), bar);
- btn_run_all_->setCursor(Qt::PointingHandCursor);
- btn_run_all_->setStyleSheet(QString("QPushButton { background:%1; color:%2; border:none;"
- " font-family:%3; font-size:%4px; font-weight:700; padding:4px 14px;"
- " letter-spacing:0.5px; }"
- "QPushButton:hover { background:%5; }")
- .arg(colors::AMBER(), colors::BG_BASE(), fonts::DATA_FAMILY)
- .arg(fonts::TINY)
- .arg(colors::ORANGE()));
+ btn_run_all_ = make_btn(tr("▶ RUN ALL"), "nbPrimaryBtn");
+ btn_run_all_->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
connect(btn_run_all_, &QPushButton::clicked, this, &CodeEditorScreen::on_run_all);
hl->addWidget(btn_run_all_);
@@ -208,8 +372,8 @@ QWidget* CodeEditorScreen::build_toolbar() {
QWidget* CodeEditorScreen::build_status_bar() {
auto* bar = new QWidget(this);
+ bar->setObjectName("nbStatusBar");
bar->setFixedHeight(24);
- bar->setStyleSheet(QString("background:%1; border-top:1px solid %2;").arg(colors::BG_RAISED(), colors::BORDER_DIM()));
auto* hl = new QHBoxLayout(bar);
hl->setContentsMargins(10, 0, 10, 0);
@@ -242,7 +406,7 @@ void CodeEditorScreen::on_new_notebook() {
NotebookCell cell;
cell.id = new_cell_id();
cell.cell_type = "code";
- cell.source = "# Fincept Python Notebook\n"
+ cell.source = "# Fincept Notebook\n"
"# Write Python code and press Ctrl+Enter to run\n"
"\n"
"print(\"Hello from Fincept Terminal!\")";
@@ -518,20 +682,35 @@ void CodeEditorScreen::on_run_all() {
// ─────────────────────────────────────────────────────────────────────────────
void CodeEditorScreen::on_open_notebook() {
- QString path =
- QFileDialog::getOpenFileName(this, tr("Open Notebook"), {}, tr("Jupyter Notebooks (*.ipynb);;All Files (*)"));
+ const QString path =
+ QFileDialog::getOpenFileName(this, tr("Open Notebook"), {}, tr("Fincept Notebooks (*.ipynb);;All Files (*)"));
if (path.isEmpty())
return;
+ open_notebook_path(path);
+}
- QFile file(path);
- if (!file.open(QIODevice::ReadOnly))
- return;
+// Public entry point: load an .ipynb from disk and switch to the editor view.
+bool CodeEditorScreen::open_notebook_path(const QString& path) {
+ const bool ok = load_notebook_from_path(path);
+ if (ok)
+ set_view(1); // surface the editor so the loaded notebook is visible
+ return ok;
+}
- QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
+// Parse an .ipynb into the cell model and refresh the editor. Shared by the
+// Open dialog, the Library, the File Manager, and session restore.
+bool CodeEditorScreen::load_notebook_from_path(const QString& path) {
+ QFile file(path);
+ if (!file.open(QIODevice::ReadOnly)) {
+ LOG_WARN("CodeEditor", "Cannot open notebook: " + path);
+ return false;
+ }
+ const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
+ file.close();
if (doc.isNull())
- return;
+ return false;
- QJsonArray json_cells = doc.object()["cells"].toArray();
+ const QJsonArray json_cells = doc.object()["cells"].toArray();
cells_.clear();
execution_counter_ = 0;
@@ -572,6 +751,7 @@ void CodeEditorScreen::on_open_notebook() {
update_navigator();
LOG_INFO("CodeEditor", "Opened notebook: " + path);
ScreenStateManager::instance().notify_changed(this);
+ return true;
}
void CodeEditorScreen::on_save_notebook() {
@@ -583,7 +763,7 @@ void CodeEditorScreen::on_save_notebook() {
QString path = notebook_path_;
if (path.isEmpty()) {
- path = QFileDialog::getSaveFileName(this, tr("Save Notebook"), "notebook.ipynb", tr("Jupyter Notebooks (*.ipynb)"));
+ path = QFileDialog::getSaveFileName(this, tr("Save Notebook"), "notebook.ipynb", tr("Fincept Notebooks (*.ipynb)"));
if (path.isEmpty())
return;
}
@@ -725,17 +905,27 @@ void CodeEditorScreen::changeEvent(QEvent* event) {
}
void CodeEditorScreen::retranslateUi() {
+ // Header
+ if (header_title_) header_title_->setText(tr("FINCEPT NOTEBOOK"));
+ const QStringList tab_labels = {tr("LIBRARY"), tr("EDITOR")};
+ for (int i = 0; i < view_btns_.size() && i < tab_labels.size(); ++i)
+ view_btns_[i]->setText(tab_labels[i]);
+ if (lib_search_input_) lib_search_input_->setPlaceholderText(tr("Search notebooks..."));
+ if (header_new_btn_) header_new_btn_->setText(tr("+ NEW NOTEBOOK"));
+
// Toolbar
- if (toolbar_title_) toolbar_title_->setText(tr("PYTHON NOTEBOOK"));
if (btn_new_) btn_new_->setText(tr("NEW"));
if (btn_open_) btn_open_->setText(tr("OPEN"));
if (btn_save_) btn_save_->setText(tr("SAVE"));
if (btn_add_cell_) btn_add_cell_->setText(tr("+ CELL"));
if (btn_clear_out_) btn_clear_out_->setText(tr("CLEAR OUT"));
- if (btn_run_all_) btn_run_all_->setText(tr("RUN ALL"));
+ if (btn_run_all_) btn_run_all_->setText(tr("▶ RUN ALL"));
if (btn_sidebar_) btn_sidebar_->setText(tr("SIDEBAR"));
if (py_label_) py_label_->setText(tr("Python 3.11"));
refresh_kernel_label();
+ if (lib_toolbar_lbl_)
+ lib_toolbar_lbl_->setText(tr("FINCEPT NOTEBOOK LIBRARY — curated finance, economics, trading, "
+ "investing, portfolio & quant notebooks"));
// Status bar
if (shortcuts_label_)
@@ -755,24 +945,9 @@ QVariantMap CodeEditorScreen::save_state() const {
void CodeEditorScreen::restore_state(const QVariantMap& state) {
const QString path = state.value("notebook_path").toString();
- if (!path.isEmpty() && notebook_path_ != path) {
- QFile f(path);
- if (f.exists()) {
- notebook_path_ = path; // pre-set so on_open_notebook picks it up
- // simulate the open flow directly
- QFile file(path);
- if (file.open(QIODevice::ReadOnly)) {
- QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
- if (!doc.isNull()) {
- // Delegate to on_open_notebook by setting the path and triggering
- // the full load — but on_open_notebook opens a dialog so we
- // reconstruct just enough to restore the path label/status.
- // Full re-open would require extracting the load logic to a helper.
- // For now: restore the path so the title bar shows the last file.
- update_status();
- }
- }
- }
+ if (!path.isEmpty() && notebook_path_ != path && QFileInfo::exists(path)) {
+ // Fully reload the notebook (cells + outputs metadata), not just the label.
+ load_notebook_from_path(path);
}
}
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
index 484ab1d98..87a0984a9 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen.h
@@ -1,23 +1,29 @@
// src/screens/code_editor/CodeEditorScreen.h
-// Python Colab — Jupyter notebook with Obsidian design system.
-// Responsive cells, markdown rendering, keyboard shortcuts, collapsible output.
+// Fincept Notebook — two-view workspace (Library + Editor) on the Obsidian
+// design system. Library lists prebuilt finance notebooks as cards; the editor
+// runs responsive notebook cells with markdown rendering and collapsible output.
#pragma once
#include "screens/common/IStatefulScreen.h"
#include <QEvent>
+#include <QGridLayout>
#include <QHideEvent>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
+#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
+#include <QResizeEvent>
#include <QScrollArea>
#include <QShowEvent>
#include <QSplitter>
+#include <QStackedWidget>
#include <QTextBrowser>
#include <QTextEdit>
#include <QVBoxLayout>
+#include <QVector>
#include <QWidget>
namespace fincept::screens {
@@ -88,6 +94,7 @@ class CellWidget : public QWidget {
void leaveEvent(QEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void changeEvent(QEvent* event) override;
+ void showEvent(QShowEvent* event) override;
private:
void build_ui();
@@ -105,6 +112,7 @@ class CellWidget : public QWidget {
bool hovered_ = false;
bool output_collapsed_ = false;
bool md_editing_ = false;
+ bool adjusting_height_ = false; // guards adjust_editor_height re-entrancy
QString title_;
// Gutter
@@ -168,6 +176,11 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
public:
explicit CodeEditorScreen(QWidget* parent = nullptr);
+ /// Load a notebook (.ipynb) from disk into the editor and switch to the
+ /// editor view. Public entry point used by the File Manager and the
+ /// Library "OPEN" action. Returns true if the file was loaded.
+ bool open_notebook_path(const QString& path);
+
void restore_state(const QVariantMap& state) override;
QVariantMap save_state() const override;
QString state_key() const override { return "code_editor"; }
@@ -177,6 +190,7 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
void showEvent(QShowEvent* event) override;
void hideEvent(QHideEvent* event) override;
void changeEvent(QEvent* event) override;
+ void resizeEvent(QResizeEvent* event) override;
private slots:
void on_add_cell();
@@ -196,8 +210,20 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
void on_toggle_sidebar();
void on_rename_cell(const QString& cell_id);
+ // Header / Library
+ void on_view_changed(int index); // 0 = Library, 1 = Editor
+ void on_library_search(const QString& text);
+ void on_open_library_entry(int catalog_index);
+
private:
void build_ui();
+ QWidget* build_header();
+ QWidget* build_editor_page();
+ QWidget* build_library_page(); // CodeEditorScreen_Library.cpp
+ void populate_library(); // CodeEditorScreen_Library.cpp
+ void relayout_library_cards(); // CodeEditorScreen_Library.cpp
+ void set_view(int index);
+ bool load_notebook_from_path(const QString& path);
QWidget* build_toolbar();
QWidget* build_status_bar();
void retranslateUi();
@@ -227,7 +253,6 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
bool sidebar_visible_ = true;
// Toolbar / status-bar text widgets (cached for retranslateUi)
- QLabel* toolbar_title_ = nullptr;
QPushButton* btn_new_ = nullptr;
QPushButton* btn_open_ = nullptr;
QPushButton* btn_save_ = nullptr;
@@ -241,6 +266,28 @@ class CodeEditorScreen : public QWidget, public IStatefulScreen {
// Tracks whether the kernel is busy so retranslateUi can re-render the badge.
bool kernel_busy_ = false;
void refresh_kernel_label();
+
+ // ── Header + two-view stack ──────────────────────────────────────────────
+ QStackedWidget* view_stack_ = nullptr;
+ int active_view_ = 0; // 0 = Library, 1 = Editor
+ QLabel* header_title_ = nullptr;
+ QVector<QPushButton*> view_btns_; // [LIBRARY, EDITOR]
+ QLineEdit* lib_search_input_ = nullptr;
+ QPushButton* header_new_btn_ = nullptr;
+
+ // ── Library view ─────────────────────────────────────────────────────────
+ QWidget* library_page_ = nullptr;
+ QLabel* lib_toolbar_lbl_ = nullptr;
+ QLabel* lib_count_lbl_ = nullptr;
+ QScrollArea* lib_scroll_ = nullptr;
+ QWidget* cards_container_ = nullptr;
+ QGridLayout* cards_layout_ = nullptr;
+ QVector<QPushButton*> cat_chips_;
+ QVector<QPushButton*> diff_chips_;
+ QString lib_category_filter_ = "All";
+ QString lib_difficulty_filter_ = "All";
+ QString lib_search_text_;
+ int lib_columns_ = 0; // last computed column count (re-flow guard)
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
index 47d9f62bc..4f238d670 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Cells.cpp
@@ -181,7 +181,8 @@ void CellWidget::build_ui() {
editor_->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
editor_->setLineWrapMode(QTextEdit::NoWrap);
editor_->setStyleSheet(QString("QTextEdit { background:%1; color:%2; border:none;"
- " font-family:%3; font-size:%4px; padding:2px 6px;"
+ " font-family:%3, 'Menlo', 'SF Mono', 'Courier New', monospace;"
+ " font-size:%4px; padding:8px 12px;"
" selection-background-color:%5; }"
"QScrollBar:vertical { background:%1; width:5px; }"
"QScrollBar::handle:vertical { background:%6; min-height:20px; }"
@@ -327,14 +328,39 @@ void CellWidget::retranslateUi() {
}
void CellWidget::adjust_editor_height() {
- if (!editor_->isVisible())
+ // Markdown cells showing the rendered preview hide the editor — its height
+ // is irrelevant. For everything else, size to fit even while the cell's
+ // stack page is still hidden (cells are built on the Editor page while the
+ // Library page is showing), so the cell isn't stuck at a tiny default.
+ if (cell_type_ == "markdown" && !md_editing_)
return;
- // Exact content height from the layout engine + CSS padding (2+2)
- int doc_h = static_cast<int>(editor_->document()->size().height());
- int target = doc_h + 6;
- int max_h = (cell_type_ == "code") ? 600 : 300;
- int h = qBound(28, target, max_h);
- editor_->setFixedHeight(h);
+
+ // adjustSize() below re-emits documentSizeChanged (this slot is connected to
+ // it) — guard against the infinite recursion that would otherwise overflow
+ // the stack.
+ if (adjusting_height_)
+ return;
+ adjusting_height_ = true;
+
+ // Grow the editor to fit ALL its lines so the cell expands with the amount
+ // of code it holds — no inner scrollbar for code. The outer notebook scroll
+ // area handles overall scrolling. Height comes from the document layout, so
+ // it is accurate regardless of current visibility.
+ editor_->document()->adjustSize();
+ const int doc_h = static_cast<int>(editor_->document()->size().height());
+ const int target = doc_h + 8; // editor CSS padding (2+2) + breathing room
+ const int min_h = 40;
+ const int max_h = (cell_type_ == "code") ? 100000 : 800; // code grows freely
+ editor_->setFixedHeight(qBound(min_h, target, max_h));
+
+ adjusting_height_ = false;
+}
+
+void CellWidget::showEvent(QShowEvent* event) {
+ QWidget::showEvent(event);
+ // Re-measure now that the stylesheet font has been polished (QSS is applied
+ // on show); construction-time sizing may use the wrong default font metrics.
+ adjust_editor_height();
}
void CellWidget::set_cell_data(const NotebookCell& cell) {
@@ -423,7 +449,7 @@ void CellWidget::set_outputs(const QVector<CellOutput>& outputs, int exec_count)
QString fg = (out.name == "stderr") ? colors::WARNING : colors::TEXT_PRIMARY;
output_view->setStyleSheet(
QString("QTextEdit { background:transparent; color:%1; border:none;"
- " font-family:%2; font-size:%3px; padding:2px 0; }"
+ " font-family:%2, 'Menlo', 'SF Mono', monospace; font-size:%3px; padding:2px 0; }"
"QScrollBar:vertical { background:transparent; width:4px; }"
"QScrollBar::handle:vertical { background:%4; }"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
@@ -462,7 +488,7 @@ void CellWidget::set_outputs(const QVector<CellOutput>& outputs, int exec_count)
tb_view->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tb_view->setStyleSheet(
QString("QTextEdit { background:transparent; color:%1; border:none;"
- " font-family:%2; font-size:%3px; }"
+ " font-family:%2, 'Menlo', 'SF Mono', monospace; font-size:%3px; }"
"QScrollBar:vertical { background:transparent; width:4px; }"
"QScrollBar::handle:vertical { background:%4; }"
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height:0; }")
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp
new file mode 100644
index 000000000..39989b8e7
--- /dev/null
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Library.cpp
@@ -0,0 +1,294 @@
+// src/screens/code_editor/CodeEditorScreen_Library.cpp
+// Fincept Notebook — Library view: prebuilt finance notebooks as filterable
+// cards (Marketplace-style), wired to NotebookLibraryService + the editor.
+
+#include "screens/code_editor/CodeEditorScreen.h"
+
+#include "core/logging/Logger.h"
+#include "services/notebooks/NotebookLibraryService.h"
+#include "ui/theme/Theme.h"
+
+#include <QFrame>
+#include <QGridLayout>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QPushButton>
+#include <QScrollArea>
+#include <QStyle>
+#include <QVBoxLayout>
+
+#include <algorithm>
+
+namespace fincept::screens {
+
+using namespace fincept::ui;
+using fincept::services::NotebookCatalogEntry;
+using fincept::services::NotebookLibraryService;
+
+namespace {
+
+constexpr int kCardMinWidth = 300;
+constexpr int kCardSpacing = 12;
+
+int compute_columns(int viewport_width) {
+ const int usable = viewport_width - 28; // grid margins
+ int cols = (usable + kCardSpacing) / (kCardMinWidth + kCardSpacing);
+ return std::clamp(cols, 1, 4);
+}
+
+// Object name for a difficulty badge → maps to the colour rules in kStyle().
+const char* difficulty_badge_object(const QString& difficulty) {
+ if (difficulty.compare("Beginner", Qt::CaseInsensitive) == 0)
+ return "nbDiffBeginner";
+ if (difficulty.compare("Hard", Qt::CaseInsensitive) == 0)
+ return "nbDiffHard";
+ return "nbDiffIntermediate";
+}
+
+} // namespace
+
+// ── Page construction ───────────────────────────────────────────────────────
+
+QWidget* CodeEditorScreen::build_library_page() {
+ auto* page = new QWidget(this);
+ auto* root = new QVBoxLayout(page);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // Toolbar row: descriptive label + count.
+ auto* toolbar = new QWidget(page);
+ toolbar->setFixedHeight(34);
+ auto* tl = new QHBoxLayout(toolbar);
+ tl->setContentsMargins(14, 0, 14, 0);
+ lib_toolbar_lbl_ = new QLabel(tr("FINCEPT NOTEBOOK LIBRARY — curated finance, economics, trading, "
+ "investing, portfolio & quant notebooks"),
+ toolbar);
+ lib_toolbar_lbl_->setObjectName("nbLibLabel");
+ lib_toolbar_lbl_->setStyleSheet(QString("font-family:%1; font-size:%2px; font-weight:700; letter-spacing:0.3px;")
+ .arg(fonts::DATA_FAMILY)
+ .arg(fonts::TINY));
+ tl->addWidget(lib_toolbar_lbl_);
+ tl->addStretch(1);
+ lib_count_lbl_ = new QLabel(toolbar);
+ lib_count_lbl_->setObjectName("nbLibLabel");
+ lib_count_lbl_->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
+ tl->addWidget(lib_count_lbl_);
+ root->addWidget(toolbar);
+
+ // Filter chips: category row + difficulty row.
+ auto make_chip_row = [&](const QStringList& labels, QVector<QPushButton*>& store, bool is_category) {
+ auto* row = new QWidget(page);
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(14, 2, 14, 4);
+ rl->setSpacing(6);
+ for (const QString& label : labels) {
+ auto* chip = new QPushButton(label, row);
+ chip->setObjectName("nbChip");
+ chip->setCursor(Qt::PointingHandCursor);
+ chip->setProperty("active", label == "All");
+ chip->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
+ connect(chip, &QPushButton::clicked, this, [this, label, is_category]() {
+ if (is_category)
+ lib_category_filter_ = label;
+ else
+ lib_difficulty_filter_ = label;
+ // Re-read the member group through `this` (capturing the local
+ // reference parameter would dangle once build_library_page returns).
+ QVector<QPushButton*>& group = is_category ? cat_chips_ : diff_chips_;
+ for (QPushButton* c : group) {
+ c->setProperty("active", c->text() == label);
+ c->style()->unpolish(c);
+ c->style()->polish(c);
+ }
+ populate_library();
+ });
+ store.append(chip);
+ rl->addWidget(chip);
+ }
+ rl->addStretch(1);
+ root->addWidget(row);
+ };
+ make_chip_row({tr("All"), tr("Finance"), tr("Economics"), tr("Trading"), tr("Investing"), tr("Portfolio"),
+ tr("Quant")},
+ cat_chips_, true);
+ make_chip_row({tr("All"), tr("Beginner"), tr("Intermediate"), tr("Hard")}, diff_chips_, false);
+
+ // Scrollable card grid.
+ lib_scroll_ = new QScrollArea(page);
+ lib_scroll_->setWidgetResizable(true);
+ lib_scroll_->setFrameShape(QFrame::NoFrame);
+ lib_scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+
+ cards_container_ = new QWidget(lib_scroll_);
+ cards_layout_ = new QGridLayout(cards_container_);
+ cards_layout_->setContentsMargins(14, 8, 14, 24);
+ cards_layout_->setHorizontalSpacing(kCardSpacing);
+ cards_layout_->setVerticalSpacing(kCardSpacing);
+ cards_layout_->setAlignment(Qt::AlignTop);
+ lib_scroll_->setWidget(cards_container_);
+ root->addWidget(lib_scroll_, 1);
+
+ return page;
+}
+
+// ── Card factory ────────────────────────────────────────────────────────────
+
+static QWidget* build_notebook_card(QWidget* parent, const NotebookCatalogEntry& e) {
+ auto* card = new QFrame(parent);
+ card->setObjectName("nbCard");
+ card->setMinimumHeight(150);
+ auto* v = new QVBoxLayout(card);
+ v->setContentsMargins(14, 12, 14, 12);
+ v->setSpacing(8);
+
+ // Badge row: difficulty + category + est. time.
+ auto* badges = new QHBoxLayout;
+ badges->setSpacing(6);
+ auto* diff = new QLabel(e.difficulty.toUpper(), card);
+ diff->setObjectName(difficulty_badge_object(e.difficulty));
+ diff->setStyleSheet(QString("font-family:%1; font-size:10px;").arg(fonts::DATA_FAMILY));
+ badges->addWidget(diff);
+ auto* cat = new QLabel(e.category.toUpper(), card);
+ cat->setObjectName("nbCatBadge");
+ cat->setStyleSheet(QString("font-family:%1; font-size:10px;").arg(fonts::DATA_FAMILY));
+ badges->addWidget(cat);
+ badges->addStretch(1);
+ auto* meta = new QLabel(QObject::tr("~%1 min").arg(e.est_minutes), card);
+ meta->setObjectName("nbCardMeta");
+ meta->setStyleSheet(QString("font-family:%1; font-size:10px;").arg(fonts::DATA_FAMILY));
+ badges->addWidget(meta);
+ v->addLayout(badges);
+
+ // Title.
+ auto* title = new QLabel(e.title, card);
+ title->setObjectName("nbCardTitle");
+ title->setWordWrap(true);
+ title->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::DATA));
+ v->addWidget(title);
+
+ // Summary.
+ auto* summary = new QLabel(e.summary, card);
+ summary->setObjectName("nbCardSummary");
+ summary->setWordWrap(true);
+ summary->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
+ v->addWidget(summary);
+
+ v->addStretch(1);
+
+ // Footer: requires + OPEN.
+ auto* footer = new QHBoxLayout;
+ auto* req = new QLabel(e.requirements, card);
+ req->setObjectName("nbCardMeta");
+ req->setStyleSheet(QString("font-family:%1; font-size:10px;").arg(fonts::DATA_FAMILY));
+ footer->addWidget(req);
+ footer->addStretch(1);
+ auto* open_btn = new QPushButton(QObject::tr("OPEN"), card);
+ open_btn->setObjectName("nbCardOpenBtn");
+ open_btn->setCursor(Qt::PointingHandCursor);
+ open_btn->setStyleSheet(QString("font-family:%1; font-size:%2px;").arg(fonts::DATA_FAMILY).arg(fonts::TINY));
+ footer->addWidget(open_btn);
+ v->addLayout(footer);
+
+ // Expose the OPEN button so the caller can wire it to the catalog index.
+ card->setProperty("open_btn_ptr", QVariant::fromValue(static_cast<void*>(open_btn)));
+ return card;
+}
+
+// ── Populate + filter ───────────────────────────────────────────────────────
+
+void CodeEditorScreen::populate_library() {
+ if (!cards_layout_ || !lib_scroll_)
+ return;
+
+ // Clear existing cards.
+ while (QLayoutItem* item = cards_layout_->takeAt(0)) {
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+
+ const auto& catalog = NotebookLibraryService::instance().catalog();
+ const QString search = lib_search_text_.trimmed();
+
+ const int cols = compute_columns(lib_scroll_->viewport()->width());
+ lib_columns_ = cols;
+ for (int c = 0; c < cols; ++c)
+ cards_layout_->setColumnStretch(c, 1);
+
+ int shown = 0, beg = 0, inter = 0, hard = 0;
+ int grid_index = 0;
+ for (int i = 0; i < catalog.size(); ++i) {
+ const NotebookCatalogEntry& e = catalog[i];
+ if (lib_category_filter_ != "All" && e.category.compare(lib_category_filter_, Qt::CaseInsensitive) != 0)
+ continue;
+ if (lib_difficulty_filter_ != "All" && e.difficulty.compare(lib_difficulty_filter_, Qt::CaseInsensitive) != 0)
+ continue;
+ if (!search.isEmpty() && !e.title.contains(search, Qt::CaseInsensitive) &&
+ !e.category.contains(search, Qt::CaseInsensitive) && !e.summary.contains(search, Qt::CaseInsensitive))
+ continue;
+
+ auto* card = build_notebook_card(cards_container_, e);
+ auto* open_btn = static_cast<QPushButton*>(card->property("open_btn_ptr").value<void*>());
+ if (open_btn) {
+ const int catalog_index = i;
+ connect(open_btn, &QPushButton::clicked, this, [this, catalog_index]() { on_open_library_entry(catalog_index); });
+ }
+ cards_layout_->addWidget(card, grid_index / cols, grid_index % cols);
+ ++grid_index;
+
+ ++shown;
+ if (e.difficulty.compare("Beginner", Qt::CaseInsensitive) == 0)
+ ++beg;
+ else if (e.difficulty.compare("Hard", Qt::CaseInsensitive) == 0)
+ ++hard;
+ else
+ ++inter;
+ }
+
+ if (shown == 0) {
+ auto* empty = new QLabel(catalog.isEmpty()
+ ? tr("Notebook library not found. Rebuild the app to bundle the notebooks.")
+ : tr("No notebooks match your filters."),
+ cards_container_);
+ empty->setObjectName("nbCardSummary");
+ empty->setStyleSheet(QString("font-family:%1; font-size:%2px; padding:24px;")
+ .arg(fonts::DATA_FAMILY)
+ .arg(fonts::SMALL));
+ cards_layout_->addWidget(empty, 0, 0);
+ }
+
+ if (lib_count_lbl_)
+ lib_count_lbl_->setText(tr("%1 notebooks · %2 beginner · %3 intermediate · %4 hard")
+ .arg(shown)
+ .arg(beg)
+ .arg(inter)
+ .arg(hard));
+}
+
+void CodeEditorScreen::relayout_library_cards() {
+ if (!cards_layout_ || !lib_scroll_)
+ return;
+ const int cols = compute_columns(lib_scroll_->viewport()->width());
+ if (cols != lib_columns_)
+ populate_library(); // re-flow only when the column count actually changes
+}
+
+void CodeEditorScreen::on_library_search(const QString& text) {
+ lib_search_text_ = text;
+ populate_library();
+}
+
+void CodeEditorScreen::on_open_library_entry(int catalog_index) {
+ const auto& catalog = NotebookLibraryService::instance().catalog();
+ if (catalog_index < 0 || catalog_index >= catalog.size())
+ return;
+ const NotebookCatalogEntry& e = catalog[catalog_index];
+ const QString path = NotebookLibraryService::instance().working_copy_for(e);
+ if (path.isEmpty()) {
+ LOG_WARN("CodeEditor", "Could not open library notebook: " + e.id);
+ return;
+ }
+ open_notebook_path(path); // loads + switches to the editor view
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Navigator.cpp b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Navigator.cpp
index 4686f88c1..a56fbd78e 100644
--- a/fincept-qt/src/screens/code_editor/CodeEditorScreen_Navigator.cpp
+++ b/fincept-qt/src/screens/code_editor/CodeEditorScreen_Navigator.cpp
@@ -41,6 +41,36 @@ namespace fincept::screens {
using namespace fincept::ui;
+namespace {
+// Build a clean, human-readable cell name from raw cell source: take the first
+// non-empty line and strip markdown header/list/quote markers, code-fence
+// backticks, and any leading emoji/symbol — so a banner like
+// "# 📘 Fincept Notebook — Time Value of Money" shows as
+// "Fincept Notebook — Time Value of Money" and "# Setup" shows as "Setup".
+QString clean_cell_name(const QString& source) {
+ QString s;
+ for (const QString& ln : source.split('\n')) {
+ const QString t = ln.trimmed();
+ if (!t.isEmpty()) {
+ s = t;
+ break;
+ }
+ }
+ if (s.isEmpty())
+ return {};
+ s.remove('`');
+ // Strip a leading run of markdown block markers + whitespace.
+ int i = 0;
+ while (i < s.size() && QStringLiteral("#>*-=+ \t").contains(s.at(i)))
+ ++i;
+ s = s.mid(i);
+ // Drop a leading emoji / symbol run so "📘 Title" becomes "Title".
+ while (!s.isEmpty() && !s.at(0).isLetterOrNumber() && s.at(0) != '(' && s.at(0) != '"' && s.at(0) != '\'')
+ s.remove(0, 1);
+ return s.simplified();
+}
+} // namespace
+
CellNavigator::CellNavigator(QWidget* parent) : QWidget(parent) {
auto* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
@@ -64,8 +94,8 @@ CellNavigator::CellNavigator(QWidget* parent) : QWidget(parent) {
list_ = new QListWidget(this);
list_->setStyleSheet(
QString("QListWidget { background:%1; border:none; outline:none;"
- " font-family:%2; font-size:%3px; }"
- "QListWidget::item { color:%4; padding:6px 10px;"
+ " font-family:%2, 'Menlo', 'SF Mono', monospace; font-size:%3px; }"
+ "QListWidget::item { color:%4; padding:7px 10px;"
" border-bottom:1px solid %5; }"
"QListWidget::item:selected { background:%6; color:%7;"
" border-left:2px solid %7; }"
@@ -122,21 +152,24 @@ void CellNavigator::rebuild(const QVector<NotebookCell>& cells, const QString& s
int selected_row = -1;
for (int i = 0; i < cells.size(); ++i) {
const auto& cell = cells[i];
- QString type_tag = (cell.cell_type == "code") ? "PY" : "MD";
+ const QString type_tag = (cell.cell_type == "code") ? "PY" : "MD";
QString exec_tag;
if (cell.execution_count > 0)
- exec_tag = QString(" [%1]").arg(cell.execution_count);
-
- QString preview = cell.title.trimmed();
- if (preview.isEmpty())
- preview = cell.source.split('\n').first().trimmed();
- if (preview.isEmpty())
- preview = tr("(empty)");
-
- const QString label = QString("%1 %2 %3%4").arg(i + 1, 2).arg(type_tag, -2).arg(preview, exec_tag);
+ exec_tag = QString(" [%1]").arg(cell.execution_count);
+
+ // Prefer a user/authored title; otherwise derive a clean name from the
+ // cell source (strips markdown markers + emoji).
+ QString name = cell.title.trimmed();
+ if (name.isEmpty())
+ name = clean_cell_name(cell.source);
+ if (name.isEmpty())
+ name = tr("(empty)");
+
+ // " 1 PY Fincept Notebook — Time Value of Money [3]"
+ const QString label = QString("%1 %2 %3%4").arg(i + 1, 2).arg(type_tag, -2).arg(name, exec_tag);
auto* item = new QListWidgetItem(label, list_);
item->setData(Qt::UserRole, cell.id);
- item->setToolTip(label);
+ item->setToolTip(name);
if (cell.id == selected_id)
selected_row = i;
diff --git a/fincept-qt/src/screens/equity_research/EquityOverviewTab.h b/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
index 233933ac5..cbd2ac568 100644
--- a/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
+++ b/fincept-qt/src/screens/equity_research/EquityOverviewTab.h
@@ -52,6 +52,9 @@ class EquityOverviewTab : public QWidget {
void set_symbol(const QString& symbol);
static QString currency_symbol(const QString& currency_code);
+ // Compact magnitude formatter (1.90T / 890.00B / …). Public so the parent
+ // research screen's title bar formats market cap identically to this tab.
+ static QString fmt_large(double v);
protected:
void changeEvent(QEvent* event) override;
@@ -99,7 +102,6 @@ class EquityOverviewTab : public QWidget {
void rebuild_chart(const QVector<services::equity::Candle>& candles);
void switch_period(QPushButton* btn, const QString& period);
- static QString fmt_large(double v);
static QString fmt_pct(double v);
QString fmt_price(double v) const;
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 33f5734f8..37bc9831d 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -20,11 +20,26 @@
#include "services/backtesting/BacktestingService.h"
#include "services/equity/EquityResearchService.h"
#include "ui/theme/Theme.h"
+#include "python/PythonRunner.h"
#include <QApplication>
+#include <QComboBox>
+#include <QDateTime>
+#include <QDialog>
#include <QEvent>
+#include <QFile>
+#include <QFileDialog>
+#include <QFormLayout>
#include <QFrame>
#include <QHBoxLayout>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QMessageBox>
+#include <QPointer>
+#include <QPushButton>
+#include <QTextStream>
+#include <QTimeZone>
#include <QVBoxLayout>
namespace fincept::screens {
@@ -183,6 +198,21 @@ QWidget* EquityResearchScreen::build_title_bar() {
});
hl->addWidget(backtest_btn);
+ auto* csv_btn = new QPushButton(tr("↓ CSV"), container);
+ csv_btn->setCursor(Qt::PointingHandCursor);
+ csv_btn->setFixedHeight(24);
+ csv_btn->setToolTip(tr("Download price history (CSV) from Yahoo Finance"));
+ csv_btn->setStyleSheet(
+ QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"
+ "padding:0 10px; font-size:%3px; font-family:%4; font-weight:700; letter-spacing:0.5px; }"
+ "QPushButton:hover { background:%5; color:%6; }")
+ .arg(ui::colors::AMBER(), ui::colors::AMBER_DIM())
+ .arg(ui::fonts::TINY)
+ .arg(ui::fonts::DATA_FAMILY)
+ .arg(ui::colors::AMBER(), ui::colors::BG_BASE()));
+ connect(csv_btn, &QPushButton::clicked, this, &EquityResearchScreen::on_download_csv_clicked);
+ hl->addWidget(csv_btn);
+
hl->addStretch();
hint_label_ = new QLabel;
@@ -237,6 +267,20 @@ void EquityResearchScreen::on_info_loaded(services::equity::StockInfo info) {
if (info.symbol != current_symbol_)
return;
current_currency_ = info.currency;
+
+ // Populate the title-bar MKT CAP. The value comes straight from yfinance's
+ // `info` (the Overview tab renders the same StockInfo::market_cap); the title
+ // bar simply was never wired to it, so it sat at the "—" placeholder.
+ if (mktcap_label_) {
+ if (info.market_cap > 0) {
+ const QString cs =
+ EquityOverviewTab::currency_symbol(info.currency.isEmpty() ? "USD" : info.currency);
+ mktcap_label_->setText(
+ tr("MKT CAP: %1%2").arg(cs, EquityOverviewTab::fmt_large(info.market_cap)));
+ } else {
+ mktcap_label_->setText(tr("MKT CAP: %1").arg(QStringLiteral("—")));
+ }
+ }
}
void EquityResearchScreen::on_tab_changed(int index) {
@@ -355,6 +399,155 @@ void EquityResearchScreen::update_quote_bar(const services::equity::QuoteData& q
hl_label_->setText(tr("H:%1%2 L:%1%3").arg(cs).arg(q.high, 0, 'f', 2).arg(q.low, 0, 'f', 2));
}
+// ── CSV price-data download (yfinance) ───────────────────────────────────────
+// current_symbol_ is already in yfinance form on this screen (the quote/info/
+// historical loads all pass it straight through), so it is handed to
+// historical_period unchanged — no exchange-suffix resolution needed here.
+
+void EquityResearchScreen::on_download_csv_clicked() {
+ const QString symbol = current_symbol_.trimmed();
+ if (symbol.isEmpty()) {
+ QMessageBox::information(this, tr("Download Price Data"), tr("Load a symbol first."));
+ return;
+ }
+
+ auto* dlg = new QDialog(this);
+ dlg->setWindowTitle(tr("Download Price Data — %1").arg(symbol));
+ dlg->setModal(true);
+ dlg->setMinimumWidth(380);
+
+ auto* root = new QVBoxLayout(dlg);
+ root->setContentsMargins(16, 16, 16, 16);
+ root->setSpacing(10);
+
+ auto* title = new QLabel(
+ tr("Export Yahoo Finance price history for <b>%1</b> as CSV.").arg(symbol), dlg);
+ title->setWordWrap(true);
+ root->addWidget(title);
+
+ auto* form = new QFormLayout();
+ form->setSpacing(8);
+
+ auto* period_combo = new QComboBox(dlg);
+ period_combo->addItems({"1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "max"});
+ period_combo->setCurrentText("1y");
+ form->addRow(tr("Period:"), period_combo);
+
+ auto* interval_combo = new QComboBox(dlg);
+ interval_combo->addItems({"1m", "5m", "15m", "30m", "1h", "1d", "1wk", "1mo"});
+ interval_combo->setCurrentText("1d");
+ form->addRow(tr("Interval:"), interval_combo);
+ root->addLayout(form);
+
+ auto* note = new QLabel(
+ tr("Note: intraday intervals (below 1d) are only available for roughly the last 60 days."),
+ dlg);
+ note->setWordWrap(true);
+ note->setStyleSheet(QString("color:%1; font-size:10px;").arg(ui::colors::TEXT_TERTIARY()));
+ root->addWidget(note);
+
+ auto* status = new QLabel(dlg);
+ status->setWordWrap(true);
+ status->setVisible(false);
+ root->addWidget(status);
+
+ auto* buttons = new QHBoxLayout();
+ buttons->addStretch();
+ auto* cancel_btn = new QPushButton(tr("Cancel"), dlg);
+ auto* download_btn = new QPushButton(tr("Download"), dlg);
+ download_btn->setDefault(true);
+ buttons->addWidget(cancel_btn);
+ buttons->addWidget(download_btn);
+ root->addLayout(buttons);
+
+ connect(cancel_btn, &QPushButton::clicked, dlg, &QDialog::reject);
+
+ connect(download_btn, &QPushButton::clicked, dlg,
+ [dlg, symbol, period_combo, interval_combo, status, download_btn, cancel_btn]() {
+ const QString period = period_combo->currentText();
+ const QString interval = interval_combo->currentText();
+
+ auto set_busy = [=](bool busy) {
+ download_btn->setEnabled(!busy);
+ cancel_btn->setEnabled(!busy);
+ period_combo->setEnabled(!busy);
+ interval_combo->setEnabled(!busy);
+ };
+ set_busy(true);
+ status->setVisible(true);
+ status->setStyleSheet(
+ QString("color:%1; font-size:11px;").arg(ui::colors::TEXT_SECONDARY()));
+ status->setText(tr("Fetching from Yahoo Finance…"));
+
+ // Terminal step: write the OHLCV array to a user-chosen CSV file.
+ auto finish = [=](const QJsonArray& candles) {
+ if (candles.isEmpty()) {
+ status->setStyleSheet(
+ QString("color:%1; font-size:11px;").arg(ui::colors::NEGATIVE()));
+ status->setText(tr("No data returned for %1 (%2). Try a longer period "
+ "or a daily interval.")
+ .arg(symbol, interval));
+ set_busy(false);
+ return;
+ }
+
+ QString safe;
+ for (const QChar ch : symbol)
+ safe += ch.isLetterOrNumber() ? ch : QChar('_');
+ const QString suggested =
+ QStringLiteral("%1_%2_%3.csv").arg(safe, period, interval);
+ const QString path = QFileDialog::getSaveFileName(
+ dlg, tr("Save Price Data"), suggested, tr("CSV Files (*.csv)"));
+ if (path.isEmpty()) {
+ status->setText(tr("Save cancelled."));
+ set_busy(false);
+ return;
+ }
+
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
+ QMessageBox::warning(
+ dlg, tr("Export failed"),
+ tr("Could not open the file for writing:\n%1").arg(file.errorString()));
+ set_busy(false);
+ return;
+ }
+ QTextStream out(&file);
+ out.setEncoding(QStringConverter::Utf8);
+ out << "datetime,timestamp,open,high,low,close,volume\n";
+ for (const auto& v : candles) {
+ const QJsonObject c = v.toObject();
+ const auto ts = static_cast<qint64>(c.value("timestamp").toDouble());
+ const QString dt = QDateTime::fromSecsSinceEpoch(ts, QTimeZone::UTC)
+ .toString("yyyy-MM-dd HH:mm:ss");
+ out << dt << ',' << ts << ',' << c.value("open").toDouble() << ','
+ << c.value("high").toDouble() << ',' << c.value("low").toDouble() << ','
+ << c.value("close").toDouble() << ','
+ << static_cast<qint64>(c.value("volume").toDouble()) << '\n';
+ }
+ file.close();
+ QMessageBox::information(
+ dlg, tr("Download complete"),
+ tr("Saved %1 rows for %2 to:\n%3").arg(candles.size()).arg(symbol, path));
+ dlg->accept();
+ };
+
+ // historical_period is daemon-routed in PythonRunner, so this is fast.
+ QPointer<QDialog> guard(dlg);
+ python::PythonRunner::instance().run(
+ "yfinance_data.py", {"historical_period", symbol, period, interval},
+ [guard, finish](python::PythonResult res) {
+ if (!guard)
+ return;
+ finish(QJsonDocument::fromJson(python::extract_json(res.output).toUtf8())
+ .array());
+ });
+ });
+
+ dlg->exec();
+ dlg->deleteLater();
+}
+
// ── Re-translation ───────────────────────────────────────────────────────────
// The quote bar is mostly numeric data — only the label prefixes (VOL/H/L,
// MKT CAP) need localization. update_quote_bar() rewrites VOL/H/L on every
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
index 4e15a04ce..d92a50cb0 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.h
@@ -49,6 +49,9 @@ class EquityResearchScreen : public QWidget, public IStatefulScreen, public IGro
void on_quote_loaded(services::equity::QuoteData quote);
void on_info_loaded(services::equity::StockInfo info);
void on_tab_changed(int index);
+ // Opens the "Download Price Data (CSV)" dialog and exports yfinance OHLCV
+ // history for current_symbol_ to a user-chosen file.
+ void on_download_csv_clicked();
private:
void build_ui();
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
index a1062063b..7e4f937e1 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
@@ -405,19 +405,13 @@ EquityOrderEntry::EquityOrderEntry(QWidget* parent) : QWidget(parent) {
order.symbol = current_symbol_;
order.exchange = exchange_combo_->currentText();
order.side = is_buy_side_ ? trading::OrderSide::Buy : trading::OrderSide::Sell;
- static const trading::OrderType type_map[] = {trading::OrderType::Market, trading::OrderType::Limit,
- trading::OrderType::StopLoss, trading::OrderType::StopLossLimit};
- order.order_type = type_map[active_type_];
+ order.order_type = selected_order_type();
order.quantity = qty;
order.price = price_edit_->text().toDouble();
order.stop_price = stop_price_edit_->text().toDouble();
order.stop_loss = sl_edit_ ? sl_edit_->text().toDouble() : 0.0;
order.take_profit = tp_edit_ ? tp_edit_->text().toDouble() : 0.0;
- const int prod_idx = product_combo_->currentIndex();
- if (!product_types_.isEmpty() && prod_idx >= 0 && prod_idx < product_types_.size())
- order.product_type = product_types_[prod_idx].value;
- else
- order.product_type = trading::ProductType::Intraday;
+ order.product_type = selected_product_type();
emit broadcast_requested(order);
});
submit_row->addWidget(broadcast_btn_, 1);
@@ -546,6 +540,20 @@ void EquityOrderEntry::set_exchange(const QString& exchange) {
}
}
+trading::OrderType EquityOrderEntry::selected_order_type() const {
+ static const trading::OrderType type_map[] = {trading::OrderType::Market, trading::OrderType::Limit,
+ trading::OrderType::StopLoss, trading::OrderType::StopLossLimit};
+ const int idx = (active_type_ >= 0 && active_type_ < 4) ? active_type_ : 0;
+ return type_map[idx];
+}
+
+trading::ProductType EquityOrderEntry::selected_product_type() const {
+ const int prod_idx = product_combo_->currentIndex();
+ if (!product_types_.isEmpty() && prod_idx >= 0 && prod_idx < product_types_.size())
+ return product_types_[prod_idx].value;
+ return trading::ProductType::Intraday;
+}
+
void EquityOrderEntry::on_submit() {
const double qty = qty_edit_->text().toDouble();
if (qty <= 0) {
@@ -559,21 +567,13 @@ void EquityOrderEntry::on_submit() {
order.exchange = exchange_combo_->currentText();
order.side = is_buy_side_ ? trading::OrderSide::Buy : trading::OrderSide::Sell;
- static const trading::OrderType type_map[] = {trading::OrderType::Market, trading::OrderType::Limit,
- trading::OrderType::StopLoss, trading::OrderType::StopLossLimit};
- order.order_type = type_map[active_type_];
+ order.order_type = selected_order_type();
order.quantity = qty;
order.price = price_edit_->text().toDouble();
order.stop_price = stop_price_edit_->text().toDouble();
order.stop_loss = sl_edit_ ? sl_edit_->text().toDouble() : 0.0;
order.take_profit = tp_edit_ ? tp_edit_->text().toDouble() : 0.0;
-
- // Product type from profile-driven combo
- const int prod_idx = product_combo_->currentIndex();
- if (!product_types_.isEmpty() && prod_idx >= 0 && prod_idx < product_types_.size())
- order.product_type = product_types_[prod_idx].value;
- else
- order.product_type = trading::ProductType::Intraday;
+ order.product_type = selected_product_type();
emit order_submitted(order);
}
@@ -624,13 +624,8 @@ void EquityOrderEntry::fetch_margin_async() {
order.quantity = qty;
order.price = price_edit_->text().toDouble();
order.stop_price = stop_price_edit_->text().toDouble();
- static const trading::OrderType type_map[] = {trading::OrderType::Market, trading::OrderType::Limit,
- trading::OrderType::StopLoss, trading::OrderType::StopLossLimit};
- order.order_type = type_map[active_type_];
- const int prod_idx = product_combo_->currentIndex();
- order.product_type = (!product_types_.isEmpty() && prod_idx >= 0 && prod_idx < product_types_.size())
- ? product_types_[prod_idx].value
- : trading::ProductType::Intraday;
+ order.order_type = selected_order_type();
+ order.product_type = selected_product_type();
const QString bid = broker_id_;
QPointer<EquityOrderEntry> self = this;
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
index 43fa57a33..9cb676c7d 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.h
@@ -51,6 +51,11 @@ class EquityOrderEntry : public QWidget {
void set_buy_side(bool is_buy);
void set_order_type(int idx);
+ // Resolve the current form selections into trading enums (dedups the
+ // order-type / product-type mapping repeated across submit/broadcast/margin).
+ trading::OrderType selected_order_type() const;
+ trading::ProductType selected_product_type() const;
+
// Options strategy helpers
bool build_strategy(trading::OptionsStrategy& out) const; // returns false when strategy == None or inputs invalid
void refresh_strategy_preview();
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 6028ab909..56f466ff1 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -493,7 +493,7 @@ void EquityTradingScreen::on_instruments_ready(const QString& broker_id) {
auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
stream->fetch_time_sales(selected_symbol_);
@@ -593,7 +593,7 @@ void EquityTradingScreen::init_focused_account() {
auto* stream = dsm.stream_for(focused_account_id_);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
stream->fetch_time_sales(selected_symbol_);
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 53aa5ff33..36c6278f9 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -144,7 +144,7 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
auto* stream = dsm.stream_for(account_id);
if (stream) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
stream->fetch_orderbook(selected_symbol_);
stream->fetch_time_sales(selected_symbol_);
@@ -347,7 +347,7 @@ void EquityTradingScreen::on_accounts_clicked() {
auto* stream = DataStreamManager::instance().stream_for(account_id);
if (stream && account_id == focused_account_id_) {
stream->set_selected_symbol(selected_symbol_, selected_exchange_);
- stream->subscribe_symbols(watchlist_symbols_);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), watchlist_symbols_);
}
AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
update_connection_status();
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
index d9280ba17..7ae56dde1 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Watchlists.cpp
@@ -154,7 +154,7 @@ void EquityTradingScreen::apply_active_watchlist(bool resubscribe) {
auto* stream = trading::DataStreamManager::instance().stream_for(focused_account_id_);
if (stream) {
- stream->subscribe_symbols(eff);
+ stream->subscribe_symbols(QStringLiteral("equity:watchlist"), eff);
stream->fetch_orderbook(selected_symbol_);
}
if (isVisible() && hub_active_)
diff --git a/fincept-qt/src/services/llm/LlmRequestBuilders.cpp b/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
index 7d959c66e..f505f5715 100644
--- a/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
+++ b/fincept-qt/src/services/llm/LlmRequestBuilders.cpp
@@ -90,23 +90,28 @@ QJsonObject LlmService::build_anthropic_request(const QString& user_message,
req["stream"] = true;
// Anthropic tools: bare {name, description, input_schema} — no OpenAI-style "type":"function" wrapper.
- if (detail::effective_tools_enabled(tools_enabled_)) {
- QJsonArray ant_tools;
- auto all_tools = mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_));
- for (const auto& tool : all_tools) {
- QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
- QJsonObject schema = tool.input_schema;
- if (schema.isEmpty()) {
- schema["type"] = "object";
- schema["properties"] = QJsonObject();
- }
- ant_tools.append(
- QJsonObject{{"name", fn_name}, {"description", tool.description}, {"input_schema", schema}});
+ QJsonArray ant_tools = build_anthropic_tools();
+ if (!ant_tools.isEmpty())
+ req["tools"] = ant_tools;
+ return req;
+}
+
+QJsonArray LlmService::build_anthropic_tools() {
+ QJsonArray ant_tools;
+ if (!detail::effective_tools_enabled(tools_enabled_))
+ return ant_tools;
+ auto all_tools = mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_));
+ for (const auto& tool : all_tools) {
+ QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
+ QJsonObject schema = tool.input_schema;
+ if (schema.isEmpty()) {
+ schema["type"] = "object";
+ schema["properties"] = QJsonObject();
}
- if (!ant_tools.isEmpty())
- req["tools"] = ant_tools;
+ ant_tools.append(
+ QJsonObject{{"name", fn_name}, {"description", tool.description}, {"input_schema", schema}});
}
- return req;
+ return ant_tools;
}
QJsonObject LlmService::build_gemini_request(const QString& user_message,
@@ -131,27 +136,32 @@ QJsonObject LlmService::build_gemini_request(const QString& user_message,
}
// Gemini tools: tools[{functionDeclarations:[{name, description, parameters}]}].
- auto all_tools = detail::effective_tools_enabled(tools_enabled_)
- ? mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_))
- : std::vector<mcp::UnifiedTool>{};
- if (!all_tools.empty()) {
- QJsonArray fn_decls;
- for (const auto& tool : all_tools) {
- QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
- QJsonObject schema = tool.input_schema;
- if (schema.isEmpty()) {
- schema["type"] = "object";
- schema["properties"] = QJsonObject();
- }
- fn_decls.append(QJsonObject{{"name", fn_name}, {"description", tool.description}, {"parameters", schema}});
- }
- if (!fn_decls.isEmpty())
- req["tools"] = QJsonArray{QJsonObject{{"functionDeclarations", fn_decls}}};
- }
+ QJsonArray gem_tools = build_gemini_tools();
+ if (!gem_tools.isEmpty())
+ req["tools"] = gem_tools;
return req;
}
+QJsonArray LlmService::build_gemini_tools() {
+ if (!detail::effective_tools_enabled(tools_enabled_))
+ return {};
+ auto all_tools = mcp::McpService::instance().get_all_tools(detail::apply_request_policy(tool_filter_));
+ QJsonArray fn_decls;
+ for (const auto& tool : all_tools) {
+ QString fn_name = tool.server_id + "__" + mcp::McpProvider::encode_tool_name_for_wire(tool.name);
+ QJsonObject schema = tool.input_schema;
+ if (schema.isEmpty()) {
+ schema["type"] = "object";
+ schema["properties"] = QJsonObject();
+ }
+ fn_decls.append(QJsonObject{{"name", fn_name}, {"description", tool.description}, {"parameters", schema}});
+ }
+ if (fn_decls.isEmpty())
+ return {};
+ return QJsonArray{QJsonObject{{"functionDeclarations", fn_decls}}};
+}
+
QJsonObject LlmService::build_fincept_request(const QString& user_message,
const std::vector<ConversationMessage>& history, bool with_tools) {
// /research/chat uses OpenAI messages format.
diff --git a/fincept-qt/src/services/llm/LlmRequestPolicy.h b/fincept-qt/src/services/llm/LlmRequestPolicy.h
index fc1aae7af..1a21e598a 100644
--- a/fincept-qt/src/services/llm/LlmRequestPolicy.h
+++ b/fincept-qt/src/services/llm/LlmRequestPolicy.h
@@ -19,6 +19,9 @@
#include "services/llm/LlmService.h"
#include "mcp/McpTypes.h"
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QSet>
#include <QString>
#include <functional>
@@ -87,4 +90,45 @@ inline mcp::ToolFilter apply_request_policy(const mcp::ToolFilter& base) {
return out;
}
+// ── Tool RAG activation ──────────────────────────────────────────────────
+//
+// When Tool RAG is on, the model is only sent the ~7 Tier-0 tools each turn and
+// discovers the rest via tool_list / tool_describe. Those meta-tools hand back
+// the discovered tool as *text* — but a structured function-calling model
+// (Kimi, OpenAI, Groq, …) can only emit a tool_call for a function actually
+// DECLARED in the request's `tools` array. Without re-declaring what it found,
+// the model stalls right after tool_describe ("I don't have that tool loaded"),
+// which is exactly the failure mode that breaks agentic actions like
+// create_portfolio.
+//
+// This mirrors Anthropic's Tool Search Tool: the discovered tool definition
+// must be injected into the active tool set. We accumulate the bare names the
+// model surfaces (via tool_list) or commits to (via tool_describe) across the
+// turn, and feed them back into format_tools_for_openai so they become real,
+// callable functions on the next round.
+inline void note_tool_activations(const QString& bare_tool_name,
+ const QJsonObject& args,
+ const mcp::ToolResult& result,
+ QSet<QString>& activated) {
+ if (!result.success)
+ return;
+ if (bare_tool_name == QLatin1String("tool_list")) {
+ // Activate every candidate the search surfaced — the model may pick any.
+ const QJsonArray rows = result.data.toObject().value("tools").toArray();
+ for (const auto& row : rows) {
+ const QString name = row.toObject().value("name").toString();
+ if (!name.isEmpty())
+ activated.insert(name);
+ }
+ } else if (bare_tool_name == QLatin1String("tool_describe")) {
+ // The model committed to one tool — prefer the canonical name echoed in
+ // the result, fall back to the name it asked about.
+ QString name = result.data.toObject().value("name").toString();
+ if (name.isEmpty())
+ name = args.value("name").toString();
+ if (!name.isEmpty())
+ activated.insert(name);
+ }
+}
+
} // namespace fincept::ai_chat::detail
diff --git a/fincept-qt/src/services/llm/LlmService.cpp b/fincept-qt/src/services/llm/LlmService.cpp
index 75eb78824..a57bc7086 100644
--- a/fincept-qt/src/services/llm/LlmService.cpp
+++ b/fincept-qt/src/services/llm/LlmService.cpp
@@ -499,23 +499,65 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", tool_results}});
- // No tools in follow-up — prevents infinite loop.
- QJsonObject fu;
- fu["model"] = model_;
- fu["messages"] = loop_msgs;
- fu["max_tokens"] = resolved_max_tokens();
- if (!system_prompt_.isEmpty())
- fu["system"] = system_prompt_;
-
- auto fu_http = blocking_post(url, fu, hdr);
- if (fu_http.success) {
+ // ── Multi-round tool loop ──
+ // Previously this was a SINGLE follow-up with NO tools attached, so
+ // the model could execute exactly one tool and never chain a second
+ // (multi-step flows like "create a portfolio then add assets" broke).
+ // We now loop, keeping the full tool set advertised each round, until
+ // the model returns a final text answer or we hit the round cap. All
+ // tools are always declared (full catalogue), so no activation step
+ // is needed here — unlike the Tool-RAG OpenAI path.
+ const int kMaxRounds = active_max_tool_rounds();
+ const QJsonArray ant_tools = build_anthropic_tools();
+ for (int round = 0; round < kMaxRounds; ++round) {
+ QJsonObject fu;
+ fu["model"] = model_;
+ fu["messages"] = loop_msgs;
+ fu["max_tokens"] = resolved_max_tokens();
+ if (!system_prompt_.isEmpty())
+ fu["system"] = system_prompt_;
+ if (!ant_tools.isEmpty())
+ fu["tools"] = ant_tools;
+
+ auto fu_http = blocking_post(url, fu, hdr);
+ if (!fu_http.success) {
+ resp.error = "Anthropic tool follow-up failed: " + fu_http.error;
+ return resp;
+ }
auto fu_doc = QJsonDocument::fromJson(fu_http.body);
- if (!fu_doc.isNull())
- resp.content = extract_anthropic_content_text(fu_doc.object()["content"].toArray());
- } else {
- resp.error = "Anthropic tool follow-up failed: " + fu_http.error;
- return resp;
+ if (fu_doc.isNull()) {
+ resp.error = "Anthropic tool follow-up parse error";
+ return resp;
+ }
+ const QJsonObject frj = fu_doc.object();
+ const QJsonArray fcontent = frj["content"].toArray();
+
+ if (frj["stop_reason"].toString() != "tool_use") {
+ resp.content = extract_anthropic_content_text(fcontent); // final answer
+ break;
+ }
+
+ // More tools requested — record the assistant turn, execute each
+ // tool_use block, and feed the results back for the next round.
+ loop_msgs.append(QJsonObject{{"role", "assistant"}, {"content", fcontent}});
+ QJsonArray more_results;
+ for (const auto& block_val : fcontent) {
+ const QJsonObject block = block_val.toObject();
+ if (block["type"].toString() != "tool_use")
+ continue;
+ const QString tid = block["id"].toString();
+ const QString tname = block["name"].toString();
+ LOG_INFO(kLlmSvcTag, QString("Anthropic tool loop r%1: %2").arg(round).arg(tname));
+ auto tr = mcp::McpService::instance().execute_openai_function(tname, block["input"].toObject());
+ more_results.append(QJsonObject{
+ {"type", "tool_result"},
+ {"tool_use_id", tid},
+ {"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
+ }
+ loop_msgs.append(QJsonObject{{"role", "user"}, {"content", more_results}});
}
+ if (resp.content.isEmpty() && resp.error.isEmpty())
+ resp.error = "Anthropic tool loop exceeded maximum rounds";
} else {
resp.content = extract_anthropic_content_text(content);
}
@@ -535,55 +577,57 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
if (has_function_calls) {
LOG_INFO(kLlmSvcTag, "Gemini requested function call(s)");
- // Execute each tool call and build matching functionResponse parts.
- // Gemini's multi-turn contract: user turn → model turn with functionCall
- // parts → user turn with functionResponse parts (NOT plain text).
- QJsonArray fn_response_parts;
- for (const auto& part_val : parts) {
- QJsonObject part = part_val.toObject();
- if (!part.contains("functionCall"))
+ // ── Multi-round tool loop ──
+ // Gemini's multi-turn contract: user → model(functionCall parts)
+ // → user(functionResponse parts) → … Previously this ran a SINGLE
+ // follow-up with NO tools attached, so the model could execute one
+ // tool and never chain a second. We now loop, re-attaching the tool
+ // set each round, until a text answer or the round cap.
+ const int kMaxRounds = active_max_tool_rounds();
+ const QJsonArray gem_tools = build_gemini_tools();
+
+ // Constant conversation prefix: prior history + the user turn.
+ QJsonArray fu_contents;
+ for (const auto& m : history) {
+ if (m.role == "system")
continue;
- QJsonObject fc = part["functionCall"].toObject();
- QString fn_name = fc["name"].toString();
- QJsonObject fn_args = fc["args"].toObject();
-
- LOG_INFO(kLlmSvcTag, "Executing Gemini tool: " + fn_name);
- auto tr = mcp::McpService::instance().execute_openai_function(fn_name, fn_args);
-
- // Gemini requires response to be an object — wrap strings under "result".
- QJsonObject response_obj;
- if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())
- response_obj = tr.data.toObject();
- else if (!tr.message.isEmpty())
- response_obj["result"] = tr.message;
- else
- response_obj = tr.to_json();
-
- fn_response_parts.append(QJsonObject{
- {"functionResponse",
- QJsonObject{{"name", fn_name}, {"response", response_obj}}}});
+ const QString role = (m.role == "assistant") ? "model" : "user";
+ fu_contents.append(QJsonObject{
+ {"role", role}, {"parts", QJsonArray{QJsonObject{{"text", m.content}}}}});
}
-
- if (!fn_response_parts.isEmpty()) {
- // history + original user + model(functionCall) + user(functionResponse).
- QJsonArray fu_contents;
- for (const auto& m : history) {
- if (m.role == "system")
+ fu_contents.append(QJsonObject{
+ {"role", "user"}, {"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});
+
+ // model_parts = the model turn whose functionCalls we execute this
+ // round; seeded with the initial response's parts.
+ QJsonArray model_parts = parts;
+ QJsonArray last_response_parts;
+ for (int round = 0; round < kMaxRounds; ++round) {
+ fu_contents.append(QJsonObject{{"role", "model"}, {"parts", model_parts}});
+
+ QJsonArray fn_response_parts;
+ for (const auto& part_val : model_parts) {
+ const QJsonObject part = part_val.toObject();
+ if (!part.contains("functionCall"))
continue;
- QString role = (m.role == "assistant") ? "model" : "user";
- fu_contents.append(QJsonObject{
- {"role", role},
- {"parts", QJsonArray{QJsonObject{{"text", m.content}}}}});
+ const QJsonObject fc = part["functionCall"].toObject();
+ const QString fn_name = fc["name"].toString();
+ LOG_INFO(kLlmSvcTag, QString("Gemini tool loop r%1: %2").arg(round).arg(fn_name));
+ auto tr =
+ mcp::McpService::instance().execute_openai_function(fn_name, fc["args"].toObject());
+ // Gemini requires response to be an object — wrap strings under "result".
+ QJsonObject response_obj;
+ if (!tr.data.isNull() && !tr.data.isUndefined() && tr.data.isObject())
+ response_obj = tr.data.toObject();
+ else if (!tr.message.isEmpty())
+ response_obj["result"] = tr.message;
+ else
+ response_obj = tr.to_json();
+ fn_response_parts.append(QJsonObject{
+ {"functionResponse", QJsonObject{{"name", fn_name}, {"response", response_obj}}}});
}
- fu_contents.append(QJsonObject{
- {"role", "user"},
- {"parts", QJsonArray{QJsonObject{{"text", user_message}}}}});
- fu_contents.append(QJsonObject{
- {"role", "model"},
- {"parts", parts}}); // echo functionCall parts verbatim
- fu_contents.append(QJsonObject{
- {"role", "user"},
- {"parts", fn_response_parts}});
+ fu_contents.append(QJsonObject{{"role", "user"}, {"parts", fn_response_parts}});
+ last_response_parts = fn_response_parts;
QJsonObject fu_body;
fu_body["contents"] = fu_contents;
@@ -593,33 +637,55 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
if (!system_prompt_.isEmpty())
fu_body["systemInstruction"] =
QJsonObject{{"parts", QJsonArray{QJsonObject{{"text", system_prompt_}}}}};
+ if (!gem_tools.isEmpty())
+ fu_body["tools"] = gem_tools;
auto fu = blocking_post(url, fu_body, hdr);
- if (fu.success) {
- auto fu_doc = QJsonDocument::fromJson(fu.body);
- if (!fu_doc.isNull()) {
- QJsonArray fu_cands = fu_doc.object()["candidates"].toArray();
- if (!fu_cands.isEmpty())
- resp.content = extract_gemini_parts_text(
- fu_cands[0].toObject()["content"].toObject()["parts"].toArray());
- }
+ if (!fu.success) {
+ resp.error = "Gemini tool follow-up failed: " + fu.error;
+ return resp;
}
- if (resp.content.isEmpty()) {
- // Render function responses as readable text.
- QString fallback;
- for (const auto& pv : fn_response_parts) {
- QJsonObject fr = pv.toObject()["functionResponse"].toObject();
- QString fn_name = fr["name"].toString();
- int sep = fn_name.indexOf("__");
- QString short_name = (sep >= 0) ? fn_name.mid(sep + 2) : fn_name;
- fallback += "\n**Tool: " + short_name + "**\n" +
- QString::fromUtf8(
- QJsonDocument(fr["response"].toObject()).toJson(QJsonDocument::Compact))
- .left(4000) +
- "\n";
+ auto fu_doc = QJsonDocument::fromJson(fu.body);
+ if (fu_doc.isNull()) {
+ resp.error = "Gemini tool follow-up parse error";
+ return resp;
+ }
+ const QJsonArray fu_cands = fu_doc.object()["candidates"].toArray();
+ const QJsonArray resp_parts =
+ fu_cands.isEmpty()
+ ? QJsonArray{}
+ : fu_cands[0].toObject()["content"].toObject()["parts"].toArray();
+
+ bool more_calls = false;
+ for (const auto& pv : resp_parts) {
+ if (pv.toObject().contains("functionCall")) {
+ more_calls = true;
+ break;
}
- resp.content = fallback;
}
+ if (!more_calls) {
+ resp.content = extract_gemini_parts_text(resp_parts); // final answer
+ break;
+ }
+ model_parts = resp_parts; // next round executes these
+ }
+
+ if (resp.content.isEmpty()) {
+ // Loop exhausted without a text turn — render the last round's
+ // function responses as readable text so the chat isn't blank.
+ QString fallback;
+ for (const auto& pv : last_response_parts) {
+ const QJsonObject fr = pv.toObject()["functionResponse"].toObject();
+ const QString fn_name = fr["name"].toString();
+ const int sep = fn_name.indexOf("__");
+ const QString short_name = (sep >= 0) ? fn_name.mid(sep + 2) : fn_name;
+ fallback += "\n**Tool: " + short_name + "**\n" +
+ QString::fromUtf8(
+ QJsonDocument(fr["response"].toObject()).toJson(QJsonDocument::Compact))
+ .left(4000) +
+ "\n";
+ }
+ resp.content = fallback;
}
} else {
resp.content = extract_gemini_parts_text(parts);
@@ -657,6 +723,11 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
loop_msgs.append(QJsonObject{{"role", "user"}, {"content", user_message}});
loop_msgs.append(msg); // assistant turn with tool_calls
+ // Tools the model has discovered this turn — seeded from this
+ // first round so the loop can re-declare them on the next turn
+ // (Tool RAG only ships Tier-0 otherwise; see note_tool_activations).
+ QSet<QString> activated;
+
for (const auto& tc_val : tcs) {
QJsonObject tc = tc_val.toObject();
QString call_id = tc["id"].toString();
@@ -671,13 +742,15 @@ LlmResponse LlmService::do_request(const QString& user_message, const std::vecto
LOG_INFO(kLlmSvcTag, QString("Tool %1 -> %2 (msg=%3 err=%4)")
.arg(fn_name, tr.success ? "OK" : "FAIL",
tr.message.left(120), tr.error.left(120)));
+ const QString bare = mcp::McpProvider::parse_openai_function_name(fn_name).second;
+ detail::note_tool_activations(bare, fn_args, tr, activated);
loop_msgs.append(QJsonObject{
{"role", "tool"},
{"tool_call_id", call_id},
{"content", QString::fromUtf8(QJsonDocument(tr.to_json()).toJson(QJsonDocument::Compact))}});
}
- resp = do_tool_loop(loop_msgs, url, hdr);
+ resp = do_tool_loop(loop_msgs, url, hdr, activated);
parse_usage(resp, rj, provider_);
return resp;
diff --git a/fincept-qt/src/services/llm/LlmService.h b/fincept-qt/src/services/llm/LlmService.h
index 632433cd0..65ecf9657 100644
--- a/fincept-qt/src/services/llm/LlmService.h
+++ b/fincept-qt/src/services/llm/LlmService.h
@@ -10,6 +10,7 @@
#include <QMutex>
#include <QNetworkAccessManager>
#include <QObject>
+#include <QSet>
#include <QString>
#include <QStringList>
@@ -137,6 +138,14 @@ class LlmService : public QObject {
QJsonObject build_fincept_request(const QString& user_message, const std::vector<ConversationMessage>& history,
bool with_tools);
+ // Provider-specific tool-array builders. Shared by the initial request
+ // builders AND the multi-round tool loops so the tools advertised on
+ // follow-up turns stay identical to the first turn (Anthropic/Gemini
+ // previously dropped tools on the follow-up, so they could never chain a
+ // second tool call). Honour the active ToolPolicy via apply_request_policy.
+ QJsonArray build_anthropic_tools(); // [{name, description, input_schema}]
+ QJsonArray build_gemini_tools(); // [{functionDeclarations:[{name, description, parameters}]}]
+
QString get_endpoint_url() const;
QMap<QString, QString> get_headers() const;
@@ -148,7 +157,12 @@ class LlmService : public QObject {
LlmResponse do_streaming_request(const QString& user_message, const std::vector<ConversationMessage>& history,
StreamCallback on_chunk);
- LlmResponse do_tool_loop(QJsonArray loop_messages, const QString& url, const QMap<QString, QString>& headers);
+ // `activated_tools` is seeded from the first round of tool calls (executed
+ // by the caller) and grows as the model discovers more via tool_list /
+ // tool_describe. In Tool RAG mode these names are force-declared to the
+ // model each round so it can actually call what it discovers.
+ LlmResponse do_tool_loop(QJsonArray loop_messages, const QString& url, const QMap<QString, QString>& headers,
+ QSet<QString> activated_tools = {});
/// Returns nullopt if the content had no text/XML tool calls.
std::optional<LlmResponse> try_extract_and_execute_text_tool_calls(const QString& content,
diff --git a/fincept-qt/src/services/llm/LlmToolLoop.cpp b/fincept-qt/src/services/llm/LlmToolLoop.cpp
index 4f676e5d1..99666aa52 100644
--- a/fincept-qt/src/services/llm/LlmToolLoop.cpp
+++ b/fincept-qt/src/services/llm/LlmToolLoop.cpp
@@ -28,7 +28,8 @@ namespace fincept::ai_chat {
namespace { constexpr const char* kLlmToolLoopTag = "LlmService"; }
LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& url,
- const QMap<QString, QString>& headers) {
+ const QMap<QString, QString>& headers,
+ QSet<QString> activated_tools) {
LlmResponse resp;
// MiniMax-style models spend 3 rounds per action (tool_list → tool_describe
// → actual call), so the default 40 gives ~13 real actions — enough for a
@@ -43,7 +44,8 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
// Temperature intentionally omitted — provider default.
fu["max_tokens"] = resolved_max_tokens();
- QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(detail::apply_request_policy(tool_filter_));
+ QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(
+ detail::apply_request_policy(tool_filter_), activated_tools);
if (!tools.isEmpty())
fu["tools"] = tools;
@@ -92,6 +94,9 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
LOG_INFO(kLlmToolLoopTag, QString("TOOL LOOP r%1: %2 -> %3 (msg=%4 err=%5)")
.arg(round).arg(fname,
tr.success ? "OK" : "FAIL", tr.message.left(120), tr.error.left(120)));
+ // If this was a discovery call (tool_list / tool_describe), declare
+ // what it surfaced so the model can actually call it next round.
+ detail::note_tool_activations(display, fa, tr, activated_tools);
loop_messages.append(QJsonObject{
{"role", "tool"},
{"tool_call_id", cid},
@@ -147,8 +152,10 @@ LlmResponse LlmService::do_tool_loop(QJsonArray loop_messages, const QString& ur
fu["max_tokens"] = resolved_max_tokens();
// Keep tools available so structured tool_calls still work. Stripping
// them used to force text-markup mode (raw <minimax:tool_call> blobs)
- // which leaked into the chat bubble.
- QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(detail::apply_request_policy(tool_filter_));
+ // which leaked into the chat bubble. Carry the activated set so a
+ // last-ditch tool call can still reference a discovered tool.
+ QJsonArray tools = mcp::McpService::instance().format_tools_for_openai(
+ detail::apply_request_policy(tool_filter_), activated_tools);
if (!tools.isEmpty())
fu["tools"] = tools;
diff --git a/fincept-qt/src/services/notebooks/NotebookLibraryService.cpp b/fincept-qt/src/services/notebooks/NotebookLibraryService.cpp
new file mode 100644
index 000000000..b6d6dfeb9
--- /dev/null
+++ b/fincept-qt/src/services/notebooks/NotebookLibraryService.cpp
@@ -0,0 +1,202 @@
+// NotebookLibraryService.cpp
+
+#include "services/notebooks/NotebookLibraryService.h"
+
+#include "core/config/AppPaths.h"
+#include "core/logging/Logger.h"
+#include "services/file_manager/FileManagerService.h"
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSet>
+#include <QStringList>
+
+namespace fincept::services {
+
+static constexpr const char* kTag = "NotebookLibrary";
+
+// ── Singleton ────────────────────────────────────────────────────────────────
+
+NotebookLibraryService& NotebookLibraryService::instance() {
+ static NotebookLibraryService s_instance;
+ return s_instance;
+}
+
+NotebookLibraryService::NotebookLibraryService(QObject* parent) : QObject(parent) {}
+
+// ── Asset resolution ──────────────────────────────────────────────────────────
+// Mirrors PythonRunner::find_scripts_dir / ComponentCatalog::load_with_fallbacks:
+// the notebooks ship under resources/notebooks/ next to the binary (POST_BUILD)
+// and inside the app bundle (install). Walk a handful of candidate layouts, then
+// fall back to walking up the tree to find the source-tree copy in dev runs.
+
+QString NotebookLibraryService::assets_dir() {
+ if (assets_dir_resolved_)
+ return assets_dir_cache_;
+ assets_dir_resolved_ = true;
+
+ const QString exe = QCoreApplication::applicationDirPath();
+ const QStringList candidates = {
+ exe + "/resources/notebooks", // dev + Windows/Linux next-to-exe
+ exe + "/../Resources/resources/notebooks", // macOS .app/Contents/Resources
+ exe + "/../resources/notebooks",
+ exe + "/../../resources/notebooks",
+ exe + "/../share/fincept-terminal/resources/notebooks", // Linux install
+ };
+ for (const QString& c : candidates) {
+ if (QFileInfo::exists(c + "/notebooks_manifest.json")) {
+ assets_dir_cache_ = QDir(c).absolutePath();
+ return assets_dir_cache_;
+ }
+ }
+
+ // Dev fallback: walk up from the executable looking for the source-tree copy.
+ QDir dir(exe);
+ for (int i = 0; i < 8 && dir.cdUp(); ++i) {
+ const QString p = dir.filePath("resources/notebooks/notebooks_manifest.json");
+ if (QFileInfo::exists(p)) {
+ assets_dir_cache_ = QFileInfo(p).absolutePath();
+ return assets_dir_cache_;
+ }
+ const QString p2 = dir.filePath("fincept-qt/resources/notebooks/notebooks_manifest.json");
+ if (QFileInfo::exists(p2)) {
+ assets_dir_cache_ = QFileInfo(p2).absolutePath();
+ return assets_dir_cache_;
+ }
+ }
+
+ LOG_WARN(kTag, "Notebook assets dir not found");
+ assets_dir_cache_.clear();
+ return assets_dir_cache_;
+}
+
+QString NotebookLibraryService::asset_path(const NotebookCatalogEntry& entry) {
+ const QString dir = assets_dir();
+ if (dir.isEmpty() || entry.file.isEmpty())
+ return {};
+ return dir + "/" + entry.file;
+}
+
+// ── Catalog ───────────────────────────────────────────────────────────────────
+
+const QVector<NotebookCatalogEntry>& NotebookLibraryService::catalog() {
+ if (!loaded_) {
+ load_catalog();
+ loaded_ = true;
+ }
+ return catalog_;
+}
+
+void NotebookLibraryService::load_catalog() {
+ catalog_.clear();
+
+ const QString dir = assets_dir();
+ if (dir.isEmpty())
+ return;
+
+ QFile f(dir + "/notebooks_manifest.json");
+ if (!f.open(QIODevice::ReadOnly)) {
+ LOG_WARN(kTag, "Cannot open notebooks_manifest.json");
+ return;
+ }
+ const QJsonDocument doc = QJsonDocument::fromJson(f.readAll());
+ f.close();
+ if (!doc.isObject())
+ return;
+
+ for (const QJsonValue& v : doc.object()["notebooks"].toArray()) {
+ const QJsonObject o = v.toObject();
+ NotebookCatalogEntry e;
+ e.id = o["id"].toString();
+ e.title = o["title"].toString();
+ e.category = o["category"].toString();
+ e.difficulty = o["difficulty"].toString();
+ e.est_minutes = o["est_minutes"].toInt();
+ e.requirements = o["requires"].toString();
+ e.summary = o["summary"].toString();
+ e.file = o["file"].toString();
+ if (!e.id.isEmpty() && !e.file.isEmpty())
+ catalog_.append(e);
+ }
+ LOG_INFO(kTag, QString("Loaded %1 prebuilt notebooks").arg(catalog_.size()));
+}
+
+// ── Seeding ───────────────────────────────────────────────────────────────────
+
+QString NotebookLibraryService::seed_marker_path() const {
+ return fincept::AppPaths::data() + "/.fincept_notebooks_seeded_v1";
+}
+
+void NotebookLibraryService::seed_into_files(bool force) {
+ if (!force && QFileInfo::exists(seed_marker_path()))
+ return;
+
+ const auto& cat = catalog();
+ if (cat.isEmpty())
+ return; // assets missing — try again next launch (no marker written)
+
+ auto& fm = FileManagerService::instance();
+
+ // Index existing code_editor files by their original name so re-seeding never
+ // duplicates a notebook the user already has.
+ QSet<QString> existing;
+ for (const QJsonValue& v : fm.files_for_screen("code_editor"))
+ existing.insert(v.toObject()["originalName"].toString());
+
+ int seeded = 0;
+ for (const NotebookCatalogEntry& e : cat) {
+ if (existing.contains(e.file))
+ continue;
+ const QString src = asset_path(e);
+ if (src.isEmpty() || !QFileInfo::exists(src))
+ continue;
+ if (!fm.import_file(src, "code_editor").isEmpty())
+ ++seeded;
+ }
+
+ // Mark seeded only once we actually have the assets, so a launch before the
+ // bundle is in place doesn't permanently skip seeding.
+ QFile marker(seed_marker_path());
+ if (marker.open(QIODevice::WriteOnly)) {
+ marker.write("seeded\n");
+ marker.close();
+ }
+ LOG_INFO(kTag, QString("Seeded %1 prebuilt notebooks into File Manager").arg(seeded));
+}
+
+// ── Working copy (copy-on-open) ────────────────────────────────────────────────
+
+QString NotebookLibraryService::working_copy_for(const NotebookCatalogEntry& entry) {
+ auto& fm = FileManagerService::instance();
+
+ // Reuse an existing managed copy if one is already present (e.g. seeded).
+ for (const QJsonValue& v : fm.files_for_screen("code_editor")) {
+ const QJsonObject o = v.toObject();
+ if (o["originalName"].toString() != entry.file)
+ continue;
+ const QString p = fm.full_path(o["name"].toString());
+ if (!p.isEmpty() && QFileInfo::exists(p))
+ return p;
+ }
+
+ // Otherwise import the bundled asset into managed storage.
+ const QString src = asset_path(entry);
+ if (!src.isEmpty() && QFileInfo::exists(src)) {
+ const QString id = fm.import_file(src, "code_editor");
+ if (!id.isEmpty()) {
+ const QString p = fm.full_path(fm.find_by_id(id).name);
+ if (!p.isEmpty())
+ return p;
+ }
+ }
+
+ // Last resort: open the read-only bundled asset directly.
+ return src;
+}
+
+} // namespace fincept::services
diff --git a/fincept-qt/src/services/notebooks/NotebookLibraryService.h b/fincept-qt/src/services/notebooks/NotebookLibraryService.h
new file mode 100644
index 000000000..24a691b8e
--- /dev/null
+++ b/fincept-qt/src/services/notebooks/NotebookLibraryService.h
@@ -0,0 +1,67 @@
+#pragma once
+// NotebookLibraryService.h — Catalog + seeding for the prebuilt "Fincept
+// Notebook" library shipped under resources/notebooks/.
+//
+// Responsibilities:
+// - Parse resources/notebooks/notebooks_manifest.json into a catalog.
+// - Resolve the bundled assets dir at runtime (dev + installed layouts).
+// - Seed copies into <profile>/files/ on first run (registered with the
+// FileManagerService so they appear in the File Manager).
+// - Provide a writable working copy for the Library "OPEN" action so the
+// bundled originals stay pristine and user edits persist + stay in sync.
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept::services {
+
+/// One prebuilt notebook described by the manifest.
+struct NotebookCatalogEntry {
+ QString id;
+ QString title;
+ QString category; // Finance, Economics, Trading, Investing, Portfolio, Quant
+ QString difficulty; // "Beginner" | "Intermediate" | "Hard"
+ int est_minutes = 0;
+ QString requirements; // "stdlib" | "pandas + numpy"
+ QString summary;
+ QString file; // bundled filename, e.g. finance_time_value_of_money.ipynb
+};
+
+class NotebookLibraryService : public QObject {
+ Q_OBJECT
+
+ public:
+ static NotebookLibraryService& instance();
+
+ /// Parsed catalog (loaded + cached on first call). Empty if assets missing.
+ const QVector<NotebookCatalogEntry>& catalog();
+
+ /// Absolute path to the bundled notebooks directory, or empty if not found.
+ QString assets_dir();
+
+ /// Absolute path to a bundled notebook .ipynb for an entry (read-only asset).
+ QString asset_path(const NotebookCatalogEntry& entry);
+
+ /// First-run seeding: copy every bundled notebook into <profile>/files/ and
+ /// register each with FileManagerService (source "code_editor"). Idempotent —
+ /// guarded by a marker file. Pass force=true to re-seed regardless.
+ void seed_into_files(bool force = false);
+
+ /// Ensure a writable working copy of `entry` exists in <profile>/files/ and
+ /// return its absolute path (registering it with FileManagerService if new).
+ /// Returns the bundled asset path as a last resort if storage is unavailable.
+ QString working_copy_for(const NotebookCatalogEntry& entry);
+
+ private:
+ explicit NotebookLibraryService(QObject* parent = nullptr);
+ void load_catalog();
+ QString seed_marker_path() const;
+
+ QVector<NotebookCatalogEntry> catalog_;
+ bool loaded_ = false;
+ QString assets_dir_cache_;
+ bool assets_dir_resolved_ = false;
+};
+
+} // namespace fincept::services
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index 1c1fe114c..870fbf559 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -3,6 +3,7 @@
#include "core/logging/Logger.h"
#include "trading/AccountManager.h"
#include "trading/BrokerRegistry.h"
+#include "trading/HistoricalDataService.h"
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
#include "trading/instruments/InstrumentService.h"
@@ -36,6 +37,7 @@ constexpr const char* ADS_TAG = "AccountDataStream";
constexpr int ADS_QUOTE_POLL_MS = 300000;
constexpr int ADS_PORTFOLIO_POLL_MS = 300000;
constexpr int ADS_WATCHLIST_POLL_MS = 300000;
+constexpr int ADS_ACTIVE_FEED_POLL_MS = 3000; // fast poll for algo/active-feed symbols (non-WS brokers)
} // namespace
// ── Construction / Destruction ──────────────────────────────────────────────
@@ -57,6 +59,10 @@ AccountDataStream::AccountDataStream(const QString& account_id, QObject* parent)
watchlist_timer_ = new QTimer(this);
watchlist_timer_->setInterval(ADS_WATCHLIST_POLL_MS);
connect(watchlist_timer_, &QTimer::timeout, this, &AccountDataStream::on_watchlist_timer);
+
+ active_feed_timer_ = new QTimer(this);
+ active_feed_timer_->setInterval(ADS_ACTIVE_FEED_POLL_MS);
+ connect(active_feed_timer_, &QTimer::timeout, this, &AccountDataStream::on_active_feed_timer);
}
AccountDataStream::~AccountDataStream() {
@@ -79,6 +85,8 @@ void AccountDataStream::start() {
watchlist_timer_->start();
}
portfolio_timer_->start();
+ if (!active_feed_symbol_union().isEmpty())
+ active_feed_timer_->start();
// Initial data fetch
async_fetch_quote();
@@ -99,6 +107,7 @@ void AccountDataStream::stop() {
quote_timer_->stop();
portfolio_timer_->stop();
watchlist_timer_->stop();
+ active_feed_timer_->stop();
ws_teardown();
LOG_INFO(ADS_TAG, QString("Stopped stream for account %1").arg(account_id_));
@@ -108,6 +117,7 @@ void AccountDataStream::pause() {
quote_timer_->stop();
portfolio_timer_->stop();
watchlist_timer_->stop();
+ active_feed_timer_->stop();
// Keep WS alive in background
}
@@ -119,12 +129,17 @@ void AccountDataStream::resume() {
watchlist_timer_->start();
}
portfolio_timer_->start();
+ if (!active_feed_symbol_union().isEmpty())
+ active_feed_timer_->start();
}
// ── Symbol management ───────────────────────────────────────────────────────
-void AccountDataStream::subscribe_symbols(const QStringList& symbols) {
- watchlist_symbols_ = symbols;
+void AccountDataStream::subscribe_symbols(const QString& consumer_id, const QStringList& symbols) {
+ if (symbols.isEmpty())
+ consumer_symbols_.remove(consumer_id);
+ else
+ consumer_symbols_[consumer_id] = symbols;
// Resubscribe whenever the socket is connected — NOT gated on ws_active(),
// which also requires ticks. On an account switch-back the socket is
// connected but may have 0 ticks (it was subscribed to 0 symbols while
@@ -133,6 +148,51 @@ void AccountDataStream::subscribe_symbols(const QStringList& symbols) {
ws_resubscribe();
}
+void AccountDataStream::unsubscribe_consumer(const QString& consumer_id) {
+ const bool had = consumer_symbols_.remove(consumer_id) > 0;
+ active_feed_symbols_.remove(consumer_id);
+ if (active_feed_timer_ && active_feed_symbol_union().isEmpty())
+ active_feed_timer_->stop();
+ if (had && ws_connected())
+ ws_resubscribe();
+}
+
+void AccountDataStream::set_active_feed(const QString& consumer_id, const QStringList& symbols) {
+ if (symbols.isEmpty())
+ active_feed_symbols_.remove(consumer_id);
+ else
+ active_feed_symbols_[consumer_id] = symbols;
+ if (!active_feed_timer_)
+ return;
+ const bool any = !active_feed_symbol_union().isEmpty();
+ if (any && running_) {
+ if (!active_feed_timer_->isActive())
+ active_feed_timer_->start();
+ if (!ws_connected())
+ async_fetch_active_feed_quotes(); // non-WS only; WS brokers wait for the pushed tick
+ } else if (!any && active_feed_timer_->isActive()) {
+ active_feed_timer_->stop();
+ }
+}
+
+QStringList AccountDataStream::subscribed_symbols() const {
+ QStringList out;
+ for (auto it = consumer_symbols_.constBegin(); it != consumer_symbols_.constEnd(); ++it)
+ for (const QString& s : it.value())
+ if (!out.contains(s))
+ out.append(s);
+ return out;
+}
+
+QStringList AccountDataStream::active_feed_symbol_union() const {
+ QStringList out;
+ for (auto it = active_feed_symbols_.constBegin(); it != active_feed_symbols_.constEnd(); ++it)
+ for (const QString& s : it.value())
+ if (!out.contains(s))
+ out.append(s);
+ return out;
+}
+
void AccountDataStream::set_selected_symbol(const QString& symbol, const QString& exchange) {
selected_symbol_ = symbol;
selected_exchange_ = exchange;
@@ -375,11 +435,11 @@ void AccountDataStream::async_fetch_funds() {
}
void AccountDataStream::async_fetch_watchlist_quotes() {
- if (watchlist_symbols_.isEmpty())
+ const QStringList symbols = subscribed_symbols();
+ if (symbols.isEmpty())
return;
const QString acct_id = account_id_;
const QString bid = broker_id_;
- const QStringList symbols = watchlist_symbols_;
QPointer<AccountDataStream> self = this;
auto creds = AccountManager::instance().load_credentials(acct_id);
@@ -407,58 +467,84 @@ void AccountDataStream::async_fetch_watchlist_quotes() {
// ── On-demand fetches ───────────────────────────────────────────────────────
-void AccountDataStream::fetch_candles(const QString& symbol, const QString& timeframe) {
- if (candles_fetching_.exchange(true))
+void AccountDataStream::on_active_feed_timer() {
+ if (!running_ || ws_connected())
+ return; // WS is connected and pushes ticks — poll ONLY for non-WS brokers / WS outage
+ if (is_token_expired()) {
+ emit token_expired(account_id_);
+ return;
+ }
+ async_fetch_active_feed_quotes();
+}
+
+void AccountDataStream::async_fetch_active_feed_quotes() {
+ const QStringList symbols = active_feed_symbol_union();
+ if (symbols.isEmpty())
return;
const QString acct_id = account_id_;
const QString bid = broker_id_;
QPointer<AccountDataStream> self = this;
auto creds = AccountManager::instance().load_credentials(acct_id);
- if (creds.api_key.isEmpty()) {
- candles_fetching_ = false;
+ if (creds.api_key.isEmpty())
return;
- }
- (void)QtConcurrent::run([self, acct_id, bid, symbol, timeframe, creds]() {
+ (void)QtConcurrent::run([self, acct_id, bid, symbols, creds]() {
auto* broker = BrokerRegistry::instance().get(bid);
- if (!broker) {
- if (self) self->candles_fetching_ = false;
+ if (!broker)
return;
- }
- // Build date range
- const QString to_dt = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm");
- QString from_dt;
- // Look-back windows kept within both Kite (1m=60d, intraday=100d,
- // day=2000d) and Fyers (intraday ~100d/req, chunked) single-request
- // limits, while loading enough bars to scroll back meaningfully.
- if (timeframe == "1d" || timeframe == "D" || timeframe == "1w" || timeframe == "W")
- from_dt = QDate::currentDate().addYears(-3).toString("yyyy-MM-dd") + " 00:00";
- else if (timeframe == "1h" || timeframe == "60")
- from_dt = QDate::currentDate().addDays(-60).toString("yyyy-MM-dd") + " 00:00";
- else if (timeframe == "30m")
- from_dt = QDate::currentDate().addDays(-45).toString("yyyy-MM-dd") + " 00:00";
- else if (timeframe == "15m")
- from_dt = QDate::currentDate().addDays(-30).toString("yyyy-MM-dd") + " 00:00";
- else if (timeframe == "5m")
- from_dt = QDate::currentDate().addDays(-15).toString("yyyy-MM-dd") + " 00:00";
- else
- from_dt = QDate::currentDate().addDays(-7).toString("yyyy-MM-dd") + " 00:00";
-
- auto result = broker->get_history(creds, symbol, timeframe, from_dt, to_dt);
- if (self) self->candles_fetching_ = false;
+ auto result = broker->get_quotes(creds, symbols.toVector());
if (!result.success || !result.data) {
if (self)
self->check_token_expiry(result.error);
return;
}
+ // Emit PER-SYMBOL quote_updated (not watchlist_updated) so DataStreamManager
+ // publishes each to broker:<id>:<acct>:quote:<symbol> (the topic algo feeds read).
QMetaObject::invokeMethod(self, [self, acct_id, data = *result.data]() {
if (!self) return;
- emit self->candles_fetched(acct_id, data);
+ for (const auto& q : data) {
+ self->quote_cache_[q.symbol] = q;
+ emit self->quote_updated(acct_id, q.symbol, q);
+ }
}, Qt::QueuedConnection);
});
}
+void AccountDataStream::fetch_candles(const QString& symbol, const QString& timeframe) {
+ if (candles_fetching_.exchange(true))
+ return;
+ const QString acct_id = account_id_;
+ QPointer<AccountDataStream> self = this;
+
+ // Map the chart timeframe to a look-back window (preserves the prior per-tf
+ // windows), then delegate to the shared HistoricalDataService (broker fetch +
+ // symbol resolution + 60s cache). Yahoo fallback is algo-only, not used here.
+ auto lookback_for = [](const QString& tf) -> int {
+ if (tf == "1d" || tf == "D" || tf == "1w" || tf == "W") return 3 * 365;
+ if (tf == "1h" || tf == "60") return 60;
+ if (tf == "30m") return 45;
+ if (tf == "15m") return 30;
+ if (tf == "5m") return 15;
+ return 7;
+ };
+
+ HistoricalDataService::instance().fetch(
+ symbol, timeframe, lookback_for(timeframe), broker_id_, acct_id,
+ [self, acct_id](bool ok, const QVector<BrokerCandle>& candles, const QString& err) {
+ if (!self)
+ return;
+ self->candles_fetching_ = false;
+ if (ok) {
+ emit self->candles_fetched(acct_id, candles);
+ } else {
+ self->check_token_expiry(err);
+ LOG_WARN(ADS_TAG, QString("fetch_candles failed for %1/%2: %3")
+ .arg(self->broker_id_, acct_id, err));
+ }
+ });
+}
+
void AccountDataStream::fetch_orderbook(const QString& symbol) {
const QString acct_id = account_id_;
const QString bid = broker_id_;
@@ -722,7 +808,7 @@ void AccountDataStream::ws_init() {
QStringList fyers_symbols;
if (!selected_symbol_.isEmpty())
fyers_symbols.append(to_fyers(selected_symbol_));
- for (const auto& s : watchlist_symbols_)
+ for (const QString& s : subscribed_symbols())
fyers_symbols.append(to_fyers(s));
fyers_symbols.removeDuplicates();
if (auto* fws = qobject_cast<FyersWebSocket*>(ws_))
@@ -788,7 +874,7 @@ void AccountDataStream::ws_init() {
QStringList symbols;
if (!selected_symbol_.isEmpty())
symbols.append(selected_symbol_);
- for (const auto& s : watchlist_symbols_) {
+ for (const QString& s : subscribed_symbols()) {
if (!symbols.contains(s))
symbols.append(s);
}
@@ -820,7 +906,7 @@ void AccountDataStream::ws_init() {
QStringList syms;
if (!selected_symbol_.isEmpty())
syms.append(selected_symbol_);
- for (const auto& s : watchlist_symbols_) {
+ for (const QString& s : subscribed_symbols()) {
if (!syms.contains(s))
syms.append(s);
}
@@ -1102,7 +1188,7 @@ void AccountDataStream::ws_resubscribe() {
QStringList fyers_symbols;
if (!selected_symbol_.isEmpty())
fyers_symbols.append(to_fyers(selected_symbol_));
- for (const auto& s : watchlist_symbols_)
+ for (const QString& s : subscribed_symbols())
fyers_symbols.append(to_fyers(s));
fyers_symbols.removeDuplicates();
fws->set_subscriptions(fyers_symbols);
@@ -1112,7 +1198,7 @@ void AccountDataStream::ws_resubscribe() {
QStringList symbols;
if (!selected_symbol_.isEmpty())
symbols.append(selected_symbol_);
- for (const auto& s : watchlist_symbols_) {
+ for (const QString& s : subscribed_symbols()) {
if (!symbols.contains(s))
symbols.append(s);
}
@@ -1125,7 +1211,7 @@ void AccountDataStream::ws_resubscribe() {
QStringList symbols;
if (!selected_symbol_.isEmpty())
symbols.append(selected_symbol_);
- for (const auto& s : watchlist_symbols_) {
+ for (const QString& s : subscribed_symbols()) {
if (!symbols.contains(s))
symbols.append(s);
}
diff --git a/fincept-qt/src/trading/AccountDataStream.h b/fincept-qt/src/trading/AccountDataStream.h
index a1993160e..78e124589 100644
--- a/fincept-qt/src/trading/AccountDataStream.h
+++ b/fincept-qt/src/trading/AccountDataStream.h
@@ -37,8 +37,18 @@ class AccountDataStream : public QObject {
void resume(); // Restart timers (screen shown)
bool is_running() const { return running_; }
- // --- Symbol management ---
- void subscribe_symbols(const QStringList& symbols);
+ // --- Symbol management (multi-consumer) ---
+ // Each consumer ("equity:watchlist", "algo:<deploymentId>", …) owns an
+ // independent symbol set. The WS/poll universe is the UNION across all
+ // consumers plus selected_symbol_; a symbol is unsubscribed only when its
+ // LAST consumer drops it. Replaces this consumer's set (empty == release).
+ void subscribe_symbols(const QString& consumer_id, const QStringList& symbols);
+ void unsubscribe_consumer(const QString& consumer_id);
+ // Mark `symbols` as "active feed" for `consumer_id`: on brokers WITHOUT a
+ // live WebSocket these get a fast (3s) REST poll instead of the 5-min
+ // watchlist cadence, so algo deployments get timely ticks. No effect on WS
+ // brokers (ticks already arrive live). Empty == release.
+ void set_active_feed(const QString& consumer_id, const QStringList& symbols);
void set_selected_symbol(const QString& symbol, const QString& exchange);
QString selected_symbol() const { return selected_symbol_; }
@@ -98,6 +108,13 @@ class AccountDataStream : public QObject {
void async_fetch_funds();
void async_fetch_watchlist_quotes();
+ // Union (deduped) of every consumer's symbols. The WS/poll universe.
+ QStringList subscribed_symbols() const;
+ // Union (deduped) of active-feed symbols across consumers.
+ QStringList active_feed_symbol_union() const;
+ void async_fetch_active_feed_quotes();
+ void on_active_feed_timer();
+
// --- Timer callbacks ---
void on_quote_timer();
void on_portfolio_timer();
@@ -125,11 +142,15 @@ class AccountDataStream : public QObject {
QTimer* quote_timer_ = nullptr;
QTimer* portfolio_timer_ = nullptr;
QTimer* watchlist_timer_ = nullptr;
+ QTimer* active_feed_timer_ = nullptr; // 3s fast poll for algo/active-feed symbols
// Subscriptions
QString selected_symbol_;
QString selected_exchange_;
- QStringList watchlist_symbols_;
+ // Consumer-keyed subscriptions (replaces the old single watchlist set).
+ QHash<QString /*consumer_id*/, QStringList /*symbols*/> consumer_symbols_;
+ // Subset of consumer symbols that need fast polling on non-WS brokers.
+ QHash<QString /*consumer_id*/, QStringList /*symbols*/> active_feed_symbols_;
// Cached data (main thread only — no mutex needed since all updates are via QueuedConnection)
QVector<BrokerPosition> positions_;
diff --git a/fincept-qt/src/trading/DataStreamManager.cpp b/fincept-qt/src/trading/DataStreamManager.cpp
index bae1131b8..3e252a991 100644
--- a/fincept-qt/src/trading/DataStreamManager.cpp
+++ b/fincept-qt/src/trading/DataStreamManager.cpp
@@ -8,6 +8,7 @@
# include "trading/BrokerTopic.h"
#include <QDateTime>
+#include <QPointer>
#include <QSet>
#include <QVariant>
@@ -364,4 +365,65 @@ void DataStreamManager::on_quote_for_hub(const QString& account_id, const QStrin
fincept::datahub::DataHub::instance().publish(topic, QVariant::fromValue(quote));
}
+// ── Shared quote feed (Stage 2) ─────────────────────────────────────────────
+
+void DataStreamManager::open_quote_feed(QObject* owner, const QString& consumer_id,
+ const QString& account_id, const QString& symbol,
+ std::function<void(const BrokerQuote&)> cb) {
+ // This singleton + DataHub live on the main thread; callers (DeploymentRunner)
+ // run on the algo engine thread. Marshal all stream/DataHub mutation here.
+ QPointer<QObject> guard(owner);
+ QMetaObject::invokeMethod(this, [this, guard, consumer_id, account_id, symbol, cb]() {
+ if (!guard)
+ return;
+ ensure_registered_with_hub();
+ if (!has_stream(account_id))
+ start_stream(account_id);
+ auto* stream = stream_for(account_id);
+ if (!stream) {
+ LOG_WARN(DSM_TAG, QString("open_quote_feed: no stream for account %1").arg(account_id));
+ return;
+ }
+ // Join the account stream as an independent consumer + request fast (3s)
+ // polling on non-WS brokers so the feed stays timely for algos.
+ stream->subscribe_symbols(consumer_id, {symbol});
+ stream->set_active_feed(consumer_id, {symbol});
+
+ // Replace any prior feed registered under this consumer id.
+ if (auto old = quote_feeds_.find(consumer_id); old != quote_feeds_.end()) {
+ if (old->owner)
+ fincept::datahub::DataHub::instance().unsubscribe(old->owner, old->topic);
+ quote_feeds_.erase(old);
+ }
+
+ const QString topic = broker_topic(stream->broker_id(), account_id,
+ QStringLiteral("quote"), symbol);
+ // DataHub fans out on the MAIN thread; marshal each quote to the owner's
+ // (engine) thread before invoking cb so on_tick_data runs there.
+ fincept::datahub::DataHub::instance().subscribe<BrokerQuote>(
+ guard, topic, [guard, cb](const BrokerQuote& q) {
+ QMetaObject::invokeMethod(guard, [guard, cb, q]() {
+ if (guard) cb(q);
+ }, Qt::QueuedConnection);
+ });
+ quote_feeds_.insert(consumer_id, QuoteFeed{account_id, topic, guard});
+ LOG_INFO(DSM_TAG, QString("Opened quote feed '%1' for %2 on account %3")
+ .arg(consumer_id, symbol, account_id));
+ }, Qt::QueuedConnection);
+}
+
+void DataStreamManager::close_quote_feed(const QString& consumer_id, const QString& account_id) {
+ QMetaObject::invokeMethod(this, [this, consumer_id, account_id]() {
+ if (auto it = quote_feeds_.find(consumer_id); it != quote_feeds_.end()) {
+ if (it->owner)
+ fincept::datahub::DataHub::instance().unsubscribe(it->owner, it->topic);
+ quote_feeds_.erase(it);
+ }
+ if (auto* stream = stream_for(account_id)) {
+ stream->unsubscribe_consumer(consumer_id);
+ stream->set_active_feed(consumer_id, {});
+ }
+ }, Qt::QueuedConnection);
+}
+
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/DataStreamManager.h b/fincept-qt/src/trading/DataStreamManager.h
index 6897af615..d6d8f024d 100644
--- a/fincept-qt/src/trading/DataStreamManager.h
+++ b/fincept-qt/src/trading/DataStreamManager.h
@@ -8,9 +8,12 @@
#include <QHash>
#include <QObject>
+#include <QPointer>
#include <QString>
#include <QTimer>
+#include <functional>
+
# include "datahub/Producer.h"
namespace fincept::trading {
@@ -45,6 +48,17 @@ class DataStreamManager : public QObject
// Registers with the hub + installs broker:* policies. Idempotent.
void ensure_registered_with_hub();
+ // --- Shared quote feed (thread-safe; callable from any thread) ---
+ // Give `consumer_id` a live feed of `symbol` on `account_id`: ensures the
+ // account stream is started + subscribed (so the symbol streams and is
+ // published to broker:<id>:<acct>:quote:<symbol>), then forwards every quote
+ // to `cb`. `cb` is invoked on `owner`'s thread (queued). `owner` is the
+ // lifetime guard. All stream/DataHub mutation happens on the main thread.
+ void open_quote_feed(QObject* owner, const QString& consumer_id,
+ const QString& account_id, const QString& symbol,
+ std::function<void(const BrokerQuote&)> cb);
+ void close_quote_feed(const QString& consumer_id, const QString& account_id);
+
// fincept::datahub::Producer
QStringList topic_patterns() const override;
void refresh(const QStringList& topics) override;
@@ -91,6 +105,14 @@ class DataStreamManager : public QObject
bool hub_registered_ = false;
QHash<QString, AccountDataStream*> streams_; // account_id -> stream (parent = this)
+
+ // Open shared quote feeds (Stage 2): consumer_id -> feed handle.
+ struct QuoteFeed {
+ QString account_id;
+ QString topic;
+ QPointer<QObject> owner;
+ };
+ QHash<QString, QuoteFeed> quote_feeds_;
};
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/HistoricalDataService.cpp b/fincept-qt/src/trading/HistoricalDataService.cpp
new file mode 100644
index 000000000..651369798
--- /dev/null
+++ b/fincept-qt/src/trading/HistoricalDataService.cpp
@@ -0,0 +1,179 @@
+// src/trading/HistoricalDataService.cpp
+#include "trading/HistoricalDataService.h"
+
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
+#include "trading/instruments/InstrumentService.h"
+
+#include <QDateTime>
+#include <QPointer>
+#include <QSet>
+#include <QtConcurrent>
+
+namespace fincept::trading {
+
+namespace {
+constexpr qint64 HDS_CACHE_TTL_MS = 60LL * 1000; // candles append slowly; 60s avoids double-fetch
+
+// Map a user-facing timeframe to the broker resolution string. Brokers accept
+// both this and the "1d"/"5m" forms (verified for Zerodha/Fyers/Upstox); the
+// algo path has used this convention across every broker in production.
+QString timeframe_to_resolution(const QString& tf) {
+ if (tf == "1m") return QStringLiteral("1");
+ if (tf == "3m") return QStringLiteral("3");
+ if (tf == "5m") return QStringLiteral("5");
+ if (tf == "15m") return QStringLiteral("15");
+ if (tf == "30m") return QStringLiteral("30");
+ if (tf == "1h") return QStringLiteral("60");
+ if (tf == "4h") return QStringLiteral("240");
+ if (tf == "1d") return QStringLiteral("D");
+ return tf; // already a broker resolution ("60"/"D"/…) or unknown — pass through
+}
+
+// ── Broker symbol resolution (moved here from CandleDataFetcher) ─────────────
+// Most broker get_history() implementations need more than a bare symbol:
+// - token brokers want EXCHANGE:SYMBOL:TOKEN (numeric instrument_token);
+// - tradejini wants the scrip id at parts[1];
+// - the rest resolve EXCHANGE:SYMBOL internally.
+// Unresolvable token brokers return "" so the caller skips/falls back.
+const QSet<QString>& hds_brokers_needing_token() {
+ static const QSet<QString> s = {
+ QStringLiteral("motilal"), QStringLiteral("aliceblue"), QStringLiteral("fivepaisa"),
+ QStringLiteral("iifl"), QStringLiteral("ibkr"), QStringLiteral("saxobank"),
+ };
+ return s;
+}
+
+// Worker-thread-safe synchronous instrument load (private named connection).
+bool hds_ensure_instruments_loaded_blocking(const QString& broker_id) {
+ auto& svc = InstrumentService::instance();
+ if (svc.is_loaded(broker_id))
+ return true;
+ svc.load_from_db_worker(broker_id);
+ return svc.is_loaded(broker_id);
+}
+
+QString hds_resolve_broker_symbol(const QString& broker_id, const QString& bare_symbol,
+ const QString& exchange) {
+ if (bare_symbol.contains(':')) // already fully qualified by caller
+ return bare_symbol;
+ const QString sym = bare_symbol.trimmed().toUpper();
+ const QString exch = exchange.isEmpty() ? QStringLiteral("NSE") : exchange.toUpper();
+
+ if (broker_id == QStringLiteral("tradejini")) { // get_history reads parts[1]
+ if (hds_ensure_instruments_loaded_blocking(broker_id)) {
+ auto inst = InstrumentService::instance().find(sym, exch, broker_id);
+ if (inst) {
+ const QString symid =
+ inst->brsymbol.isEmpty() ? QString::number(inst->instrument_token) : inst->brsymbol;
+ return exch + ":" + symid;
+ }
+ }
+ return exch + ":" + sym; // best-effort
+ }
+ if (hds_brokers_needing_token().contains(broker_id)) { // EXCHANGE:SYMBOL:TOKEN
+ if (!hds_ensure_instruments_loaded_blocking(broker_id))
+ return {};
+ auto tok = InstrumentService::instance().instrument_token(sym, exch, broker_id);
+ if (!tok.has_value() || tok.value() <= 0)
+ return {};
+ return exch + ":" + sym + ":" + QString::number(tok.value());
+ }
+ // Brokers whose get_history resolves the symbol internally — warm the cache so
+ // the lookup succeeds, but pass the bare symbol (they default exchange to NSE).
+ static const QSet<QString> kInternalResolvers = {
+ QStringLiteral("zerodha"), QStringLiteral("angelone"),
+ QStringLiteral("dhan"), QStringLiteral("upstox"),
+ };
+ if (kInternalResolvers.contains(broker_id))
+ hds_ensure_instruments_loaded_blocking(broker_id);
+ return bare_symbol; // everyone else accepts the bare symbol as-is
+}
+
+} // namespace
+
+HistoricalDataService& HistoricalDataService::instance() {
+ static HistoricalDataService s;
+ return s;
+}
+
+void HistoricalDataService::fetch(const QString& symbol, const QString& timeframe,
+ int lookback_days, const QString& broker_id,
+ const QString& account_id, Callback callback) {
+ const QString key =
+ broker_id + "|" + symbol + "|" + timeframe + "|" + QString::number(lookback_days);
+
+ // Serve from cache when fresh (main thread).
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
+ if (auto it = cache_.constFind(key); it != cache_.constEnd()) {
+ if (now - it->fetched_ms < HDS_CACHE_TTL_MS && !it->candles.isEmpty()) {
+ callback(true, it->candles, {});
+ return;
+ }
+ }
+
+ // Load credentials on the calling (main) thread: QSqlDatabase is bound to the
+ // thread that opened it, so SecureStorage::retrieve must not run on a worker.
+ auto creds = AccountManager::instance().load_credentials(account_id);
+ if (creds.api_key.isEmpty()) {
+ callback(false, {}, QStringLiteral("No credentials"));
+ return;
+ }
+
+ QPointer<HistoricalDataService> self = this;
+ (void)QtConcurrent::run(
+ [self, key, symbol, timeframe, lookback_days, broker_id, creds, callback]() {
+ auto* broker = BrokerRegistry::instance().get(broker_id);
+ if (!broker) {
+ QMetaObject::invokeMethod(self ? self.data() : nullptr, [callback]() {
+ callback(false, {}, QStringLiteral("Broker not found"));
+ }, Qt::QueuedConnection);
+ return;
+ }
+
+ const QDateTime to = QDateTime::currentDateTime();
+ const QDateTime from = to.addDays(-lookback_days);
+ const QString resolution = timeframe_to_resolution(timeframe);
+ const QString from_s = from.toString("yyyy-MM-dd");
+ const QString to_s = to.toString("yyyy-MM-dd");
+ const QString resolved = hds_resolve_broker_symbol(broker_id, symbol, QStringLiteral("NSE"));
+
+ auto has_data = [](const ApiResponse<QVector<BrokerCandle>>& r) {
+ return r.success && r.data.value_or(QVector<BrokerCandle>{}).size() > 0;
+ };
+
+ ApiResponse<QVector<BrokerCandle>> result;
+ QString last_err;
+ if (!resolved.isEmpty()) {
+ result = broker->get_history(creds, resolved, resolution, from_s, to_s);
+ if (!result.success)
+ last_err = result.error;
+ } else {
+ last_err = QStringLiteral("symbol resolution failed (no instrument token)");
+ }
+ // Retry with the bare symbol if the resolved form yielded nothing.
+ if (!has_data(result) && resolved != symbol) {
+ auto r2 = broker->get_history(creds, symbol, resolution, from_s, to_s);
+ if (has_data(r2))
+ result = r2;
+ else if (last_err.isEmpty())
+ last_err = r2.error;
+ }
+
+ const bool ok = has_data(result);
+ const QVector<BrokerCandle> candles = result.data.value_or(QVector<BrokerCandle>{});
+ const QString err =
+ ok ? QString() : (last_err.isEmpty() ? QStringLiteral("No data") : last_err);
+
+ QMetaObject::invokeMethod(self ? self.data() : nullptr,
+ [self, key, ok, candles, err, callback]() {
+ if (self && ok)
+ self->cache_.insert(
+ key, CacheEntry{QDateTime::currentMSecsSinceEpoch(), candles});
+ callback(ok, ok ? candles : QVector<BrokerCandle>{}, err);
+ }, Qt::QueuedConnection);
+ });
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/HistoricalDataService.h b/fincept-qt/src/trading/HistoricalDataService.h
new file mode 100644
index 000000000..a9a3e54c1
--- /dev/null
+++ b/fincept-qt/src/trading/HistoricalDataService.h
@@ -0,0 +1,52 @@
+// src/trading/HistoricalDataService.h
+#pragma once
+// HistoricalDataService — one place for broker OHLCV history.
+//
+// Both the equity chart (AccountDataStream::fetch_candles) and the algo engine
+// (CandleDataFetcher) need historical candles from the connected broker. This
+// service unifies that path: broker symbol resolution (token brokers), the
+// get_history call with a bare-symbol fallback, and a short TTL cache so the
+// same series isn't fetched twice when a chart + an algo open it together.
+//
+// It returns the trading-layer BrokerCandle. The algo side converts to its own
+// OhlcvCandle and layers a Yahoo-Finance fallback on top (in CandleDataFetcher)
+// for symbols/brokers the broker history endpoint can't serve.
+#include "trading/TradingTypes.h"
+
+#include <QHash>
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+#include <functional>
+
+namespace fincept::trading {
+
+class HistoricalDataService : public QObject {
+ Q_OBJECT
+ public:
+ static HistoricalDataService& instance();
+
+ using Callback =
+ std::function<void(bool ok, const QVector<BrokerCandle>& candles, const QString& error)>;
+
+ // Fetch `lookback_days` of OHLCV history for `symbol` at `timeframe`
+ // ("1m"/"3m"/"5m"/"15m"/"30m"/"1h"/"4h"/"1d") from `broker_id`/`account_id`.
+ // Served from a short TTL cache when a fresh copy exists. Must be called on
+ // the main thread (loads credentials there for SQLite thread-safety);
+ // `callback` is invoked on the main thread.
+ void fetch(const QString& symbol, const QString& timeframe, int lookback_days,
+ const QString& broker_id, const QString& account_id, Callback callback);
+
+ private:
+ HistoricalDataService() = default;
+ Q_DISABLE_COPY(HistoricalDataService)
+
+ struct CacheEntry {
+ qint64 fetched_ms = 0;
+ QVector<BrokerCandle> candles;
+ };
+ QHash<QString, CacheEntry> cache_; // key: broker|symbol|tf|lookback
+};
+
+} // namespace fincept::trading