DEV Community

Cover image for Developing an Equity Business Application with .NET 8, Azure, and AI
Paulo Torres
Paulo Torres

Posted on

Developing an Equity Business Application with .NET 8, Azure, and AI

In the competitive world of finance, equity investors require sophisticated tools to make informed decisions. By leveraging .NET 8, Azure, and Artificial Intelligence (AI), developers can build robust applications that provide real-time insights, predictive analytics, and a seamless user experience. This article presents a real-world example of creating an equity business application for investors, complete with code snippets, configurations, and detailed explanations.

Scenario: Building an Equity Investment Platform

Our goal is to develop an equity investment platform that offers:

  • Real-time stock data visualization
  • Predictive analytics for stock performance
  • Personalized investment recommendations
  • Secure user authentication and data protection

Image description

Setting Up the Development Environment

Prerequisites

Image description

Here is an outline of the key steps involved:

Image description

Now, let's dive into the development process.

Let's walk through the process step by step.

Step 1: Creating the .NET 8 Web Application

Initialize a new ASP.NET Core Web Application.

dotnet new webapp -n EquityInvestorPlatform
cd EquityInvestorPlatform
Enter fullscreen mode Exit fullscreen mode

Project Structure

  • Frontend: ASP.NET Core Razor Pages or Blazor for interactive UI
  • Backend: ASP.NET Core Web API for data processing
  • Data Layer: Entity Framework Core with SQL Server
  • AI Integration: Azure Machine Learning for predictive analytics
  • Authentication: Azure Active Directory (Azure AD) for secure login

Step 2: Implementing Secure User Authentication with Azure AD

Registering the Application in Azure AD

  1. Navigate to the Azure Portal and go to Azure Active Directory.
  2. Under App registrations, click New registration.
  3. Enter a Name for your app (e.g., "EquityInvestorPlatform").
  4. Set the Redirect URI to https://localhost:5001/signin-oidc.
  5. Click Register.

Configuring the Application

Install the necessary NuGet packages.

dotnet add package Microsoft.AspNetCore.Authentication.AzureAD.UI
dotnet add package Microsoft.Identity.Web
Enter fullscreen mode Exit fullscreen mode

Modify Program.cs to configure authentication.

using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Configure Azure AD authentication
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

var app = builder.Build();

// Enable authentication middleware
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();
Enter fullscreen mode Exit fullscreen mode

Add the Azure AD configuration to appsettings.json.

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "yourdomain.onmicrosoft.com",
  "TenantId": "your-tenant-id",
  "ClientId": "your-client-id",
  "CallbackPath": "/signin-oidc"
}
Enter fullscreen mode Exit fullscreen mode

Protecting Routes

Apply the [Authorize] attribute to secure pages.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;

[Authorize]
public class DashboardModel : PageModel
{
    public void OnGet()
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Integrating Real-Time Stock Data

Using a Third-Party API

We'll use a financial data API like Alpha Vantage or Yahoo Finance.

Installing HttpClientFactory

dotnet add package Microsoft.Extensions.Http
Enter fullscreen mode Exit fullscreen mode

Configuring Services

In Program.cs:

builder.Services.AddHttpClient("StockDataClient", client =>
{
    client.BaseAddress = new Uri("https://www.alphavantage.co/");
});
Enter fullscreen mode Exit fullscreen mode

Creating the Stock Service

public class StockService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey = "YOUR_ALPHA_VANTAGE_API_KEY";

