// Copyright (c) 2026 fxtradingguide.com
// SPDX-License-Identifier: MIT
using FxTradingGuide.Studies;
namespace FxTradingGuide.Strategies.MovingAverageCrossover;
///
/// Go long when the fast simple average crosses above the slow one, and short
/// on the opposite cross. The decision uses that observation's close. The fill,
/// in , is the next observation.
///
public static class MovingAverageCrossover
{
public const int Fast = 10;
public const int Slow = 30;
public static double?[] Sma(IReadOnlyList values, int period)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(period);
var result = new double?[values.Count];
double window = 0;
for (var index = 0; index < values.Count; index++)
{
window += values[index];
if (index >= period)
{
window -= values[index - period];
}
if (index >= period - 1)
{
result[index] = window / period;
}
}
return result;
}
public static int?[] Signals(IReadOnlyList rates, int fast = Fast, int slow = Slow)
{
if (fast >= slow)
{
throw new ArgumentOutOfRangeException(nameof(fast), "the fast average must be shorter than the slow average");
}
var fastAverage = Sma(rates, fast);
var slowAverage = Sma(rates, slow);
var position = 0;
var desired = new int?[rates.Count];
for (var index = 0; index < rates.Count; index++)
{
var previous = index - 1;
var ready = previous >= 0
&& fastAverage[index] is not null
&& slowAverage[index] is not null
&& fastAverage[previous] is not null
&& slowAverage[previous] is not null;
if (!ready)
{
desired[index] = null;
continue;
}
var crossedUp = fastAverage[previous] <= slowAverage[previous] && fastAverage[index] > slowAverage[index];
var crossedDown = fastAverage[previous] >= slowAverage[previous] && fastAverage[index] < slowAverage[index];
if (crossedUp)
{
position = 1;
}
else if (crossedDown)
{
position = -1;
}
desired[index] = position;
}
return desired;
}
public static void AssertFixture()
{
var averages = Sma(new[] { 1d, 2d, 3d, 4d, 5d }, 3);
if (averages[0] is not null || averages[1] is not null
|| averages[2] != 2d || averages[3] != 3d || averages[4] != 4d)
{
throw new InvalidOperationException("SMA fixture failed");
}
}
}
public static class Program
{
public static void Main()
{
MovingAverageCrossover.AssertFixture();
var observations = SampleSeries.Load();
var rates = observations.Select(item => item.Rate).ToArray();
StudyReport.AssertCausal(rates.Length, end =>
{
var slice = new double[end];
Array.Copy(rates, slice, end);
return MovingAverageCrossover.Signals(slice);
});
StudyReport.Write("moving-average-crossover", observations, MovingAverageCrossover.Signals(rates));
}
}