AB.Measure exposure. Understand uncertainty. Decide with context.All projects

Financial Analytics

Casablanca Risk

A Casablanca Stock Exchange risk-intelligence platform combining a 124,562-row historical panel, stock and portfolio risk analysis, volatility and regime models, simulation, and structured news context.

Web ScrapingFinancial RiskGARCH / HMMPortfolio AnalyticsNews Classification
View source repository ↗
Casablanca Risk interface

Why it matters

Makes local market exposure and uncertainty understandable without presenting risk analytics as price prediction or investment advice.

My role

Financial data analyst and solution developer

  1. 01Engineered quote and financial-news collectors with Requests, Beautiful Soup, Pandas, source adapters, robots.txt checks, caching, scheduling, validation, deduplication, and failure-safe atomic writes.
  2. 02Assembled and validated 124,562 daily observations across 78 symbols, delayed quotes, issuer references, portfolio records, and multilingual financial news.
  3. 03Implemented stock, market, tail, liquidity, regime, portfolio, simulation, and event-level risk analysis with explicit validation and investability gates.
  4. 04Translated risk evidence into rankings, profiles, portfolio scorecards, news context, and virtual trading without presenting analytics as price prediction.
01

Market data challenge

Free per-stock Casablanca history is fragmented. The current analytical panel contains 124,562 daily observations across 78 symbols from January 2015 to June 2026, with MASI history, delayed quotes, issuer references, and explicit source and verification labels.

02

Data acquisition & web scraping

Python collectors built with Requests, Beautiful Soup, and Pandas retrieve delayed Casablanca Stock Exchange quotes and French/Arabic financial news from Casablanca Bourse, AMMC, Medias24, L'Economiste, Boursenews, Finances News Hebdo, and La Vie Eco. Source-specific adapters normalize inconsistent HTML into stable quote, issuer, article, timestamp, and provenance schemas.

03

Reliable feed engineering

The quote collector can run every 30 minutes during market hours, respects robots.txt, caches raw HTML for traceability, skips overlapping runs with lock files, and preserves append-only quote history. Temporary outputs must pass required-column, row-count, and positive-price checks before atomic replacement; the last valid snapshot remains available if a refresh fails.

04

News normalization & provenance

Cross-source deduplication groups normalized same-day headlines, selects the most reliable canonical source, and retains corroborating sources. Every item carries source type, verification status, reliability, confidence, language, collection time, and deterministic company, sector, theme, risk, and opportunity mappings.

05

Data quality & freshness

Quote and news refreshes validate schemas, row counts, and numeric prices before atomic replacement. Feed status records attempts, successes, age, row counts, errors, and repeated failures so the interface can expose stale data honestly.

06

Stock & market risk

The platform calculates annualised return and volatility, Sharpe ratio, maximum drawdown, beta to MASI, historical VaR, Expected Shortfall, relative-risk scores, market breadth, sector movement, correlation, and stock-level data-quality signals.

07

Liquidity & investability

Amihud illiquidity, zero-return share, observation coverage, and security-master flags identify stale or difficult-to-trade names. These gates prevent low-quality or illiquid securities from entering portfolio and event-study conclusions without sufficient evidence.

08

Forecasting & validation

GARCH forecasts volatility, HMM identifies market regimes, and Kupiec backtesting checks VaR exceedances. The objective is to forecast risk conditions rather than future prices.

09

Portfolio construction

Equal weight, minimum variance, Hierarchical Risk Parity, and MASI buy-and-hold are compared using an investable universe and Ledoit-Wolf covariance shrinkage. Scorecards expose position weights, concentration, weighted volatility, beta, and downside exposure.

010

Walk-forward evidence

Out-of-sample walk-forward tests use periodic rebalancing, transaction costs, survivorship-aware filtering, and saved historical weights. In the latest report, minimum variance produced about 11.0% annualised return, 11.5% volatility, and a 0.75 Sharpe versus approximately 5.4%, 13.3%, and 0.28 for MASI buy-and-hold.

011

Monte Carlo risk distribution

