Overall Statistics
/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

namespace QuantConnect.Indicators
{
    /// <summary>
    /// This indicator computes the n-period percentage rate of change in a value using the following:
    /// 100 * (value_0 - value_n) / value_n
    /// </summary>
    public class ROCPRateOfChangePercent : WindowIndicator<IndicatorDataPoint>
    {
        /// <summary>
        /// Creates a new RateOfChangePercent indicator with the specified period
        /// </summary>
        /// <param name="period">The period over which to perform to computation</param>
        public ROCPRateOfChangePercent(int period)
            : base("ROCPROCP" + period, period + 1)
        {
        }

        /// <summary>
        /// Creates a new RateOfChangePercent indicator with the specified period
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="period">The period over which to perform to computation</param>
        public ROCPRateOfChangePercent(string name, int period)
            : base(name, period + 1)
        {
        }

        /// <summary>
        /// Computes the next value for this indicator from the given state.
        /// </summary>
        /// <param name="window">The window of data held in this indicator</param>
        /// <param name="input">The input value to this indicator on this time step</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input)
        {
            // if we're not ready just grab the first input point in the window
            decimal denominator = !window.IsReady ? window[window.Count - 1] : window.MostRecentlyRemoved;
            decimal newDenom = !window.IsReady ? window[window.Count - 2] : window[window.Count - 1];
			
            if (denominator == 0 || newDenom == 0)
            {
                return 0;
            }
            
            
			decimal oldROCP = (window[0] - denominator)/denominator;
			decimal newROCP = (input - newDenom)/newDenom;
			if (oldROCP == 0)
			{
				return 0;
			}
            return 100*(newROCP - oldROCP)/oldROCP;
        }
    }
}
using MathNet.Numerics;

namespace QuantConnect
{
	public class AnnualizedExponentialSlope : WindowIndicator<IndicatorDataPoint>
    {
        public AnnualizedExponentialSlope(int period)
            : base("AdjustedSlope" + period, period)
        {
        }

        public AnnualizedExponentialSlope(string name, int period)
            : base(name, period)
        {
        }

        protected override decimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input)
        {
            if (window.Count < 3) return 0m;

            var xVals = new double[window.Count];
            var yVals = new double[window.Count];

            // load input data for regression
            for (int i = 0; i < window.Count; i++)
            {
                xVals[i] = i;
                // we want the log of our y values
                yVals[i] = Math.Log((double)window[window.Count - i - 1].Value);
            }

            //http://numerics.mathdotnet.com/Regression.html

            // solves y=a + b*x via linear regression
            var fit = Fit.Line(xVals, yVals);
            var intercept = fit.Item1;
            var slope = fit.Item2;

            // compute rsquared
            var rsquared = GoodnessOfFit.RSquared(xVals.Select(x => intercept + slope*x), yVals);

            // anything this small can be viewed as flat
            if (double.IsNaN(slope) || Math.Abs(slope) < 1e-25) return 0m;

            // trading days per year for us equities
            const int dayCount = 252;

            // annualize dy/dt
            var annualSlope = ((Math.Pow(Math.Exp(slope), dayCount)) - 1) * 100;

            // scale with rsquared
            annualSlope = annualSlope * rsquared;

            return (decimal) annualSlope;
        }
    }
}
namespace QuantConnect 
{   
    public class BasicTemplateAlgorithm : QCAlgorithm
    {
    	private RateOfChangePercent ROCPyear;
    	private ROCPRateOfChangePercent ROCPROCPyear;
    	private string symbol;
    	
        public override void Initialize() 
        {
            SetStartDate(2006, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(25000);
            symbol = "LNG";
            AddSecurity(SecurityType.Equity, symbol, Resolution.Daily);
            
            ROCPyear = new RateOfChangePercent(252); // 252 trading days in a US year
            RegisterIndicator(symbol, ROCPyear, Resolution.Daily, Field.Close);
            PlotIndicator("ROCP", true, ROCPyear);
            ROCPROCPyear = new ROCPRateOfChangePercent(252);
            RegisterIndicator(symbol, ROCPROCPyear, Resolution.Daily, Field.Close);
            PlotIndicator("ROCP", true, ROCPROCPyear);
        }

        //Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
        public void OnData(TradeBars data) 
        {
        	if (!ROCPyear.IsReady) return;
        	
        	var quantity = Portfolio[symbol].Quantity;
        	if (quantity == 0 && ROCPyear > 20)
        	{
        		SetHoldings(symbol, .75);
        	}
        	if (quantity > 0) {
        		if (ROCPyear < 0) {
        			SetHoldings(symbol, 0);
        		}
        	}
        	if (quantity < 0) {
        		if (ROCPyear > 0) {
        			SetHoldings(symbol, 0);
        		}
        	}
        	if (quantity == 0 && ROCPyear < -20)
        	{
        			SetHoldings(symbol, -.75);
        	}
        }
    }
}