# Risk Management SPARQL Templates

PREFIX risk: <http://ggen.dev/ontology/risk-management#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

# Query 1: Calculate portfolio VaR
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?confidenceLevel - Confidence level (e.g., 0.95)
SELECT ?portfolio ?varValue ?varMethod ?timeHorizon
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:calculatesVaR ?var .
  ?var a ?varMethod ;
       risk:varValue ?varValue ;
       risk:confidenceLevel ?confidenceLevel ;
       risk:timeHorizon ?timeHorizon .
  FILTER (?varMethod IN (risk:HistoricalVaR, risk:MonteCarloVaR, risk:ParametricVaR))
}

# Query 2: Get all risk exposures for a portfolio
# PARAM: ?portfolioId - Portfolio identifier
SELECT ?position ?instrument ?quantity ?riskFactor ?exposure
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:hasPosition ?position .
  ?position risk:instrument ?instrument ;
            risk:quantity ?quantity ;
            risk:exposedTo ?riskFactor .
  ?riskFactor risk:exposureAmount ?exposure .
}

# Query 3: Get options Greeks for a portfolio
# PARAM: ?portfolioId - Portfolio identifier
SELECT ?position ?instrument ?delta ?gamma ?vega ?theta ?rho
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:hasPosition ?position .
  ?position risk:instrument ?instrument ;
            risk:measuredBy ?greeks .
  OPTIONAL { ?greeks a risk:Delta ; risk:deltaValue ?delta }
  OPTIONAL { ?greeks a risk:Gamma ; risk:gammaValue ?gamma }
  OPTIONAL { ?greeks a risk:Vega ; risk:vegaValue ?vega }
  OPTIONAL { ?greeks a risk:Theta ; risk:thetaValue ?theta }
  OPTIONAL { ?greeks a risk:Rho ; risk:rhoValue ?rho }
}

# Query 4: Run stress test scenarios
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?scenarioType - Scenario type filter
SELECT ?scenario ?scenarioName ?impact ?probability
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:subjectTo ?stressTest .
  ?stressTest risk:appliesScenario ?scenario .
  ?scenario a ?scenarioType ;
            risk:scenarioName ?scenarioName ;
            risk:impact ?impact ;
            risk:probability ?probability .
}
ORDER BY DESC(?impact)

# Query 5: Get credit risk metrics for counterparties
# PARAM: ?portfolioId - Portfolio identifier
SELECT ?counterparty ?position ?pd ?lgd ?ead ?expectedLoss
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:hasPosition ?position .
  ?position risk:exposedToCounterparty ?counterparty ;
            risk:hasCreditRisk ?creditRisk .
  ?counterparty risk:hasPD ?pdMetric ;
                risk:hasRating ?rating .
  ?pdMetric risk:pdValue ?pd .
  ?counterparty risk:hasLGD ?lgdMetric .
  ?lgdMetric risk:lgdValue ?lgd .
  ?position risk:hasEAD ?eadMetric .
  ?eadMetric risk:eadValue ?ead .
  BIND(?pd * ?lgd * ?ead AS ?expectedLoss)
}
ORDER BY DESC(?expectedLoss)

# Query 6: Check risk limit breaches
# PARAM: ?portfolioId - Portfolio identifier
SELECT ?limit ?limitType ?limitValue ?utilization ?breachAmount ?breachTime
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:governedBy ?limitStructure ;
             risk:breaches ?breach .
  ?limitStructure risk:hasLimit ?limit .
  ?limit risk:limitType ?limitType ;
         risk:limitValue ?limitValue ;
         risk:utilization ?utilization .
  ?breach risk:breachAmount ?breachAmount ;
          risk:breachTime ?breachTime .
  FILTER (?utilization > 1.0)
}
ORDER BY DESC(?breachAmount)

# Query 7: Get historical VaR with backtesting
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?startDate - Start date
# PARAM: ?endDate - End date
SELECT ?date ?varValue ?actualPnL ?breach
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:calculatesVaR ?var .
  ?var a risk:HistoricalVaR ;
       risk:varValue ?varValue ;
       risk:calculationDate ?date .
  ?portfolio risk:actualPnL ?actualPnL .
  BIND(IF(?actualPnL < -?varValue, true, false) AS ?breach)
  FILTER (?date >= ?startDate && ?date <= ?endDate)
}
ORDER BY ?date

# Query 8: Calculate conditional VaR (CVaR/Expected Shortfall)
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?confidenceLevel - Confidence level
SELECT ?portfolio ?cvarValue ?varValue ?excessLoss
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:measuredBy ?cvar .
  ?cvar a risk:ConditionalVaR ;
        risk:cvarValue ?cvarValue ;
        risk:confidenceLevel ?confidenceLevel .
  ?portfolio risk:calculatesVaR ?var .
  ?var risk:varValue ?varValue .
  BIND(?cvarValue - ?varValue AS ?excessLoss)
}

