Skip to content

Instantly share code, notes, and snippets.

@kiranmaya
Created March 7, 2024 13:56
Show Gist options
  • Save kiranmaya/b3fa1ce6aa3a5f086f3cc0db8ae241e5 to your computer and use it in GitHub Desktop.
Save kiranmaya/b3fa1ce6aa3a5f086f3cc0db8ae241e5 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace MainTrade
{
public class KNNRegressionLorenzian
{
private List<STOCK> _data;
public KNNRegressionLorenzian(List<STOCK> data)
{
_data = data;
}
public void AddStock(STOCK stock)
{
_data.Add(stock);
}
public void RemoveStock(STOCK stock)
{
_data.Remove(stock);
}
public double Predict(STOCK query, int k)
{
var distances = _data.Select(stock => new { Stock = stock, Distance = CalculateDistance(query, stock) })
.OrderBy(item => item.Distance)
.Take(k);
double sum = 0;
double totalWeight = 0;
foreach(var item in distances)
{
double weight = 1.0f / (1.0f + item.Distance);
sum += item.Stock.LastPrice * weight; // Use any other property as needed
totalWeight += weight;
}
return sum / totalWeight;
}
private double CalculateDistance(STOCK query, STOCK stock)
{
// Lorenzian distance
double distance = Math.Sqrt(Math.Pow(query.LastPrice - stock.LastPrice, 2))
+ Math.Sqrt(Math.Pow(query.AskPrice - stock.AskPrice, 2))
+ Math.Sqrt(Math.Pow(query.BidPrice - stock.BidPrice, 2))
+ Math.Sqrt(Math.Pow(query.BuyersDepth - stock.BuyersDepth, 2))
+ Math.Sqrt(Math.Pow(query.BuyersDepth - stock.BuyersDepth, 2))
+ Math.Sqrt(Math.Pow(query.LastTradeVolume - stock.LastTradeVolume, 2))
+ Math.Sqrt(Math.Pow(query.DayVolume - stock.DayVolume, 2));
return distance;
}
}
}
@kiranmaya
Copy link
Author

kiranmaya commented Mar 7, 2024

private double CalculateDistance(STOCK query, STOCK stock)
{
// Lorenzian distance
double distance = Math.Pow(Math.Sqrt(Math.Abs(query.LastPrice - stock.LastPrice)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.AskPrice - stock.AskPrice)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.BidPrice - stock.BidPrice)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.BuyersDepth - stock.BuyersDepth)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.SellersDepth - stock.SellersDepth)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.LastTradeVolume - stock.LastTradeVolume)), 2)
+ Math.Pow(Math.Sqrt(Math.Abs(query.DayVolume - stock.DayVolume)), 2);

return distance;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment