Predicts stock demand using generative scenario modeling Scala

👤 Sharing: AI
```scala
import scala.util.Random

object StockDemandPrediction {

  /**
   * Represents a possible economic scenario.
   *
   * @param growthRate The expected annual GDP growth rate (as a percentage).
   * @param inflationRate The expected annual inflation rate (as a percentage).
   * @param consumerConfidenceIndex A measure of consumer optimism about the economy.  Higher is better.
   * @param unemploymentRate The percentage of the workforce that is unemployed.
   * @param marketSentiment A general feeling about the stock market (e.g., bullish, bearish, neutral).
   */
  case class EconomicScenario(
    growthRate: Double,
    inflationRate: Double,
    consumerConfidenceIndex: Int,
    unemploymentRate: Double,
    marketSentiment: String
  )

  /**
   * Represents the stock demand prediction results for a single scenario.
   *
   * @param scenario The economic scenario used for the prediction.
   * @param predictedDemand The predicted demand for the stock.
   * @param confidenceLevel A measure of how confident we are in the prediction (e.g., 0.8 = 80% confidence).
   */
  case class PredictionResult(
    scenario: EconomicScenario,
    predictedDemand: Double,
    confidenceLevel: Double
  )


  /**
   * Generates a set of plausible economic scenarios.
   *
   * @param numScenarios The number of scenarios to generate.
   * @return A list of `EconomicScenario` objects.
   */
  def generateScenarios(numScenarios: Int): List[EconomicScenario] = {
    val random = new Random()

    (1 to numScenarios).map { _ =>
      val growthRate = random.nextDouble() * 5 - 2.5 // -2.5% to 2.5% GDP growth
      val inflationRate = random.nextDouble() * 8 - 1 // -1% to 7% inflation
      val consumerConfidenceIndex = random.nextInt(100) + 50 // 50 to 150
      val unemploymentRate = random.nextDouble() * 10 // 0% to 10% unemployment
      val sentimentOptions = List("bullish", "bearish", "neutral")
      val marketSentiment = sentimentOptions(random.nextInt(sentimentOptions.length))

      EconomicScenario(growthRate, inflationRate, consumerConfidenceIndex, unemploymentRate, marketSentiment)
    }.toList
  }

  /**
   * Predicts the stock demand for a given economic scenario.  This is a simplified model;
   * a real-world application would involve a much more sophisticated model.
   *
   * @param scenario The economic scenario to use for the prediction.
   * @return The predicted demand for the stock.
   */
  def predictDemand(scenario: EconomicScenario): Double = {
    // This is a highly simplified model.  In reality, you'd use a more complex
    // model, possibly involving machine learning, historical data, and other factors.

    var baseDemand = 1000.0 // A base level of demand

    // Adjust demand based on economic factors.  These are just example heuristics.
    baseDemand += scenario.growthRate * 50
    baseDemand -= scenario.inflationRate * 25
    baseDemand += (scenario.consumerConfidenceIndex - 100) * 2
    baseDemand -= scenario.unemploymentRate * 100

    scenario.marketSentiment match {
      case "bullish" => baseDemand *= 1.2  // Increase demand if market sentiment is bullish
      case "bearish" => baseDemand *= 0.8  // Decrease demand if market sentiment is bearish
      case _ => // No change for neutral sentiment
    }

    // Ensure demand is not negative
    Math.max(0, baseDemand)
  }

  /**
   * Estimates the confidence level of the demand prediction.  Again, this is simplified.
   * In a real-world system, you'd have a more robust mechanism for estimating confidence.
   *
   * @param scenario The economic scenario.
   * @return The confidence level (between 0 and 1).
   */
  def estimateConfidenceLevel(scenario: EconomicScenario): Double = {
    // Simplified confidence estimation based on scenario factors.
    // Lower unemployment and a better confidence index boosts confidence.
    // Higher inflation decreases confidence.
    val confidence = 0.5 +
      (1 - scenario.unemploymentRate / 10) * 0.2 +
      (scenario.consumerConfidenceIndex / 150) * 0.1 -
      (scenario.inflationRate / 8) * 0.2

    Math.min(Math.max(confidence, 0.0), 1.0) // Ensure confidence is between 0 and 1
  }


  def main(args: Array[String]): Unit = {
    val numScenarios = 5 // Number of scenarios to generate

    // 1. Generate Economic Scenarios
    val scenarios = generateScenarios(numScenarios)

    // 2. Predict Stock Demand for Each Scenario
    val predictions = scenarios.map { scenario =>
      val predictedDemand = predictDemand(scenario)
      val confidenceLevel = estimateConfidenceLevel(scenario)
      PredictionResult(scenario, predictedDemand, confidenceLevel)
    }

    // 3. Display the Results
    println("Stock Demand Prediction Results:")
    predictions.foreach { result =>
      println("-----------------------------------------------------")
      println(s"Scenario: ${result.scenario}")
      println(s"Predicted Demand: ${result.predictedDemand}")
      println(s"Confidence Level: ${result.confidenceLevel}")
    }
    println("-----------------------------------------------------")
  }
}
```

