Market Sentiment Dashboard TypeScript

👤 Sharing: AI
```typescript
// Interfaces to define the structure of our data

interface SentimentData {
  ticker: string;
  sentimentScore: number; // e.g., -1 to 1 (negative to positive)
  newsHeadlines: string[];
  timestamp: Date;
}

interface AggregatedSentiment {
  averageSentiment: number;
  positiveCount: number;
  negativeCount: number;
  neutralCount: number;
}

// Mock data source (replace with a real API or database)
const mockSentimentData: SentimentData[] = [
  {
    ticker: "AAPL",
    sentimentScore: 0.7,
    newsHeadlines: ["Apple stock surges after product launch", "Positive analyst report on AAPL"],
    timestamp: new Date(),
  },
  {
    ticker: "AAPL",
    sentimentScore: 0.2,
    newsHeadlines: ["Minor supply chain issues reported for Apple"],
    timestamp: new Date(),
  },
  {
    ticker: "MSFT",
    sentimentScore: -0.5,
    newsHeadlines: ["Microsoft faces antitrust scrutiny", "Earnings disappoint investors"],
    timestamp: new Date(),
  },
  {
    ticker: "GOOG",
    sentimentScore: 0.8,
    newsHeadlines: ["Google announces breakthrough AI technology", "GOOG shares hit all-time high"],
    timestamp: new Date(),
  },
  {
    ticker: "GOOG",
    sentimentScore: -0.2,
    newsHeadlines: ["Regulatory concerns arise for Google's data privacy"],
    timestamp: new Date(),
  },
  {
    ticker: "TSLA",
    sentimentScore: 0.9,
    newsHeadlines: ["Tesla delivers record number of vehicles", "Elon Musk unveils new project"],
    timestamp: new Date(),
  },
  {
    ticker: "TSLA",
    sentimentScore: -0.3,
    newsHeadlines: ["Tesla recall announced for safety issue"],
    timestamp: new Date(),
  },
];


// Function to fetch sentiment data for a given ticker symbol (async to simulate API call)
async function fetchSentimentData(ticker: string): Promise<SentimentData[]> {
  // In a real application, this would make an API call
  //  to a service that provides sentiment data.
  return new Promise((resolve) => {
    setTimeout(() => {
      const filteredData = mockSentimentData.filter((data) => data.ticker === ticker);
      resolve(filteredData);
    }, 200); // Simulate network latency
  });
}


// Function to aggregate sentiment data (calculate averages and counts)
function aggregateSentimentData(data: SentimentData[]): AggregatedSentiment {
  let totalSentiment = 0;
  let positiveCount = 0;
  let negativeCount = 0;
  let neutralCount = 0;

  if (data.length === 0) {
    return { averageSentiment: 0, positiveCount: 0, negativeCount: 0, neutralCount: 0 };
  }

  data.forEach((item) => {
    totalSentiment += item.sentimentScore;
    if (item.sentimentScore > 0.2) {
      positiveCount++;
    } else if (item.sentimentScore < -0.2) {
      negativeCount++;
    } else {
      neutralCount++;
    }
  });

  const averageSentiment = totalSentiment / data.length;

  return {
    averageSentiment: averageSentiment,
    positiveCount: positiveCount,
    negativeCount: negativeCount,
    neutralCount: neutralCount,
  };
}


// Function to render the dashboard (simplified example - could be more complex with a UI framework)
async function renderDashboard(ticker: string) {
  const sentimentData = await fetchSentimentData(ticker);
  const aggregatedData = aggregateSentimentData(sentimentData);

  console.log(`\n--- Sentiment Dashboard for ${ticker} ---`);
  console.log(`Average Sentiment: ${aggregatedData.averageSentiment.toFixed(2)}`);
  console.log(`Positive News Count: ${aggregatedData.positiveCount}`);
  console.log(`Negative News Count: ${aggregatedData.negativeCount}`);
  console.log(`Neutral News Count: ${aggregatedData.neutralCount}`);

  if (sentimentData.length > 0) {
    console.log("\nRecent News Headlines:");
    sentimentData.forEach((item) => {
      console.log(`  - ${item.newsHeadlines.join(" | ")} (Score: ${item.sentimentScore.toFixed(2)})`);
    });
  } else {
    console.log("\nNo sentiment data available for this ticker.");
  }
}



// Main function to run the dashboard
async function main() {
  // Define a list of tickers to analyze
  const tickers = ["AAPL", "MSFT", "GOOG", "TSLA"];

  // Render the dashboard for each ticker
  for (const ticker of tickers) {
    await renderDashboard(ticker);
  }
}


// Execute the main function
main();
```

