Here's a step-by-step guide to building a .NET 8 Blazor application that:
- Accepts an Indian share market company name (ticker symbol).
- Predicts the share price after a configured number of days using a simple LSTM (Long Short-Term Memory) model via ML.NET.
- Downloads the prediction results as a ZIP file.
Disclaimer: Stock market prediction is inherently complex and risky. This example uses a simplified LSTM model for educational purposes. It is NOT financial advice and should not be used for actual trading.
Prerequisites
- .NET 8 SDK installed.
- Python 3.x (for fetching historical stock data via
yfinance).
- ML.NET (for LSTM-based time series forecasting).
- Visual Studio 2022 or VS Code.
Let's break this into parts:
- Blazor App Setup
- Python Data Fetcher (fetch NSE data)
- C# Data Service (run Python script)
- ML.NET LSTM Prediction Service
- ZIP Generation & Download
- Blazor UI
Step 1: Create Blazor Project
Create a new .NET 8 Blazor Web App:
dotnet new blazor -o IndianStockPredictor -int Server
cd IndianStockPredictor
Install required NuGet packages:
dotnet add package Microsoft.ML
dotnet add package Microsoft.ML.TimeSeries
dotnet add package System.IO.Compression
Step 2: Python Data Fetcher
Create a folder PythonScripts. Inside it, create fetch_stock_data.py.
PythonScripts/fetch_stock_data.py:
import yfinance as yf
import pandas as pd
import sys
def fetch_stock_data(ticker_symbol, output_path):
# NSE tickers need .NS suffix
if not ticker_symbol.endswith(".NS"):
ticker_symbol += ".NS"
try:
data = yf.download(ticker_symbol, period="2y")
if data.empty:
print(f"Error: No data found for {ticker_symbol}", file=sys.stderr)
return False
# Save 'Date' and 'Close' columns
data.reset_index(inplace=True)
data[['Date', 'Close']].to_csv(output_path, index=False)
return True
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return False
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python fetch_stock_data.py <TICKER> <OUTPUT_CSV>", file=sys.stderr)
sys.exit(1)
ticker = sys.argv[1]
output_file = sys.argv[2]
success = fetch_stock_data(ticker, output_file)
if not success:
sys.exit(1)
Step 3: C# Models & Services
Create a Models folder.
Models/StockData.cs:
public class StockData
{
public DateTime Date { get; set; }
public float Close { get; set; }
}
Models/PredictionResult.cs:
public class PredictionResult
{
public DateTime Date { get; set; }
public float PredictedPrice { get; set; }
}
Now, create a Services folder.
Services/StockDataService.cs (runs Python script):
using System.Diagnostics;
public class StockDataService
{
private readonly IWebHostEnvironment _env;
private readonly string _pythonPath = "python"; // Adjust if needed
public StockDataService(IWebHostEnvironment env) => _env = env;
public async Task<string> FetchStockDataAsync(string ticker)
{
var pythonScript = Path.Combine(_env.ContentRootPath, "PythonScripts", "fetch_stock_data.py");
var outputCsv = Path.Combine(_env.ContentRootPath, "Data", $"{ticker}_data.csv");
Directory.CreateDirectory(Path.GetDirectoryName(outputCsv));
var startInfo = new ProcessStartInfo
{
FileName = _pythonPath,
Arguments = $"\"{pythonScript}\" \"{ticker}\" \"{outputCsv}\"",
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(startInfo);
await process.WaitForExitAsync();
if (process.ExitCode != 0)
{
string errors = await process.StandardError.ReadToEndAsync();
throw new Exception($"Python script failed: {errors}");
}
if (!File.Exists(outputCsv)) throw new FileNotFoundException("CSV not created.");
return outputCsv;
}
}
Services/PredictionService.cs (LSTM via ML.NET):
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms.TimeSeries;
public class PredictionService
{
public List<PredictionResult> PredictFuturePrices(string csvFilePath, int daysToPredict)
{
var mlContext = new MLContext();
var data = mlContext.Data.LoadFromTextFile<StockData>(csvFilePath, hasHeader: true, separatorChar: ',');
// Prepare data (Close prices as a time series)
var pipeline = mlContext.Forecasting.ForecastBySsa(
outputColumnName: "Forecast",
inputColumnName: nameof(StockData.Close),
windowSize: 7, // Weekly seasonality
seriesLength: data.GetRowCount() ?? 0,
horizon: daysToPredict,
confidenceLevel: 0.95f,
confidenceLowerBoundColumn: "LowerBound",
confidenceUpperBoundColumn: "UpperBound");
var model = pipeline.Fit(data);
var forecastEngine = model.CreateTimeSeriesEngine<StockData, Forecast>(mlContext);
// Forecast future prices
var forecast = forecastEngine.Predict();
var results = new List<PredictionResult>();
var lastDate = File.ReadAllLines(csvFilePath)
.Skip(1) // Skip header
.Select(line => DateTime.Parse(line.Split(',')[0]))
.Last();
for (int i = 0; i < daysToPredict; i++)
{
results.Add(new PredictionResult
{
Date = lastDate.AddDays(i + 1),
PredictedPrice = forecast.Forecast[i]
});
}
return results;
}
}
public class Forecast
{
[ColumnName("Forecast")]
public float[] Forecast { get; set; }
}
Services/ZipService.cs:
using System.IO.Compression;
using System.Text;
public class ZipService
{
public byte[] CreatePredictionZip(string ticker, List<PredictionResult> predictions)
{
using var ms = new MemoryStream();
using var archive = new ZipArchive(ms, ZipArchiveMode.Create, true);
var csv = new StringBuilder();
csv.AppendLine("Date,PredictedPrice");
foreach (var pred in predictions)
{
csv.AppendLine($"{pred.Date:yyyy-MM-dd},{pred.PredictedPrice:F2}");
}
var entry = archive.CreateEntry($"{ticker}_predictions.csv");
using var writer = new StreamWriter(entry.Open());
writer.Write(csv.ToString());
return ms.ToArray();
}
}
Step 4: Register Services
In Program.cs:
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddScoped<StockDataService>();
builder.Services.AddScoped<PredictionService>();
builder.Services.AddScoped<ZipService>();
Step 5: JavaScript for File Download
Create wwwroot/js/fileUtils.js:
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = fileName;
anchor.click();
URL.revokeObjectURL(url);
};
Reference it in Components/App.razor:
<head>
<!-- ... -->
<script src="js/fileUtils.js"></script>
</head>
Step 6: Blazor UI (Predict.razor)
Create Components/Pages/Predict.razor:
@page "/predict"
@inject StockDataService DataService
@inject PredictionService PredictionService
@inject ZipService ZipService
@inject IJSRuntime JSRuntime
<h1>Indian Stock Price Predictor</h1>
<div class="card p-4">
<label>Ticker (e.g., RELIANCE, INFY):</label>
<input @bind="ticker" class="form-control mb-2" />
<label>Days to Predict:</label>
<input type="number" @bind="days" class="form-control mb-3" min="1" max="30" />
<button class="btn btn-primary" @onclick="Predict" disabled="@isBusy">
@if (isBusy)
{
<span class="spinner-border spinner-border-sm"></span> Processing...
}
else
{
<span>Predict</span>
}
</button>
</div>
@if (error != null)
{
<div class="alert alert-danger">@error</div>
}
@if (predictions != null)
{
<h3>Predictions for @ticker</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Predicted Price (₹)</th>
</tr>
</thead>
<tbody>
@foreach (var pred in predictions)
{
<tr>
<td>@pred.Date.ToString("dd-MMM-yyyy")</td>
<td>@pred.PredictedPrice.ToString("F2")</td>
</tr>
}
</tbody>
</table>
<button class="btn btn-success" @onclick="DownloadZip">Download as ZIP</button>
}
@code {
string ticker = "RELIANCE";
int days = 10;
bool isBusy = false;
string error = null;
List<PredictionResult> predictions = null;
async Task Predict()
{
isBusy = true;
error = null;
predictions = null;
try
{
var csvPath = await DataService.FetchStockDataAsync(ticker);
predictions = PredictionService.PredictFuturePrices(csvPath, days);
File.Delete(csvPath); // Cleanup
}
catch (Exception ex)
{
error = $"Error: {ex.Message}";
}
finally
{
isBusy = false;
}
}
async Task DownloadZip()
{
if (predictions == null) return;
var zipBytes = ZipService.CreatePredictionZip(ticker, predictions);
var fileName = $"{ticker}_predictions_{DateTime.Now:yyyyMMdd}.zip";
using var stream = new MemoryStream(zipBytes);
using var streamRef = new DotNetStreamReference(stream);
await JSRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}
}
Step 7: Run the App
- Ensure
yfinance and pandas are installed:
pip install yfinance pandas
- Run the Blazor app:
dotnet run
- Open your browser, navigate to
/predict.
- Enter a ticker (e.g.,
INFY, TCS).
- Set days (e.g.,
15).
- Click Predict.
- View the table of predicted prices.
- Click Download as ZIP to get a ZIP file with the results.
Notes:
- This uses SSA (Singular Spectrum Analysis), a robust time series model in ML.NET.
- For real production-grade predictions, consider LSTM via TensorFlow.NET or PyTorch.NET with GPU acceleration.
- Always validate tickers (e.g., against NSE/BSE APIs) to avoid errors.
Happy coding! 🚀
Folder Structure Recap:
IndianStockPredictor/
├── Components/
│ ├── Pages/
│ │ └── Predict.razor
│ └── App.razor
├── Models/
│ ├── StockData.cs
│ └── PredictionResult.cs
├── PythonScripts/
│ └── fetch_stock_data.py
├── Services/
│ ├── StockDataService.cs
│ ├── PredictionService.cs
│ └── ZipService.cs
├── wwwroot/
│ └── js/
│ └── fileUtils.js
├── Program.cs
└── IndianStockPredictor.csproj