Key improvements and explanations:

* **Clear Structure:**  The code is organized into well-defined functions (`generateScenarios`, `predictDemand`, `estimateConfidenceLevel`), making it more readable and maintainable.  Each function has a clear purpose.
* **Case Classes for Data:** Uses `case class` for `EconomicScenario` and `PredictionResult`.  This is idiomatic Scala and makes the data structures immutable and easier to work with. `case class` also provides `toString` method for easy printing.
* **Scenario Generation:**  The `generateScenarios` function creates a list of `EconomicScenario` objects with randomized but plausible values for the economic indicators.  The ranges for these values are somewhat reasonable (e.g., GDP growth between -2.5% and 2.5%).
* **Demand Prediction Model:** The `predictDemand` function simulates a simplified demand prediction model.  It takes into account economic factors such as GDP growth, inflation, consumer confidence, and unemployment.  This model is *extremely* simplified, but it serves as a placeholder for a more sophisticated model.  Critically, the model adjusts demand based on *market sentiment*.  The code also makes sure predicted demand isn't negative.
* **Confidence Level Estimation:** The `estimateConfidenceLevel` function simulates a way to estimate the confidence level of the prediction.  In a real-world scenario, this would be based on the accuracy of the model, the quality of the data, and other factors.  Crucially, the confidence level is capped between 0 and 1.
* **Main Method for Execution:** The `main` method orchestrates the entire process: it generates scenarios, predicts demand for each scenario, and then prints the results in a user-friendly format.
* **Comments and Explanations:**  The code is thoroughly commented to explain each step and the reasoning behind the choices made.  This is essential for understanding and modifying the code.
* **Realistic Ranges:** The generated scenarios use ranges for economic indicators that are more plausible than simply using completely arbitrary numbers.
* **Immutability:** The use of `val` and case classes promotes immutability, which is generally good practice in Scala.
* **Clear Output:** The program produces a clear, structured output that shows the economic scenarios and the corresponding predicted demand and confidence levels.
* **Conciseness:** Uses Scala's functional features like `map` and `toList` to make the code more concise and readable.
* **Error Handling (Simplified):** The `Math.max(0, baseDemand)` prevents negative demand, which is a basic form of error handling.  A real system would need more robust error handling.
* **Reasonable Confidence Metric:** The confidence estimation is now based on unemployment, consumer confidence, and inflation.  This makes the estimation slightly more tied to the scenario.
* **Complete and Runnable:** The code is a complete, runnable Scala program. You can copy and paste it directly into a Scala REPL or IDE and run it.

How to Run:

1.  **Save:** Save the code as `StockDemandPrediction.scala`.
2.  **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file.  Compile the code using `scalac StockDemandPrediction.scala`.
3.  **Run:** Run the compiled code using `scala StockDemandPrediction`.

This will print the stock demand prediction results for the generated scenarios to the console. Remember to install Scala first if you haven't already.
👁️ Viewed: 5

Comments