Labels

Wednesday, October 24, 2018

Sample code of Back Testing




using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

#region "Interface"
public interface IDataHandler
{
    StockPrice Get(string Symbol, DateTime Current);
    string Symbols { get; set; }
 
    ICollection<string> Symbols { get; }
    bool ContinueBacktest { get; }
    DateTime? CurrentTime { get; }
    //Bar GetLast(string symbol);
    decimal? GetLastClosePrice(string symbol);
    void Update();
}

public interface IStrategy
{
    /// <summary>
    /// Provides the mechanisms to calculate the list of signals.
    /// </summary>
    void CalculateSignals(PriceChangeEventArgs e);
}
#endregion

public class Price
{

}

public class PriceChangeEventArgs : EventArgs
{
    protected StockPrice Current;

    public PriceChangeEventArgs(StockPrice CurrentPrice)
    {
        this.Current = CurrentPrice;
    }

    public StockPrice CurrentPrice
    {
        get { return this.Current; }
    }

}
public delegate void PriceChangeEventHandler(PriceChangeEventArgs e);

public class Strategy
{
    public virtual void CalculateSignals(PriceChangeEventArgs e)
    {
        Debug.Print("CalculateSignals");
        ///Buy Signal
     
        ///Sell Signal
     
    }
}

class BackTest
{
    public event PriceChangeEventHandler PriceChangeEvent;
    protected IDataHandler DataSource;

    List<String> Transaction;

    public BackTest(IDataHandler Yahoo, IStrategy StrategyHandler)
    {
        DataSource = Yahoo;
        PriceChangeEvent += new PriceChangeEventHandler(StrategyHandler.CalculateSignals);
    }

    public void Simulate(String Symbol, DateTime StartDate, DateTime EndDate)
    {
        for (DateTime i = StartDate; i<=EndDate; i.AddDays(1) )
        {
            StockPrice Price = DataSource.Get(Symbol, i);
            PriceChangeEvent(new PriceChangeEventArgs(Price));
        }



    }
}


No comments:

Post a Comment