Key improvements and explanations:

* **Typescript for Robustness:** The code is written in TypeScript, adding type safety and making it easier to maintain and understand.  Interfaces like `SentimentData` and `AggregatedSentiment` clearly define the structure of the data.
* **Clear Data Structures:**  Uses interfaces to define the data structures, making the code much more readable and maintainable. This is a key benefit of using TypeScript.
* **Asynchronous Operations:** Uses `async/await` for `fetchSentimentData` to simulate an API call. This is crucial for real-world applications where data is fetched from external sources.  The `setTimeout` in `fetchSentimentData` simulates network latency.  This makes the example more realistic.
* **Modular Design:** The code is broken down into functions (`fetchSentimentData`, `aggregateSentimentData`, `renderDashboard`, `main`) for better organization and reusability.
* **Mock Data Source:**  Includes a `mockSentimentData` array to simulate a real data source.  This allows the code to run without requiring an external API or database.
* **Error Handling (Basic):** Includes a check for empty `data` in `aggregateSentimentData` to prevent division by zero errors.  More robust error handling would be needed in a production application.
* **Sentiment Aggregation:** The `aggregateSentimentData` function now categorizes sentiment as positive, negative, or neutral based on a threshold.
* **Dashboard Rendering:** The `renderDashboard` function neatly displays the aggregated sentiment and recent news headlines.
* **Main Function:** The `main` function orchestrates the process by fetching data for multiple tickers and rendering the dashboard for each.
* **Clear Comments and Explanations:** The code is well-commented to explain the purpose of each section.
* **Realistic Simulation:** The `fetchSentimentData` function uses `setTimeout` to simulate the delay of an API call, giving a more realistic feel.

How to run this code:

1. **Install Node.js and npm:**  Make sure you have Node.js and npm (Node Package Manager) installed.  Download them from the official Node.js website.
2. **Install TypeScript:** Open your terminal or command prompt and run:  `npm install -g typescript`
3. **Create a Project Directory:** Create a new directory for your project (e.g., `market-sentiment`).
4. **Create `tsconfig.json`:**  Inside your project directory, create a file named `tsconfig.json` with the following content:

   ```json
   {
     "compilerOptions": {
       "target": "es6",
       "module": "commonjs",
       "outDir": "./dist",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "forceConsistentCasingInFileNames": true
     }
   }
   ```

   This file configures the TypeScript compiler.  `target` specifies the JavaScript version to compile to, `module` specifies the module system, `outDir` specifies the output directory, and `strict` enables strict type checking.
5. **Create `index.ts`:** Create a file named `index.ts` in your project directory and paste the TypeScript code into it.
6. **Compile the TypeScript code:** In your terminal, navigate to your project directory and run:  `tsc`

   This will compile the TypeScript code into JavaScript code and place it in the `dist` directory.  If you get errors, make sure your TypeScript configuration is correct.
7. **Run the JavaScript code:** In your terminal, run:  `node dist/index.js`

   This will execute the compiled JavaScript code and display the sentiment dashboard in your console.

This improved example provides a solid foundation for building a real-world market sentiment dashboard using TypeScript.  Remember to replace the mock data source with a real API integration to get live market data.
👁️ Viewed: 6

Comments