# Query 9: Get credit migration matrix
# PARAM: ?fromRating - Starting credit rating
SELECT ?counterparty ?fromRating ?toRating ?migrationDate ?probability
WHERE {
  ?counterparty risk:hasRating ?rating1 .
  ?rating1 risk:ratingValue ?fromRating ;
           risk:migrationDate ?startDate .
  ?counterparty risk:hasRating ?rating2 .
  ?rating2 risk:ratingValue ?toRating ;
           risk:migrationDate ?migrationDate .
  ?migration risk:fromRating ?fromRating ;
             risk:toRating ?toRating ;
             risk:probability ?probability .
  FILTER (?migrationDate > ?startDate)
}

# Query 10: Reverse stress test
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?maxLoss - Maximum acceptable loss
SELECT ?scenario ?scenarioName ?impact ?factors
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:subjectTo ?reverseTest .
  ?reverseTest a risk:ReverseStressTest ;
               risk:appliesScenario ?scenario ;
               risk:maxAcceptableLoss ?maxLoss .
  ?scenario risk:scenarioName ?scenarioName ;
            risk:impact ?impact ;
            risk:involvedFactors ?factors .
  FILTER (?impact >= ?maxLoss)
}
ORDER BY ?impact

# Query 11: Sensitivity analysis
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?riskFactor - Risk factor to analyze
SELECT ?factor ?baseValue ?shockSize ?impactOnValue ?elasticity
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:subjectTo ?sensitivityAnalysis .
  ?sensitivityAnalysis a risk:SensitivityAnalysis ;
                       risk:analyzesRiskFactor ?factor .
  ?factor risk:factorName ?riskFactor ;
          risk:baseValue ?baseValue ;
          risk:shockSize ?shockSize ;
          risk:impactOnValue ?impactOnValue .
  BIND((?impactOnValue / ?baseValue) / (?shockSize / ?baseValue) AS ?elasticity)
}

# Query 12: Get concentration risk metrics
# PARAM: ?portfolioId - Portfolio identifier
SELECT ?exposureType (SUM(?exposure) AS ?totalExposure) ?limit ?concentration
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:hasPosition ?position ;
             risk:governedBy ?limitStructure .
  ?position risk:exposureType ?exposureType ;
            risk:exposureAmount ?exposure .
  ?limitStructure risk:hasLimit ?concLimit .
  ?concLimit a risk:ConcentrationLimit ;
             risk:exposureType ?exposureType ;
             risk:limitValue ?limit .
  BIND(SUM(?exposure) / ?limit AS ?concentration)
}
GROUP BY ?exposureType ?limit

# Query 13: Calculate incremental VaR
# PARAM: ?portfolioId - Portfolio identifier
# PARAM: ?positionId - Position to analyze
SELECT ?position ?instrument ?portfolioVaR ?newVaR ?incrementalVaR
WHERE {
  ?portfolio risk:portfolioId ?portfolioId ;
             risk:calculatesVaR ?var1 ;
             risk:hasPosition ?position .
  ?var1 risk:varValue ?portfolioVaR .
  ?position risk:positionId ?positionId ;
            risk:instrument ?instrument .
  ?portfolio risk:calculatesVaR ?var2 .
  ?var2 risk:excludesPosition ?position ;
        risk:varValue ?portfolioVaRWithout .
  BIND(?portfolioVaR - ?portfolioVaRWithout AS ?incrementalVaR)
  BIND(?portfolioVaR AS ?newVaR)
}

# Query 14: Get operational risk events
# PARAM: ?startDate - Start date
# PARAM: ?endDate - End date
SELECT ?event ?eventType ?severity ?lossAmount ?eventDate
WHERE {
  ?event a risk:OperationalRiskEvent ;
         risk:eventType ?eventType ;
         risk:severity ?severity ;
         risk:lossAmount ?lossAmount ;
         risk:eventDate ?eventDate .
  FILTER (?eventDate >= ?startDate && ?eventDate <= ?endDate)
}
ORDER BY DESC(?lossAmount)

# Query 15: Monitor key risk indicators (KRIs)
SELECT ?kri ?kriName ?currentValue ?threshold ?status ?trend
WHERE {
  ?kri a risk:KeyRiskIndicator ;
       risk:kriName ?kriName ;
       risk:currentValue ?currentValue ;
       risk:threshold ?threshold ;
       risk:status ?status ;
       risk:trend ?trend .
  FILTER (?currentValue > ?threshold * 0.8)
}
ORDER BY DESC(?currentValue)