    public StockService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("StockDataClient");
    }

    public async Task<StockQuote> GetStockQuoteAsync(string symbol)
    {
        var response = await _httpClient.GetAsync($"/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={_apiKey}");
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        // Deserialize JSON to StockQuote object
        var stockQuote = JsonConvert.DeserializeObject<StockQuote>(content);
        return stockQuote;
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating Models

public class StockQuote
{
    [JsonProperty("Global Quote")]
    public GlobalQuote GlobalQuote { get; set; }
}

public class GlobalQuote
{
    [JsonProperty("01. symbol")]
    public string Symbol { get; set; }

    [JsonProperty("05. price")]
    public string Price { get; set; }

    // Add other properties as needed
}
Enter fullscreen mode Exit fullscreen mode

Displaying Data in the UI

In your Razor Page:

@page
@model IndexModel
@inject StockService StockService

<h2>Stock Quote</h2>
<form method="post">
    <input type="text" name="Symbol" placeholder="Enter Stock Symbol" />
    <button type="submit">Get Quote</button>
</form>

@if (Model.StockQuote != null)
{
    <div>
        <p>Symbol: @Model.StockQuote.GlobalQuote.Symbol</p>
        <p>Price: @Model.StockQuote.GlobalQuote.Price</p>
    </div>
}

@functions {
    public StockQuote StockQuote { get; set; }

    public async Task OnPostAsync(string symbol)
    {
        StockQuote = await StockService.GetStockQuoteAsync(symbol);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Implementing Predictive Analytics with Azure Machine Learning

Creating a Predictive Model

Use Azure Machine Learning Studio to:

  1. Prepare Data: Historical stock data.
  2. Train Model: Use regression algorithms to predict future stock prices.
  3. Deploy Model: Expose the model as a REST endpoint.

Consuming the Model in the Application

Installing Necessary Packages

dotnet add package Newtonsoft.Json
Enter fullscreen mode Exit fullscreen mode

Creating the Prediction Service

public class PredictionService
{
    private readonly HttpClient _httpClient;
    private readonly string _endpoint = "YOUR_AZURE_ML_ENDPOINT";
    private readonly string _apiKey = "YOUR_AZURE_ML_API_KEY";

    public PredictionService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
    }

    public async Task<PredictionResult> PredictStockPriceAsync(PredictionInput input)
    {
        var request = new HttpRequestMessage(HttpMethod.Post, _endpoint);
        request.Headers.Add("Authorization", $"Bearer {_apiKey}");
        request.Content = new StringContent(JsonConvert.SerializeObject(input), Encoding.UTF8, "application/json");

        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        var predictionResult = JsonConvert.DeserializeObject<PredictionResult>(content);
        return predictionResult;
    }
}

public class PredictionInput
{
    public string Symbol { get; set; }
    public DateTime Date { get; set; }
    // Other features as required
}

public class PredictionResult
{
    public float PredictedPrice { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Integrating with the UI

In your Razor Page:

@page
@model PredictionModel
@inject PredictionService PredictionService

<h2>Predict Stock Price</h2>
<form method="post">
    <input type="text" name="Symbol" placeholder="Enter Stock Symbol" />
    <input type="date" name="Date" />
    <button type="submit">Predict Price</button>
</form>

@if (Model.PredictedPrice != null)
{
    <div>
        <p>Predicted Price: @Model.PredictedPrice</p>
    </div>
}

@functions {
    public float? PredictedPrice { get; set; }

    public async Task OnPostAsync(string symbol, DateTime date)
    {
        var input = new PredictionInput { Symbol = symbol, Date = date };
        var result = await PredictionService.PredictStockPriceAsync(input);
        PredictedPrice = result.PredictedPrice;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Providing Personalized Investment Recommendations

Using AI for Recommendations

Developing the Recommendation Model

  • Data: User portfolio, investment history, risk tolerance.
  • Algorithm: Collaborative filtering or content-based filtering.
  • Deployment: Use Azure Machine Learning to deploy the model as a service.

Consuming the Recommendation Service

public class RecommendationService
{
    private readonly HttpClient _httpClient;
    private readonly string _endpoint = "YOUR_RECOMMENDATION_API_ENDPOINT";
    private readonly string _apiKey = "YOUR_API_KEY";

    public RecommendationService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
    }

    public async Task<List<Recommendation>> GetRecommendationsAsync(string userId)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, $"{_endpoint}?userId={userId}");
        request.Headers.Add("Authorization", $"Bearer {_apiKey}");

        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        var recommendations = JsonConvert.DeserializeObject<List<Recommendation>>(content);
        return recommendations;
    }
}

public class Recommendation
{
    public string Symbol { get; set; }
    public float ExpectedReturn { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Displaying Recommendations in the Dashboard

@page
@model DashboardModel
@inject RecommendationService RecommendationService

<h2>Your Personalized Recommendations</h2>

@if (Model.Recommendations != null)
{
    <ul>
        @foreach (var rec in Model.Recommendations)
        {
            <li>@rec.Symbol - Expected Return: @rec.ExpectedReturn%</li>
        }
    </ul>
}

@functions {
    public List<Recommendation> Recommendations { get; set; }

    public async Task OnGetAsync()
    {
        var userId = User.Identity.Name;
        Recommendations = await RecommendationService.GetRecommendationsAsync(userId);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Data Storage with Entity Framework Core and SQL Server

Installing Entity Framework Core

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Enter fullscreen mode Exit fullscreen mode

Creating the Data Context

public class EquityDbContext : DbContext
{
    public EquityDbContext(DbContextOptions<EquityDbContext> options)
        : base(options)
    {
    }

    public DbSet<UserPortfolio> Portfolios { get; set; }
    public DbSet<StockTransaction> Transactions { get; set; }
}

public class UserPortfolio
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public List<StockTransaction> Transactions { get; set; }
}

public class StockTransaction
{
    public int Id { get; set; }
    public string Symbol { get; set; }
    public int Shares { get; set; }
    public decimal PriceAtPurchase { get; set; }
    public DateTime PurchaseDate { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Configuring the Database Connection

In appsettings.json:

"ConnectionStrings": {
  "EquityDb": "Server=(localdb)\\mssqllocaldb;Database=EquityDb;Trusted_Connection=True;"
}
Enter fullscreen mode Exit fullscreen mode

In Program.cs:

builder.Services.AddDbContext<EquityDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("EquityDb")));
Enter fullscreen mode Exit fullscreen mode

Applying Migrations

dotnet ef migrations add InitialCreate
dotnet ef database update
Enter fullscreen mode Exit fullscreen mode

Step 7: Deploying to Azure

Creating Azure Resources

  • App Service: For hosting the web application.
  • Azure SQL Database: For data storage.
  • Azure Machine Learning Services: For AI models.
  • Azure Key Vault: For managing secrets.

Deployment Steps

Publish the Application

Use Visual Studio or Azure CLI to publish the application to Azure App Service.

# Create a resource group
az group create --name EquityInvestorRG --location "East US"

# Create an App Service plan
az appservice plan create --name EquityInvestorPlan --resource-group EquityInvestorRG --sku B1

# Create a Web App
az webapp create --resource-group EquityInvestorRG --plan EquityInvestorPlan --name EquityInvestorApp

# Deploy the app
dotnet publish -c Release
az webapp deploy --resource-group EquityInvestorRG --name EquityInvestorApp --src-path ./bin/Release/net8.0/publish
Enter fullscreen mode Exit fullscreen mode

Configure Connection Strings and App Settings

Set environment variables for connection strings and API keys.

az webapp config connection-string set --resource-group EquityInvestorRG --name EquityInvestorApp \
    --settings EquityDb="Server=tcp:yourserver.database.windows.net;Database=EquityDb;User ID=...;Password=...;" --connection-string-type SQLAzure

az webapp config appsettings set --resource-group EquityInvestorRG --name EquityInvestorApp --settings \
    AzureMLApiKey="YOUR_AZURE_ML_API_KEY" \
    AlphaVantageApiKey="YOUR_ALPHA_VANTAGE_API_KEY"
Enter fullscreen mode Exit fullscreen mode

Step 8: Ensuring Security and Compliance

Using Azure Key Vault

Store sensitive information like API keys and connection strings in Azure Key Vault.

Create a Key Vault

az keyvault create --name EquityInvestorVault --resource-group EquityInvestorRG --location "East US"
Enter fullscreen mode Exit fullscreen mode

Add Secrets to Key Vault

az keyvault secret set --vault-name EquityInvestorVault --name "AlphaVantageApiKey" --value "YOUR_API_KEY"
Enter fullscreen mode Exit fullscreen mode

Configure the App to Access Key Vault

In Program.cs, use Managed Identity to access Key Vault.

builder.Configuration.AddAzureKeyVault(new Uri("https://EquityInvestorVault.vault.azure.net/"), new DefaultAzureCredential());
Enter fullscreen mode Exit fullscreen mode

Enabling HTTPS and SSL

Force HTTPS in the Azure App Service settings and configure SSL certificates if using custom domains.

Conclusion

By integrating .NET 8, Azure services, and AI technologies, we've developed a comprehensive equity investment platform that meets the needs of modern investors. This application demonstrates how cutting-edge technologies can be combined to deliver real-time data, predictive analytics, and personalized experiences while maintaining high security and compliance standards.

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Paulo Torres,
Top 5, very nice and helpful !
Thanks for sharing.