Add TBar, TBarSeries, TSeries, TValue, and IFeed implementations with comprehensive documentation and examples

- Introduced TBar struct for efficient OHLCV data representation.
- Implemented TBarSeries class for high-performance collection of TBar instances using Structure of Arrays (SoA) layout.
- Added TSeries class for time-series data management with zero-copy access.
- Created TValue struct for time-value pairs with implicit conversions.
- Defined IFeed interface for consistent data feed implementations.
- Developed CsvFeed class for loading historical OHLCV data from CSV files.
- Implemented GBM class for generating synthetic financial data using Geometric Brownian Motion.
- Added Quantower project files for Averages indicator with necessary dependencies and configurations.
- Included extensive usage examples and notebooks for TBar, TBarSeries, TSeries, TValue, and feed implementations.
This commit is contained in:
Miha Kralj
2025-11-27 19:51:43 -08:00
parent 1c8f514756
commit 74b49d2bb4
37 changed files with 1379 additions and 462 deletions
+45
View File
@@ -0,0 +1,45 @@
# IFeed Interface
`IFeed` defines the standard contract for all data feeds in QuanTAlib, ensuring consistent behavior across different data sources (synthetic, file-based, or live API).
## Key Concepts
- **Bidirectional Control**: The `Next(ref bool isNew)` method allows the consumer to request a new bar (`isNew = true`) or an update to the current bar (`isNew = false`).
- **Streaming**: Designed for bar-by-bar processing, simulating real-time data flow.
- **Batching**: Supports fetching historical data ranges via `Fetch()`.
## Interface Definition
```csharp
public interface IFeed
{
/// <summary>
/// Gets the next bar with full control over new/update state.
/// </summary>
TBar Next(ref bool isNew);
/// <summary>
/// Convenience overload for simple next-bar requests.
/// </summary>
TBar Next(bool isNew = true);
/// <summary>
/// Retrieves a batch of historical bars.
/// </summary>
TBarSeries Fetch(int count, long startTime, TimeSpan interval);
}
```
## Implementation Guidelines
When implementing `IFeed`:
1. **State Management**: Maintain the current position in the data source.
2. **End of Data**: When data is exhausted, `Next` should return the last valid bar and set `isNew` to `false`.
3. **Intra-bar Updates**: If the source supports it (e.g., live ticks), `Next(isNew: false)` should return the updated state of the current bar. If not supported (e.g., CSV), it should return the current bar unchanged.
4. **Thread Safety**: Implementations are generally not required to be thread-safe unless specified.
## Implementations
- **`GBM`**: Geometric Brownian Motion generator (Synthetic).
- **`CsvFeed`**: Reads OHLCV data from CSV files (Historical).
+68
View File
@@ -0,0 +1,68 @@
#!meta
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"name":"csharp","languageName":"csharp"},{"name":"fsharp","languageName":"F#","aliases":["f#","fs"]},{"name":"html","languageName":"HTML"},{"name":"http","languageName":"HTTP"},{"name":"javascript","languageName":"JavaScript","aliases":["js"]},{"name":"mermaid","languageName":"Mermaid"},{"name":"pwsh","languageName":"PowerShell","aliases":["powershell"]},{"name":"value"}]}}
#!csharp
// Reference the library
#r "..\..\bin\QuanTAlib.dll"
using QuanTAlib;
using System.IO;
// 1. Setup: Use existing CSV file
// CsvFeed expects a CSV with header: timestamp,open,high,low,close,volume
// Timestamp format: YYYY-MM-DD
string csvPath = "daily_IBM.csv";
Console.WriteLine($"Using CSV file: {csvPath}");
#!csharp
// 2. Initialize CsvFeed
// The feed loads the data and prepares it for streaming
var feed = new CsvFeed(csvPath);
Console.WriteLine("CsvFeed initialized.");
#!csharp
// 3. Streaming Data
// Simulate processing historical data bar by bar
Console.WriteLine("\nStreaming data (first 5 bars):");
int count = 0;
bool isNew = true;
// Get first bar
var bar = feed.Next(isNew: true);
while (isNew && count < 5)
{
count++;
Console.WriteLine($" Bar {count}: {bar}");
// Get next bar
bar = feed.Next(ref isNew);
}
Console.WriteLine($"Streamed {count} bars.");
#!csharp
// 4. Batch Fetching
// Retrieve a specific range of data
Console.WriteLine("\nBatch fetching:");
// Using a date range present in daily_IBM.csv (July 2025)
long startTime = new DateTime(2025, 7, 8).Ticks;
var interval = TimeSpan.FromDays(1);
// Fetch 3 bars starting from July 8th, 2025
var batch = feed.Fetch(5, startTime, interval);
Console.WriteLine($"Fetched {batch.Count} bars:");
foreach (var b in batch)
{
Console.WriteLine($" {b}");
}
+68
View File
@@ -0,0 +1,68 @@
# CsvFeed Class
`CsvFeed` is a file-based feed implementation that loads historical OHLCV data from CSV files. It supports both streaming access (simulating real-time playback) and batch retrieval.
## Key Features
- **Historical Data Loading**: Reads standard OHLCV CSV files.
- **Chronological Ordering**: Automatically reverses data if needed (assumes newest-first in file, provides oldest-first).
- **Streaming Interface**: Implements `IFeed` for consistent usage with other feed types.
- **Batch Retrieval**: Supports fetching specific time ranges via `Fetch()`.
## CSV Format Requirements
The file must have a header row and follow this column order:
`timestamp, open, high, low, close, volume`
- **Timestamp**: `YYYY-MM-DD` (assumed UTC midnight)
- **Prices/Volume**: Numeric values
Example:
```csv
Date,Open,High,Low,Close,Volume
2024-01-01,100.0,105.0,99.0,102.5,10000
2024-01-02,102.5,103.0,101.0,101.5,8500
```
## Class Definition
```csharp
public class CsvFeed : IFeed
{
public CsvFeed(string filePath);
public TBar Next(bool isNew = true);
public TBarSeries Fetch(int count, long startTime, TimeSpan interval);
}
```
## Usage
### 1. Loading Data
```csharp
var feed = new CsvFeed("path/to/data.csv");
```
### 2. Streaming Data (Simulation)
```csharp
// Get first bar
var bar = feed.Next(isNew: true);
// Loop through all data
while (true)
{
// Process bar...
Console.WriteLine(bar);
// Get next bar
bool isNew = true;
bar = feed.Next(ref isNew);
// Stop if no more new data
if (!isNew) break;
}
```
### 3. Fetching a Batch
```csharp
long startTime = new DateTime(2024, 1, 1).Ticks;
var batch = feed.Fetch(10, startTime, TimeSpan.FromDays(1));
+69
View File
@@ -0,0 +1,69 @@
#!meta
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"name":"csharp","languageName":"csharp"},{"name":"fsharp","languageName":"F#","aliases":["f#","fs"]},{"name":"html","languageName":"HTML"},{"name":"http","languageName":"HTTP"},{"name":"javascript","languageName":"JavaScript","aliases":["js"]},{"name":"mermaid","languageName":"Mermaid"},{"name":"pwsh","languageName":"PowerShell","aliases":["powershell"]},{"name":"value"}]}}
#!csharp
// Reference the library
#r "..\..\bin\QuanTAlib.dll"
using QuanTAlib;
// 1. Initialize GBM Generator
// GBM simulates price movements using Geometric Brownian Motion
// Parameters: Start Price, Drift (mu), Volatility (sigma)
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2);
Console.WriteLine("GBM Generator initialized (Start=100, Drift=5%, Vol=20%)");
#!csharp
// 2. Batch Generation
// Generate a sequence of bars at once
// Useful for backtesting or initializing indicators
long startTime = DateTime.UtcNow.Ticks;
var interval = TimeSpan.FromMinutes(1);
var history = gbm.Fetch(10, startTime, interval);
Console.WriteLine($"Generated {history.Count} bars:");
for (int i = 0; i < history.Count; i++)
{
Console.WriteLine($" Bar {i}: Time={history[i].AsDateTime:HH:mm}, Close={history[i].Close:F2}");
}
#!csharp
// 3. Streaming Generation
// Simulate real-time data feed bar by bar
Console.WriteLine("\nStreaming new bars:");
for (int i = 0; i < 3; i++)
{
var bar = gbm.Next(isNew: true);
Console.WriteLine($" New Bar: {bar.Close:F2}");
}
#!csharp
// 4. Intra-bar Updates
// Simulate real-time price ticks within a single bar
// The High/Low will expand, and Close will update
Console.WriteLine("\nSimulating intra-bar updates:");
// Start a new bar
var liveBar = gbm.Next(isNew: true);
Console.WriteLine($" Open: {liveBar.Open:F2}, Close: {liveBar.Close:F2}");
// Simulate 5 ticks
for (int i = 1; i <= 5; i++)
{
liveBar = gbm.Next(isNew: false);
Console.WriteLine($" Tick {i}: Close={liveBar.Close:F2}, High={liveBar.High:F2}, Low={liveBar.Low:F2}");
}
// Finalize bar
liveBar = gbm.Next(isNew: true);
Console.WriteLine($" Finalized Previous, Started New: {liveBar.Open:F2}");
+67
View File
@@ -0,0 +1,67 @@
# GBM Class
`GBM` (Geometric Brownian Motion) is a synthetic data generator that simulates realistic financial price movements. It is useful for testing indicators, strategies, and system performance without relying on external data files.
## Key Features
- **Geometric Brownian Motion**: Uses the standard mathematical model for asset price dynamics.
- **Configurable Parameters**: Control drift (trend) and volatility (noise).
- **Stateless Design**: Minimal memory footprint; only maintains state needed for continuity.
- **Dual Modes**: Supports both streaming (bar-by-bar) and batch generation.
- **Intra-bar Updates**: Can simulate real-time price updates within a single bar.
## Mathematical Model
The price evolution follows the stochastic differential equation:
$$ dS_t = \mu S_t dt + \sigma S_t dW_t $$
Where:
- $S_t$: Asset price at time $t$
- $\mu$: Drift (expected return)
- $\sigma$: Volatility (standard deviation of returns)
- $W_t$: Wiener process (Brownian motion)
## Class Definition
```csharp
public class GBM : IFeed
{
public GBM(double startPrice = 100.0, double mu = 0.05, double sigma = 0.2, TimeSpan? defaultTimeframe = null);
public TBar Next(bool isNew = true);
public TBarSeries Fetch(int count, long startTime, TimeSpan interval);
}
```
## Usage
### 1. Initialization
```csharp
// Default: Start at 100, 5% drift, 20% volatility
var gbm = new GBM();
// Custom: Start at 50, 10% drift, 50% volatility
var volatileGbm = new GBM(startPrice: 50.0, mu: 0.10, sigma: 0.50);
```
### 2. Streaming Generation
```csharp
// Generate a new bar
var bar = gbm.Next(isNew: true);
// Simulate intra-bar updates (e.g., real-time ticks)
for (int i = 0; i < 5; i++)
{
var updatedBar = gbm.Next(isNew: false);
Console.WriteLine($"Update: {updatedBar.Close}");
}
```
### 3. Batch Generation
```csharp
long startTime = DateTime.UtcNow.Ticks;
var interval = TimeSpan.FromMinutes(1);
// Generate 1000 bars
var history = gbm.Fetch(1000, startTime, interval);