Indian Share Market Price Prediction Application in .NET 8
Below is a complete implementation of a .NET 8 application that accepts an Indian company name and predicts its share price after a configured number of days. This solution uses a simple moving average approach for prediction (note that real stock prediction is much more complex and would require advanced machine learning models).
Solution Structure
- Console Application - For user interaction
- Prediction Service - Contains the prediction logic
- Configuration - For setting prediction parameters
Implementation
1. Create a new .NET 8 Console Application
dotnet new console -n StockPricePredictor
cd StockPricePredictor
2. Add required NuGet packages
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package CsvHelper
3. Project Structure
StockPricePredictor/
├── appsettings.json
├── Program.cs
├── Services/
│ ├── IStockPredictionService.cs
│ ├── StockPredictionService.cs
│ └── StockDataService.cs
├── Models/
│ ├── StockData.cs
│ └── PredictionResult.cs
└── Data/
└── sample_stock_data.csv
4. Implementation Files
appsettings.json
{
"PredictionSettings": {
"DefaultPredictionDays": 7,
"MovingAverageWindow": 30,
"DataFilePath": "Data/sample_stock_data.csv"
}
}
Models/StockData.cs
namespace StockPricePredictor.Models;
public class StockData
{
public string CompanyName { get; set; }
public DateTime Date { get; set; }
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public long Volume { get; set; }
}
Models/PredictionResult.cs
namespace StockPricePredictor.Models;
public class PredictionResult
{
public string CompanyName { get; set; }
public DateTime PredictionDate { get; set; }
public decimal CurrentPrice { get; set; }
public decimal PredictedPrice { get; set; }
public int DaysAhead { get; set; }
public string PredictionMethod { get; set; }
}
Services/IStockPredictionService.cs
using StockPricePredictor.Models;
namespace StockPricePredictor.Services;
public interface IStockPredictionService
{
Task<PredictionResult> PredictStockPriceAsync(string companyName, int daysAhead);
}
Services/StockPredictionService.cs
using StockPricePredictor.Models;
using Microsoft.Extensions.Options;
namespace StockPricePredictor.Services;
public class StockPredictionService : IStockPredictionService
{
private readonly StockDataService _stockDataService;
private readonly PredictionSettings _settings;
public StockPredictionService(StockDataService stockDataService, IOptions<PredictionSettings> settings)
{
_stockDataService = stockDataService;
_settings = settings.Value;
}
public async Task<PredictionResult> PredictStockPriceAsync(string companyName, int daysAhead)
{
var stockData = await _stockDataService.GetStockDataAsync(companyName);
if (stockData == null || !stockData.Any())
{
throw new InvalidOperationException($"No data found for company: {companyName}");
}
// Get the most recent data point
var latestData = stockData.OrderByDescending(s => s.Date).First();
var currentPrice = latestData.Close;
// Simple moving average prediction
var movingAverage = CalculateMovingAverage(stockData, _settings.MovingAverageWindow);
// Simple prediction: assume the price will follow the moving average trend
var predictedPrice = movingAverage * (1 + CalculateTrendFactor(stockData));
return new PredictionResult
{
CompanyName = companyName,
PredictionDate = DateTime.Today.AddDays(daysAhead),
CurrentPrice = currentPrice,
PredictedPrice = predictedPrice,
DaysAhead = daysAhead,
PredictionMethod = $"Moving Average ({_settings.MovingAverageWindow} days)"
};
}
private decimal CalculateMovingAverage(IEnumerable<StockData> stockData, int window)
{
var closingPrices = stockData
.OrderByDescending(s => s.Date)
.Take(window)
.Select(s => s.Close)
.ToList();
return closingPrices.Average();
}
private decimal CalculateTrendFactor(IEnumerable<StockData> stockData)
{
var orderedData = stockData.OrderBy(s => s.Date).ToList();
if (orderedData.Count < 2) return 0;
var firstPrice = orderedData.First().Close;
var lastPrice = orderedData.Last().Close;
return (lastPrice - firstPrice) / firstPrice;
}
}
Services/StockDataService.cs
using StockPricePredictor.Models;
using CsvHelper;
using System.Globalization;
using Microsoft.Extensions.Options;
namespace StockPricePredictor.Services;
public class StockDataService
{
private readonly PredictionSettings _settings;
public StockDataService(IOptions<PredictionSettings> settings)
{
_settings = settings.Value;
}
public async Task<IEnumerable<StockData>> GetStockDataAsync(string companyName)
{
// In a real application, this would fetch from a database or API
// For this example, we'll use a CSV file
if (!File.Exists(_settings.DataFilePath))
{
throw new FileNotFoundException($"Stock data file not found at {_settings.DataFilePath}");
}
using var reader = new StreamReader(_settings.DataFilePath);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csv.GetRecords<StockData>().ToList();
return records.Where(r => r.CompanyName.Equals(companyName, StringComparison.OrdinalIgnoreCase));
}
}
PredictionSettings.cs
namespace StockPricePredictor.Services;
public class PredictionSettings
{
public int DefaultPredictionDays { get; set; }
public int MovingAverageWindow { get; set; }
public string DataFilePath { get; set; }
}
Program.cs
using StockPricePredictor.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
services.AddOptions<PredictionSettings>()
.Bind(hostContext.Configuration.GetSection("PredictionSettings"));
services.AddSingleton<StockDataService>();
services.AddSingleton<IStockPredictionService, StockPredictionService>();
})
.Build();
var predictionService = host.Services.GetRequiredService<IStockPredictionService>();
var config = host.Services.GetRequiredService<IConfiguration>();
var defaultPredictionDays = config.GetValue<int>("PredictionSettings:DefaultPredictionDays");
Console.WriteLine("Indian Share Market Price Predictor");
Console.WriteLine("===================================");
Console.Write("Enter company name: ");
var companyName = Console.ReadLine();
Console.Write($"Enter number of days ahead to predict (default {defaultPredictionDays}): ");
var input = Console.ReadLine();
if (!int.TryParse(input, out var daysAhead) || daysAhead <= 0)
{
daysAhead = defaultPredictionDays;
}
try
{
var prediction = await predictionService.PredictStockPriceAsync(companyName, daysAhead);
Console.WriteLine("\nPrediction Results:");
Console.WriteLine("------------------");
Console.WriteLine($"Company: {prediction.CompanyName}");
Console.WriteLine($"Current Price: ₹{prediction.CurrentPrice:N2}");
Console.WriteLine($"Predicted Price in {prediction.DaysAhead} days: ₹{prediction.PredictedPrice:N2}");
Console.WriteLine($"Prediction Method: {prediction.PredictionMethod}");
Console.WriteLine($"Prediction Date: {prediction.PredictionDate:d}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
5. Sample Data File (Data/sample_stock_data.csv)
CompanyName,Date,Open,High,Low,Close,Volume
RELIANCE,2023-01-01,2400.50,2450.75,2390.25,2430.50,1234567
RELIANCE,2023-01-02,2435.00,2475.25,2425.75,2460.00,1345678
RELIANCE,2023-01-03,2465.50,2500.75,2455.25,2485.50,1456789
TCS,2023-01-01,3200.50,3250.75,3190.25,3230.50,987654
TCS,2023-01-02,3235.00,3275.25,3225.75,3260.00,1098765
TCS,2023-01-03,3265.50,3300.75,3255.25,3285.50,1209876
INFY,2023-01-01,1500.50,1550.75,1490.25,1530.50,2345678
INFY,2023-01-02,1535.00,1575.25,1525.75,1560.00,2456789
INFY,2023-01-03,1565.50,1600.75,1555.25,1585.50,2567890
How to Use the Application
- Run the application:
dotnet run
- Enter a company name (e.g., "RELIANCE", "TCS", "INFY")
- Enter the number of days ahead you want to predict (or press enter for default)
- The application will display the prediction results
Important Notes
-
This is a simplified example using moving averages for prediction. Real stock prediction would require:
- More sophisticated algorithms (machine learning models)
- Access to real-time market data
- Consideration of many more factors (market trends, company news, economic indicators, etc.)
-
For a production application, you would want to:
- Connect to a real stock data API
- Implement proper error handling
- Add logging
- Consider using a database for historical data
- Implement more sophisticated prediction algorithms
-
The sample data is very limited. In a real application, you would need comprehensive historical data.
-
Stock market predictions are inherently uncertain and should not be used for actual trading decisions without proper financial analysis.