A 10,000-path, 252-day HRP simulation reports the complete outcome distribution rather than one forecast. The latest run showed about a 35.7% probability of loss, 6.5% median return, a negative 19.8% fifth-percentile return, 41.2% ninety-fifth percentile, and a negative 14.9% median maximum drawdown.

012

Event-level analysis

Market-model event studies calculate abnormal returns, CAR[-5,+5], CAR[0,+1], CAR[0,+5], abnormal-volume ratios, and sentiment/confidence context. Liquidity, observation, and event-count gates prevent weak data from being presented as a meaningful conclusion.

013

French & Arabic news

Financial stories are collected from market, regulator, and media sources. Deterministic aliases and sector/theme dictionaries attach context, while multilingual processing and auditable tags describe risk or opportunity without issuing buy/sell signals.

014

Analytical findings

The work highlights that domestic diversification can be limited by bank and telecom concentration, while the MASI's lower correlation with global indices may make Moroccan equities more relevant in an international diversification context.

015

Decision support

Searchable market snapshots, stock risk profiles, risk rankings, news context, portfolio simulation, and virtual trading translate the analysis into an educational workflow with visible uncertainty and data limitations.

Technical implementation

How the solution was built.

Each layer connects an implementation choice to the decision or workflow it supports.

07 layers
LayerImplementationOperational purpose
Market collectionRequests, Beautiful Soup and source-specific adapters for delayed quotes and issuer dataBuild a consistent local-market panel from fragmented public sources
News collectionFrench and Arabic financial-news scraping with normalized headlines, provenance and cross-source deduplicationConnect market analysis to traceable company, sector and macro context
Data reliabilityrobots.txt checks, raw-response caching, schema validation, lock files, scheduling and atomic writesPreserve the last valid dataset and expose stale or failed refreshes honestly
Risk measurementVolatility, beta, drawdown, historical VaR, Expected Shortfall, correlation and liquidity indicatorsCompare stock and portfolio exposure with interpretable downside measures
Risk modellingGARCH volatility forecasts, HMM regimes and Kupiec VaR backtestingEstimate changing risk conditions and verify whether loss thresholds remain credible
Portfolio analysisMinimum variance, Hierarchical Risk Parity, Ledoit-Wolf covariance and walk-forward testingCompare allocations using out-of-sample evidence, costs and investability gates
Simulation and events10,000-path Monte Carlo distributions and market-model event studiesQuantify ranges of outcomes and examine abnormal behaviour around news events

Product walkthrough

Screens connected to decisions.

11 screens
Casablanca Risk: concept art
01
concept art

Documents the concept art stage of Casablanca Risk and the evidence available to its user.

Casablanca Risk: market snapshot
02
market snapshot

Makes the listed market searchable and comparable through price, volume, capitalization, and recent movement.

Casablanca Risk: stock detail
03
stock detail

Combines historical price context with market value, traded value, and relative-risk indicators.

Casablanca Risk: stock risk profile
04
stock risk profile

Translates volatility, VaR, expected shortfall, and drawdown into a readable risk profile.

Casablanca Risk: stock news disclosures
05
stock news disclosures

Connects company-level disclosures and sentiment context to the security being examined.

Casablanca Risk: news risk context
06
news risk context

Maps news to stocks, sectors, and macro themes to distinguish risk signals from opportunity context.

Casablanca Risk: practice account summary
07
practice account summary

Keeps virtual cash, invested capital, positions, and return visible before entering the simulator.

Casablanca Risk: tracked risk ranking
08
tracked risk ranking

Ranks tracked securities by comparable risk measures instead of implying price direction.

Casablanca Risk: paper trading simulator
09
paper trading simulator

Lets users test their own analysis with virtual money, delayed prices, and explicit transaction costs.

Casablanca Risk: holdings risk scorecard
10
holdings risk scorecard

Connects position-level P&L with portfolio concentration, weighted volatility, and beta.

Casablanca Risk: news signal details
11
news signal details

Expands each article into traceable risk and opportunity tags with source and confidence context.

Continue exploring03 / 11
Next project · Data AnalyticsExecutive Performance AnalyticsA dashboard earns its place when a metric changes a decision.↗
← Previous · FaultForgeView project archive
Project archiveGitHub repository ↗Discuss this work ↗