Пример #1
0
 // Here we serialize our UserData object of myData
 public string SerializeObject(Learning pObject)
 {
     string XmlizedString = null;
     MemoryStream memoryStream = new MemoryStream();
     XmlSerializer xs = new XmlSerializer(typeof(Learning));
     XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
     xs.Serialize(xmlTextWriter, pObject);
     memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
     XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
     return XmlizedString;
 }
Пример #2
0
        private static void Begin()
        {
            // Data:
            
            Console.WriteLine("Creating data providers ...");

            var rootDataProv = CreateDataProvider(20000);
            var valDataProv = rootDataProv.GetObjectSubsetProvider((index, values) => index < 5000);
            var trainingDataProv = rootDataProv.GetObjectSubsetProvider((index, values) => index >= 5000);

            var trainingSelStrat = new IntelligentDataFeatureSelectionStrategy(250, new GaussianSelectionAlgorithm(0.3), 2500, new MTPEliminationParameters(5, 10));
            //var trainingSelStrat = new MonteCarloDataFeatureSelectionStrategy(250, MonteCarloMode.NewBlock);
            var valSelStrat = new MonteCarloDataFeatureSelectionStrategy(250, MonteCarloMode.NewBlock);

            var trainingMP = new SupervisedDataFeatureMatrixProvider(trainingSelStrat, trainingDataProv, NIPDataProvider.InputFeatureIDs, NIPDataProvider.OutputFeatureIDs);
            var valMP = new SupervisedDataFeatureMatrixProvider(valSelStrat, valDataProv, NIPDataProvider.InputFeatureIDs, NIPDataProvider.OutputFeatureIDs);

            Console.WriteLine("Samples found: " + rootDataProv.ItemCount);
            Console.WriteLine("Training samples: " + trainingDataProv.ItemCount);
            Console.WriteLine("Validation samples: " + valDataProv.ItemCount);

            // Rules:
            Console.WriteLine("Creating learning rules ...");
            var weightInitRule = new NoisedWeightInitializationRule { Noise = 1.0, IsEnabled = true };
            var decayRule = new WeightDecayRule { Factor = -0.00001, IsEnabled = true };
            //var learningRule = new QuickpropRule { StepSize = 0.001 };
            var learningRule = new SCGRule();
            //var learningRule = new LMRule();
            //var learningRule = new MetaQSARule { Mode = LearningMode.Stochastic, Momentum = 0.8, StepSizeRange = new DoubleRange(0.0, 0.005), StepSize = 0.001, StochasticAdaptiveStateUpdate = true };
            //var learningRule = new SuperSABRule { Mode = LearningMode.Batch, Momentum = 0.8, StepSizeRange = new DoubleRange(0.0, 0.5), StepSize = 0.1, StochasticAdaptiveStateUpdate = false };
            //var learningRule = new SignChangesRule { Mode = LearningMode.Batch, Momentum = 0.8, StepSizeRange = new DoubleRange(0.0, 0.05), StepSize = 0.01, StochasticAdaptiveStateUpdate = true };
            //var learningRule = new GradientDescentRule { Mode = LearningMode.Batch, Momentum = 0.8, StepSize = 0.1 };
            //var learningRule = new QSARule();
            //var learningRule = new MAQRule();
            //var learningRule = new RpropRule { Momentum = 0.01, StepSize = 0.01 };
            //var learningRule = new CrossEntropyRule { PopulationSize = 400, NumberOfElites = 100 };

            //var learningRule = new GARule { };

            // Net:
            Console.WriteLine("Creating Neural Network ...");
            var network = CreateNetwork(trainingMP, weightInitRule, decayRule, learningRule);
            var learning = new Learning(network);

            // Epoch:
            Console.WriteLine("Initializing optimization epoch ...");
            var epoch = new OptimizationEpoch(learning, trainingMP, valMP, 1);
            epoch.Initialize();

            epoch.BestValidationResult.Updated += OnBestResultUpdated;

            // Training loop:
            Console.WriteLine("Starting ...");

            bool done = false;
            do
            {
                //CodeBench.By("Epoch").Do = () =>
                //{
                //    epoch.Step();
                //};

                //CodeBench.By("Epoch").WriteToConsole();

                epoch.Step();

                WriteResult(epoch, trainedNet != null);
                if (Console.KeyAvailable)
                {
                    var key = Console.ReadKey();
                    switch (key.Key)
                    {
                        case ConsoleKey.Escape:
                            done = true;
                            break;
                        case ConsoleKey.S:
                            Save(network, trainingMP);
                            break;
                        case ConsoleKey.V:
                            if (trainedNet != null) Save(trainedNet, trainingMP);
                            break;
                    }
                }
            }
            while (!done);
        }
Пример #3
0
        private void InitLearning()
        {
            int v_index = 1;

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name = "Angular (npm, NodeJS, Gulp, etc...)",
                Year = 2017,
                Firm = "(Auto formation)"
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name = "JQuery",
                Year = 2017,
                Firm = "(Auto formation)"
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name = "WPF",
                Year = 2017,
                Firm = "(Auto formation)"
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "Techniques avancées en C#",
                Description = "NuGet, Tests, Generics, TPL, Async/Await, Dependency Injection, LinQ, Extension Methods, JSON / REST, PowerShell, Transaction Scope…",
                Year        = 2016,
                Firm        = "(Interne)",
                DayLength   = 12
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "Introduction au Cloud Azure",
                Description = "Service Fabric, Document DB",
                Year        = 2016,
                Firm        = "(Interne)",
                DayLength   = 2
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name      = "Oracle, optimisation d'applications",
                Year      = 2015,
                Firm      = "ORSYS",
                DayLength = 4
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "SCRUM",
                Description = "Utiliser efficacement la méthode SCRUM",
                Year        = 2015,
                Firm        = "Cegos",
                DayLength   = 5
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "C# 5.0 / VS 2012",
                Description = "Mise en oeuvre des nouveautés",
                Year        = 2014,
                Firm        = "ORSYS",
                DayLength   = 5
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name      = "Test Driven Development en .NET",
                Year      = 2014,
                Firm      = "ORSYS",
                DayLength = 3
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "Optimisation SQL Server",
                Description = "Développement de base de données SQL Server hautement performantes",
                Year        = 2013,
                Firm        = "Learning Tree",
                DayLength   = 4
            });

            Learning.Add(v_index++, new LearningResumeElement
            {
                Name        = "ASP.NET",
                Description = "Creation d’applications Web",
                Year        = 2013,
                Firm        = "Learning Tree",
                DayLength   = 4
            });
        }
Пример #4
0
 protected override void InitializeLearningAlgorithms(BufferAllocator allocator, Learning.LearningLayerGroups learningLayerGroups, NNInitParameters initPars)
 {
 }
Пример #5
0
 public NeuralComputation(Learning learning, object featuredObject = null)
     : this(learning.Network, learning.NumberOfIterations, featuredObject)
 {
     Contract.Requires(learning != null);
 }
Пример #6
0
 static void Main()
 {
     Learning <Student> l1 = new Learning <Student>();
     //Learning<Dog> l2 = new Learning<Dog>();
     Friend <Emp, Dog> f1 = new Friend <Emp, Dog>();
 }
Пример #7
0
 public ActionResult Delete(int learningId, int companyId, int userId, string reason)
 {
     return(Learning.Delete(learningId, companyId, userId, reason));
 }
Пример #8
0
 private void refreshDgv()
 {
     this.dgv.DataSource = Learning.getAllLearners();
     DGVHelper.AutoSizeForDGV(dgv);
 }
Пример #9
0
        public async Task TestTeachXor()
        {
            IInputLayer inputLayer  = new InputLayer(() => new InputNode(), 2, new Bias());
            var         innerLayer  = new Layer(() => new Neuron(new Logistic(0.888)), 3, new Bias());
            var         outputLayer = new Layer(new Neuron(new Logistic(0.777)));

            var network = new Network
            {
                InputLayer  = inputLayer,
                OutputLayer = outputLayer
            };

            network.AddInnerLayer(innerLayer);

            foreach (var layer in network.Layers)
            {
                foreach (var node in layer.Nodes)
                {
                    node.OnResultCalculated += (n, v) =>
                    {
                        Debug.WriteLine($"{n}: {v}");

                        return(Task.CompletedTask);
                    };
                }
            }

            var generator = new EachToEachSynapseGenerator(new Random());

            generator.Generate(network, inputLayer, innerLayer);
            generator.Generate(network, innerLayer, outputLayer);

            var samples = new List <ILearningSample>
            {
                new LearningSample(new double[] { 0, 1 }, new double[] { 1 }),
                new LearningSample(new double[] { 1, 0 }, new double[] { 1 }),
                new LearningSample(new double[] { 0, 0 }, new double[] { 0 }),
                new LearningSample(new double[] { 1, 1 }, new double[] { 0 })
            };

            await network.Input(new double[] { 1, 0 });

            var beforeLearning = network.LastCalculatedValue.First();

            var strategy = new BackpropagationStrategy();
            var settings = new LearningSettings
            {
                EpochRepeats        = 10000,
                InitialTheta        = THETA,
                ThetaFactorPerEpoch = epoch => 0.9999,
                ShuffleEveryEpoch   = true
            };
            var learning = new Learning <Network, ILearningSample>(network, strategy, settings);
            await learning.Learn(samples);

            await network.Input(new double[] { 1, 0 });

            var afterLearning = (await network.Output()).First();

            Assert.True(beforeLearning < afterLearning);

            await network.Input(new double[] { 1, 0 });

            var output = (await network.Output()).First();

            Assert.True(Math.Abs(1 - output) < DELTA);

            await network.Input(new double[] { 1, 1 });

            output = (await network.Output()).First();
            Assert.True(Math.Abs(0 - output) < DELTA);

            await network.Input(new double[] { 0, 0 });

            output = (await network.Output()).First();
            Assert.True(Math.Abs(0 - output) < DELTA);

            await network.Input(new double[] { 0, 1 });

            output = (await network.Output()).First();
            Assert.True(Math.Abs(1 - output) < DELTA);
        }
Пример #10
0
 private void FrmLearning_Load(object sender, EventArgs e)
 {
     this.dgv.DataSource = Learning.getAllLearners();
     DGVHelper.AutoSizeForDGV(dgv);
 }
Пример #11
0
 /// <summary>
 /// Dump the current state of SPLConqueror to Files.
 /// </summary>
 /// <param name="pathArray">Array with file paths. Needs 5 paths. Data will be stored in these files.</param>
 /// <param name="mlSettings">Current ML_Settings, to save.</param>
 /// <param name="toSample">Sampling strategies to save.</param>
 /// <param name="toSampleValidation">Validation sampling strategies to save.</param>
 /// <param name="exp">Learning object to save.</param>
 /// <param name="history">Command history to save.</param>
 public static void dump(string[] pathArray, ML_Settings mlSettings, List <SamplingStrategies> toSample, List <SamplingStrategies> toSampleValidation, Learning exp, CommandHistory history)
 {
     if (pathArray.Length >= 6)
     {
         StreamWriter sw = new StreamWriter(pathArray[0]);
         sw.Write(PersistGlobalState.dump());
         sw.Flush();
         sw.Close();
         sw = new StreamWriter(pathArray[1]);
         sw.Write(PersistMLSettings.dump(mlSettings));
         sw.Flush();
         sw.Close();
         sw = new StreamWriter(pathArray[2]);
         sw.Write(PersistSampling.dump(toSample));
         sw.Flush();
         sw.Close();
         sw = new StreamWriter(pathArray[3]);
         sw.Write(PersistSampling.dump(toSampleValidation));
         sw.Flush();
         sw.Close();
         sw = new StreamWriter(pathArray[4]);
         sw.Write(PersistLearning.dump(exp));
         sw.Flush();
         sw.Close();
         sw = new StreamWriter(pathArray[5]);
         sw.Write(PersistCommandHistory.dump(history));
         sw.Flush();
         sw.Close();
     }
     else
     {
         GlobalState.logError.logLine("Couldnt dump the data. Not all target paths are given");
     }
 }
Пример #12
0
        public static void BackTest(string Date, string Weeks)
        {
            ///////////////////////////
            ///
            /// Setting backtest object
            ///
            //////////////////////////

            Backtest Mybacktest     = new Backtest();
            Backtest Mybacktest_adj = new Backtest();

            // Initial the two backtest

            Mybacktest.Init();
            Mybacktest_adj.Init();

            ///////////////////////////
            ///
            /// Setting data container to store the information
            /// outside the for loop
            ///
            ///////////////////////////

            // setting netvalue lists for both standard strategy and dynamic strategy

            List <double> Hisc_netValue = new List <double>();
            List <double> Adj_netValue  = new List <double>();

            // setting lists to store Fixed Income ETFs and Equity ETFs
            // we are holding during this trading week for the caculation of
            // Turnover Utility function

            List <string> ETFs_holding_FI  = new List <string>();
            List <string> ETFs_holding_Equ = new List <string>();

            // setting matrix to store the trading history during this backtest

            string[][] trading_history_ETF           = new string[Convert.ToInt64(Weeks)][];
            double[][] trading_history_allocation    = new double[Convert.ToInt64(Weeks)][];
            double[][] ADJtrading_history_allocation = new double[Convert.ToInt64(Weeks)][];

            // setting two variable drawdown and position ratio for the caculation
            // in Dynamic strategy, position ratio means the percentage of Fixed Income
            // ETFs we are currently holding

            double DrawDown       = 0;
            double Position_ratio = 0.2;

            int FI_holding_weeks  = 0;
            int Equ_holding_weeks = 0;

            double[] FI_holding_allocation  = new double[5];
            double[] Equ_holding_allocation = new double[5];

            //////////////////////////////////
            ///
            /// For loop backtest
            ///
            /////////////////////////////////


            for (int i = 0; i < Convert.ToInt64(Weeks); i++)
            {
                // seting Datapreprocessing class for both Fixed Income ETFs and Equity ETFs

                DataPreProcessing pro_FI  = new DataPreProcessing();
                DataPreProcessing pro_Equ = new DataPreProcessing();

                // caculate the date of today start from the 'Date'
                // which is given by backtest function

                var Today = DateTime.Parse(Date).AddDays(i * 7);

                // print the date we trained the model and trade

                Console.WriteLine("Date: {0}", Today.ToString());

                // cleaning data use data preprocessing class

                pro_FI.Run(Today.ToString(), 112, "Fixed Income");
                pro_Equ.Run(Today.ToString(), 112, "Equity");

                // Set prediction vector

                double[] predictions_FI  = new double[pro_FI.Trade_ETF.Count];
                double[] predictions_Equ = new double[pro_Equ.Trade_ETF.Count];

                // Set blend ETFs list to store the Top 10 etfs which is going to be
                // longed by the algorithm

                List <string> Blend_ETFs = new List <string>();

                /////////////////////////////
                ///                   ///////
                /// FI ETF prediction ///////
                ///                   ///////
                /////////////////////////////

                for (int j = 0; j < pro_FI.Trade_ETF.Count; j++)
                {
                    // Grab the data from the datapreprocessing object class

                    var y = pro_FI.Target_List[j];
                    var fy = new FrameBuilder.Columns <DateTime, string> {
                        { "Y", y }
                    }.Frame;
                    var data          = pro_FI.Feature_List[j].Join(fy);
                    var pred_Features = pro_FI.pred_Feature_List[j];

                    data.SaveCsv("dataset.csv");

                    // Training machine learning and predict

                    var prediction = Learning.FitGBT(pred_Features);

                    predictions_FI[j] = prediction;
                }

                // Get the minimum scores of top 5 ETF

                var hold_FI = PredRanking(predictions_FI, 5);

                // Get the namelist of top 5 ETF

                List <string> ETFs_FI = new List <string>();

                for (int m = 0; m < pro_FI.Trade_ETF.Count; m++)
                {
                    if (predictions_FI[m] >= hold_FI)
                    {
                        ETFs_FI.Add(pro_FI.Trade_ETF[m]);
                    }
                }


                // Caculate the bid-ask spread cost if trade all 5 ETFs given by algorithm

                double[] FixedIncomeSpread = new double[5];
                FixedIncomeSpread = GetBidAskSpread(ETFs_FI.ToArray());

                // Cacualte the Unitility and decide if we should trade this week

                if (i == 0)
                {
                    ETFs_holding_FI = ETFs_FI;
                }
                else
                {
                    // get all prediction results of both holding etf and etfs which we may be going to trade

                    double[] holding_pred = ETFname2Prediction(ETFs_holding_FI, predictions_FI, pro_FI);
                    double[] long_pred    = ETFname2Prediction(ETFs_FI, predictions_FI, pro_FI);

                    // caculate the trade diff which is the utility of trading this week

                    double trade_diff = long_pred.Sum() -
                                        holding_pred.Sum() -
                                        CaculateRebalanceCost(ETFs_FI,
                                                              ETFs_holding_FI,
                                                              FI_holding_allocation,
                                                              pro_FI);

                    // check if it is worth of trading

                    if (trade_diff < 0)
                    {
                        // It is not worth of trading and ETFs portfolio will be same

                        FI_holding_weeks += 1;
                        ETFs_FI           = ETFs_holding_FI;

                        // setting spread equals to 0 because we are not going to trade this week

                        FixedIncomeSpread = new double[] { 0, 0, 0, 0, 0 };
                    }
                    else
                    {
                        FI_holding_weeks = 0;

                        // It is worth of changing positions and trading this week !

                        // recaculate the spread costs because we may not going to trade all
                        // ETFs which we are holding right now.

                        for (int m = 0; m < 5; m++)
                        {
                            for (int n = 0; n < 5; n++)
                            {
                                if (ETFs_FI[m] == ETFs_holding_FI[n])
                                {
                                    FixedIncomeSpread[m] = 0;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                        // resetting the fixed income ETFs  we are holding

                        ETFs_holding_FI = ETFs_FI;
                    }
                }

                Console.WriteLine("Long the following ETFs: ");

                // Store the Fixed Income ETFs namelist to blend ETFs list

                for (int n = 0; n < ETFs_FI.Count; n++)
                {
                    Console.WriteLine(ETFs_FI[n]);
                    Blend_ETFs.Add(ETFs_FI[n]);
                }

                ///////////////////////////////////
                ///                         ///////
                /// Equity ETF prediction   ///////
                ///                         ///////
                ///////////////////////////////////


                for (int j = 0; j < pro_Equ.Trade_ETF.Count; j++)
                {
                    // Run machine learning and predict next week for all ETFss

                    var y = pro_Equ.Target_List[j];

                    var fy = new FrameBuilder.Columns <DateTime, string> {
                        { "Y", y }
                    }.Frame;
                    var data          = pro_Equ.Feature_List[j].Join(fy);
                    var pred_Features = pro_Equ.pred_Feature_List[j];

                    data.SaveCsv("dataset.csv");

                    var prediction = Learning.FitGBT(pred_Features);

                    predictions_Equ[j] = prediction;
                }


                List <string> ETFs_Equ = new List <string>();

                // Find the min score of top 5 best ETFs

                var hold_Equ = PredRanking(predictions_Equ, 5);

                for (int m = 0; m < pro_Equ.Trade_ETF.Count; m++)
                {
                    if (predictions_Equ[m] >= hold_Equ)
                    {
                        ETFs_Equ.Add(pro_Equ.Trade_ETF[m]);
                    }
                }

                // caculate the bidAsk Spread

                double[] EquityBASpread = new double[5];
                EquityBASpread = GetBidAskSpread(ETFs_Equ.ToArray());

                if (i == 0)
                {
                    ETFs_holding_Equ = ETFs_Equ;
                }
                else
                {
                    double[] holding_pred = ETFname2Prediction(ETFs_holding_Equ, predictions_Equ, pro_Equ);
                    double[] long_pred    = ETFname2Prediction(ETFs_Equ, predictions_Equ, pro_Equ);

                    // Caculate the Utility

                    double trade_diff = long_pred.Sum() -
                                        holding_pred.Sum() -
                                        CaculateRebalanceCost(ETFs_Equ,
                                                              ETFs_holding_Equ,
                                                              Equ_holding_allocation,
                                                              pro_Equ);

                    // check if it is worth of trading this week

                    if (trade_diff < 0)
                    {
                        Equ_holding_weeks += 1;
                        ETFs_Equ           = ETFs_holding_Equ;
                        EquityBASpread     = new double[] { 0, 0, 0, 0, 0 };
                    }
                    else
                    {
                        // Recacluate the spread costs

                        Equ_holding_weeks = 0;

                        for (int m = 0; m < 5; m++)
                        {
                            for (int n = 0; n < 5; n++)
                            {
                                if (ETFs_Equ[m] == ETFs_holding_Equ[n])
                                {
                                    EquityBASpread[m] = 0;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                        ETFs_holding_Equ = ETFs_Equ;
                    }
                }

                // Store the Equity ETFs we are going to long in Blend ETFs list

                for (int n = 0; n < ETFs_Equ.Count; n++)
                {
                    Console.WriteLine(ETFs_Equ[n]);
                    Blend_ETFs.Add(ETFs_Equ[n]);
                }

                //  Caculate optimized allocations for both Fixed income and Equity ETFs

                //////////////////////////////

                Console.WriteLine("Holding weeks for current Fixed Income ETFs is {0}", FI_holding_weeks);
                Console.WriteLine("Holding weeks for current Equity ETFs is {0}", Equ_holding_weeks);

                double[] AllocationFI = new double[5];

                if (FI_holding_weeks == 0)
                {
                    AllocationFI          = PO.ETF2AllocationOwnOptim(ETFs_FI, pro_FI);
                    FI_holding_allocation = AllocationFI;
                }
                else if (FI_holding_weeks < 15)
                {
                    AllocationFI = FI_holding_allocation;
                }
                else
                {
                    FI_holding_weeks      = 0;
                    AllocationFI          = PO.ETF2AllocationOwnOptim(ETFs_FI, pro_FI);
                    FI_holding_allocation = AllocationFI;
                }

                //////////////////////////////

                double[] AllocationEqu = new double[5];

                if (Equ_holding_weeks == 0)
                {
                    AllocationEqu          = PO.ETF2AllocationOwnOptim(ETFs_Equ, pro_Equ);
                    Equ_holding_allocation = AllocationEqu;
                }
                else if (Equ_holding_weeks < 15)
                {
                    AllocationEqu = Equ_holding_allocation;
                }
                else
                {
                    Equ_holding_weeks      = 0;
                    AllocationEqu          = PO.ETF2AllocationOwnOptim(ETFs_Equ, pro_Equ);
                    Equ_holding_allocation = AllocationEqu;
                }

                //////////////////////////////

                // Setting allocations which is an array to store allocations for strandard strategy

                double[] allocations = new double[10];

                for (int fi = 0; fi < 5; fi++)
                {
                    allocations[fi] = AllocationFI[fi] * 0.2;
                }

                for (int equ = 0; equ < 5; equ++)
                {
                    allocations[equ + 5] = AllocationEqu[equ] * 0.8;
                }


                // Setting ALLOCATION which is an array to store allocations for strandard strategy

                double[] ALLOCATION = new double[10];

                for (int fi = 0; fi < 5; fi++)
                {
                    ALLOCATION[fi] = AllocationFI[fi] * Position_ratio;
                }

                for (int equ = 0; equ < 5; equ++)
                {
                    ALLOCATION[equ + 5] = AllocationEqu[equ] * (1 - Position_ratio);
                }

                //  Transform ETFs list to an array

                string[] ETFs = new string[10];

                for (int etf = 0; etf < 10; etf++)
                {
                    ETFs[etf] = Blend_ETFs[etf];
                }

                // Storing the ETFs trading history and allocations

                trading_history_ETF[i] = new string[10];
                trading_history_ETF[i] = ETFs;

                trading_history_allocation[i] = new double[10];
                trading_history_allocation[i] = allocations;

                ADJtrading_history_allocation[i] = new double[10];
                ADJtrading_history_allocation[i] = ALLOCATION;

                // Get the spread array for all ETFs

                double[] spread = new double[10];

                Array.Copy(FixedIncomeSpread, spread, FixedIncomeSpread.Length);
                Array.Copy(EquityBASpread, 0, spread, FixedIncomeSpread.Length, EquityBASpread.Length);

                // Caculate the weighted spread for the adjustment in netvalue

                double weighted_spread = 0;

                for (int spreadItem = 0; spreadItem < 10; spreadItem++)
                {
                    weighted_spread += allocations[spreadItem] * spread[spreadItem];
                }

                // clearing the NetValue

                Hisc_netValue.Add(Mybacktest.Rebalance(Today, ETFs, allocations) * (1 - weighted_spread));
                Adj_netValue.Add(Mybacktest_adj.Rebalance(Today, ETFs, ALLOCATION) * (1 - weighted_spread));

                // Caculate the current drawdown and adjust the position ratio which is
                //  the percentage for the fixed income ETFs

                if (i == 0)
                {
                    DrawDown = 0;
                }
                else
                {
                    DrawDown = 1 - Hisc_netValue.Last() / Hisc_netValue.Max();
                }

                // Adjust the position ratio

                if (DrawDown > 0.1)
                {
                    Position_ratio = 0.8;
                }
                else if (DrawDown > 0.08)
                {
                    Position_ratio = 0.6;
                }
                else if (DrawDown > 0.05)
                {
                    Position_ratio = 0.4;
                }
                else
                {
                    Position_ratio = 0.2;
                }

                // Print out the current drawdown and position ratio.

                Console.WriteLine("Current drawdown is: {0}", DrawDown);
                Console.WriteLine("Fixed Income has been adjusted to: {0} %", Position_ratio * 100);
            }


            // Result analysis for NetValue

            /////////////////////
            ///
            /// Backtest Metrics of Strandard Strategy
            ///
            ////////////////////


            var StrategyNetValue = Hisc_netValue.ToArray();

            double MaxDD = 0;

            for (int i = 1; i < StrategyNetValue.Length; i++)
            {
                var    MaxNetValue = StrategyNetValue.Take(i).Max();
                double drawdown    = 1 - StrategyNetValue[i] / MaxNetValue;

                if (drawdown > MaxDD)
                {
                    MaxDD = drawdown;
                }
            }

            Console.WriteLine("Maximum drawdown of This Strategy is: {0}", MaxDD);

            var AnnualReturn = Math.Log(StrategyNetValue.Last()) /
                               (Convert.ToDouble(Weeks) / 50);

            Console.WriteLine("Annual Return of This Strategy is: {0}", AnnualReturn);

            var StrategyReturn = NetValue2Return(StrategyNetValue);

            Console.WriteLine("Standard Deviation of This Strategy is: {0}",
                              Statistics.StandardDeviation(StrategyReturn));

            double[] BTmetrics = new double[3];
            BTmetrics[0] = AnnualReturn;
            BTmetrics[1] = MaxDD;
            BTmetrics[2] = Statistics.StandardDeviation(StrategyReturn) * Math.Sqrt(50);

            // Result analysis for AdjNetValue

            /////////////////////
            ///
            /// Backtest Metrics of Dynamic Strategy
            ///
            /////////////////////

            var ADJStrategyNetValue = Adj_netValue.ToArray();

            double ADJMaxDD = 0;

            for (int i = 1; i < ADJStrategyNetValue.Length; i++)
            {
                var    MaxNetValue = ADJStrategyNetValue.Take(i).Max();
                double drawdown    = 1 - ADJStrategyNetValue[i] / MaxNetValue;

                if (drawdown > ADJMaxDD)
                {
                    ADJMaxDD = drawdown;
                }
            }


            Console.WriteLine("Maximum drawdown of ADJ Strategy is: {0}", ADJMaxDD);

            var ADJAnnualReturn = Math.Log(ADJStrategyNetValue.Last()) /
                                  (Convert.ToDouble(Weeks) / 50);

            Console.WriteLine("Annual Return of ADJ Strategy is: {0}", ADJAnnualReturn);

            var ADJStrategyReturn = NetValue2Return(ADJStrategyNetValue);

            Console.WriteLine("Standard Deviation of This Strategy is: {0}",
                              Statistics.StandardDeviation(ADJStrategyReturn));

            double[] ADJBTmetrics = new double[3];
            ADJBTmetrics[0] = ADJAnnualReturn;
            ADJBTmetrics[1] = ADJMaxDD;
            ADJBTmetrics[2] = Statistics.StandardDeviation(ADJStrategyReturn) * Math.Sqrt(50);

            // Output all results to CSV
            // Without position adjustment
            SaveArrayAsCSV_(trading_history_allocation, "StrandardTradingHistoryAllocation.csv");
            SaveArrayAsCSV(BTmetrics, "StandardBacktestMetrics.csv");
            SaveArrayAsCSV(StrategyNetValue, "StandardNet_value.csv");
            // With position adjustmnet
            SaveArrayAsCSV_(ADJtrading_history_allocation, "DynamicTradingHistoryAllocation.csv");
            SaveArrayAsCSV(ADJBTmetrics, "DynamicBacktestMetrics.csv");
            SaveArrayAsCSV(ADJStrategyNetValue, "DynamicNetValue.csv");

            SaveArrayAsCSV_ <string>(trading_history_ETF, "ETFTradingHistoryforALL.csv");

            Console.ReadKey();
        }
Пример #13
0
 /// <summary>
 /// Требуемый метод для поддержки конструктора — не изменяйте 
 /// содержимое этого метода с помощью редактора кода.
 /// </summary>
 private void InitializeComponent()
 {
     this.components = new System.ComponentModel.Container();
     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormToDoList));
     this.panel1 = new System.Windows.Forms.Panel();
     this.buttonExit = new System.Windows.Forms.Button();
     this.buttonMinimize = new System.Windows.Forms.Button();
     this.buttonTargets = new System.Windows.Forms.Button();
     this.buttonIdeas = new System.Windows.Forms.Button();
     this.buttonBooks = new System.Windows.Forms.Button();
     this.buttonLearning = new System.Windows.Forms.Button();
     this.panel2 = new System.Windows.Forms.Panel();
     this.pictureBox1 = new System.Windows.Forms.PictureBox();
     this.label1 = new System.Windows.Forms.Label();
     this.Time = new System.Windows.Forms.Label();
     this.Date = new System.Windows.Forms.Label();
     this.timer1 = new System.Windows.Forms.Timer(this.components);
     this.pictureBox2 = new System.Windows.Forms.PictureBox();
     this.panel3 = new System.Windows.Forms.Panel();
     this.button1 = new System.Windows.Forms.Button();
     this.learning1 = new ToDoList.Learning();
     this.books1 = new ToDoList.Books();
     this.targets1 = new ToDoList.Targets();
     this.ideas1 = new ToDoList.Ideas();
     this.panel1.SuspendLayout();
     this.panel2.SuspendLayout();
     ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
     ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
     this.SuspendLayout();
     //
     // panel1
     //
     resources.ApplyResources(this.panel1, "panel1");
     this.panel1.BackColor = System.Drawing.Color.LightSeaGreen;
     this.panel1.Controls.Add(this.buttonExit);
     this.panel1.Controls.Add(this.buttonMinimize);
     this.panel1.Controls.Add(this.buttonTargets);
     this.panel1.Controls.Add(this.buttonIdeas);
     this.panel1.Controls.Add(this.buttonBooks);
     this.panel1.Controls.Add(this.buttonLearning);
     this.panel1.Controls.Add(this.panel2);
     this.panel1.Name = "panel1";
     //
     // buttonExit
     //
     resources.ApplyResources(this.buttonExit, "buttonExit");
     this.buttonExit.BackColor = System.Drawing.Color.Teal;
     this.buttonExit.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonExit.ForeColor = System.Drawing.Color.White;
     this.buttonExit.Name = "buttonExit";
     this.buttonExit.UseVisualStyleBackColor = false;
     this.buttonExit.Click += new System.EventHandler(this.button6_Click);
     //
     // buttonMinimize
     //
     resources.ApplyResources(this.buttonMinimize, "buttonMinimize");
     this.buttonMinimize.BackColor = System.Drawing.Color.Teal;
     this.buttonMinimize.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonMinimize.ForeColor = System.Drawing.Color.White;
     this.buttonMinimize.Name = "buttonMinimize";
     this.buttonMinimize.UseVisualStyleBackColor = false;
     this.buttonMinimize.Click += new System.EventHandler(this.button5_Click);
     //
     // buttonTargets
     //
     resources.ApplyResources(this.buttonTargets, "buttonTargets");
     this.buttonTargets.BackColor = System.Drawing.Color.Teal;
     this.buttonTargets.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonTargets.ForeColor = System.Drawing.Color.White;
     this.buttonTargets.Name = "buttonTargets";
     this.buttonTargets.UseVisualStyleBackColor = false;
     this.buttonTargets.Click += new System.EventHandler(this.buttonTargets_Click);
     //
     // buttonIdeas
     //
     resources.ApplyResources(this.buttonIdeas, "buttonIdeas");
     this.buttonIdeas.BackColor = System.Drawing.Color.Teal;
     this.buttonIdeas.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonIdeas.ForeColor = System.Drawing.Color.White;
     this.buttonIdeas.Name = "buttonIdeas";
     this.buttonIdeas.UseVisualStyleBackColor = false;
     this.buttonIdeas.Click += new System.EventHandler(this.buttonIdeas_Click);
     //
     // buttonBooks
     //
     resources.ApplyResources(this.buttonBooks, "buttonBooks");
     this.buttonBooks.BackColor = System.Drawing.Color.Teal;
     this.buttonBooks.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonBooks.ForeColor = System.Drawing.Color.White;
     this.buttonBooks.Name = "buttonBooks";
     this.buttonBooks.UseVisualStyleBackColor = false;
     this.buttonBooks.Click += new System.EventHandler(this.buttonBooks_Click);
     //
     // buttonLearning
     //
     resources.ApplyResources(this.buttonLearning, "buttonLearning");
     this.buttonLearning.BackColor = System.Drawing.Color.Teal;
     this.buttonLearning.FlatAppearance.BorderColor = System.Drawing.Color.Teal;
     this.buttonLearning.ForeColor = System.Drawing.Color.White;
     this.buttonLearning.Name = "buttonLearning";
     this.buttonLearning.UseVisualStyleBackColor = false;
     this.buttonLearning.Click += new System.EventHandler(this.buttonLearning_Click);
     //
     // panel2
     //
     resources.ApplyResources(this.panel2, "panel2");
     this.panel2.Controls.Add(this.pictureBox1);
     this.panel2.Controls.Add(this.label1);
     this.panel2.Name = "panel2";
     //
     // pictureBox1
     //
     resources.ApplyResources(this.pictureBox1, "pictureBox1");
     this.pictureBox1.Name = "pictureBox1";
     this.pictureBox1.TabStop = false;
     //
     // label1
     //
     resources.ApplyResources(this.label1, "label1");
     this.label1.ForeColor = System.Drawing.SystemColors.ButtonFace;
     this.label1.Name = "label1";
     //
     // Time
     //
     resources.ApplyResources(this.Time, "Time");
     this.Time.ForeColor = System.Drawing.Color.Teal;
     this.Time.Name = "Time";
     //
     // Date
     //
     resources.ApplyResources(this.Date, "Date");
     this.Date.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.Date.ForeColor = System.Drawing.Color.Teal;
     this.Date.Name = "Date";
     //
     // timer1
     //
     this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
     //
     // pictureBox2
     //
     resources.ApplyResources(this.pictureBox2, "pictureBox2");
     this.pictureBox2.Name = "pictureBox2";
     this.pictureBox2.TabStop = false;
     //
     // panel3
     //
     resources.ApplyResources(this.panel3, "panel3");
     this.panel3.BackColor = System.Drawing.Color.Teal;
     this.panel3.Name = "panel3";
     //
     // button1
     //
     resources.ApplyResources(this.button1, "button1");
     this.button1.BackColor = System.Drawing.Color.DimGray;
     this.button1.ForeColor = System.Drawing.Color.LightGray;
     this.button1.Name = "button1";
     this.button1.UseVisualStyleBackColor = false;
     this.button1.Click += new System.EventHandler(this.button1_Click);
     //
     // learning1
     //
     resources.ApplyResources(this.learning1, "learning1");
     this.learning1.Name = "learning1";
     //
     // books1
     //
     resources.ApplyResources(this.books1, "books1");
     this.books1.Name = "books1";
     //
     // targets1
     //
     resources.ApplyResources(this.targets1, "targets1");
     this.targets1.Name = "targets1";
     //
     // ideas1
     //
     resources.ApplyResources(this.ideas1, "ideas1");
     this.ideas1.Name = "ideas1";
     //
     // FormToDoList
     //
     resources.ApplyResources(this, "$this");
     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     this.BackColor = System.Drawing.Color.Honeydew;
     this.Controls.Add(this.Time);
     this.Controls.Add(this.button1);
     this.Controls.Add(this.panel3);
     this.Controls.Add(this.pictureBox2);
     this.Controls.Add(this.Date);
     this.Controls.Add(this.panel1);
     this.Controls.Add(this.learning1);
     this.Controls.Add(this.books1);
     this.Controls.Add(this.targets1);
     this.Controls.Add(this.ideas1);
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.Name = "FormToDoList";
     this.Load += new System.EventHandler(this.FormToDoList_Load);
     this.panel1.ResumeLayout(false);
     this.panel2.ResumeLayout(false);
     this.panel2.PerformLayout();
     ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
     ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Пример #14
0
    /// <summary>Begin page running after session validations</summary>
    private void Go()
    {
        this.user       = Session["User"] as ApplicationUser;
        this.company    = Session["company"] as Company;
        this.dictionary = Session["Dictionary"] as Dictionary <string, string>;
        this.formFooter = new FormFooter();
        this.formFooter.AddButton(new UIButton {
            Id = "BtnPrint", Icon = "icon-file-pdf", Text = this.dictionary["Common_PrintPdf"], Action = "success", ColumnsSpan = 12
        });
        this.formFooter.AddButton(new UIButton {
            Id = "BtnSave", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success"
        });
        this.formFooter.AddButton(new UIButton {
            Id = "BtnCancel", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
        });

        if (this.Request.QueryString["id"] != null)
        {
            this.learningId = Convert.ToInt32(this.Request.QueryString["id"]);
        }

        if (this.learningId != -1)
        {
            this.learning = new Learning(this.learningId, this.company.Id);
            if (this.learning.CompanyId != this.company.Id)
            {
                this.Response.Redirect("NoAccesible.aspx", Constant.EndResponse);
                Context.ApplicationInstance.CompleteRequest();
                this.learning = Learning.Empty;
            }

            this.formFooter.ModifiedBy = this.learning.ModifiedBy.Description;
            this.formFooter.ModifiedOn = this.learning.ModifiedOn;

            this.learning.ObtainAssistance();
            this.RenderDocuments();
        }
        else
        {
            this.learning = Learning.Empty;
        }

        string label = string.Format(CultureInfo.InvariantCulture, "{0}: <strong>{1}</strong>", this.dictionary["Item_Learning"], this.learning.Description);

        if (this.learningId == -1)
        {
            label = "Item_Learning_NewLabel";
        }

        this.master = this.Master as Giso;
        this.master.TitleInvariant = this.learningId != -1;
        string serverPath = this.Request.Url.AbsoluteUri.Replace(this.Request.RawUrl.Substring(1), string.Empty);

        this.master.AddBreadCrumb("Item_Learnings", "FormacionList.aspx", Constant.NotLeaft);
        this.master.AddBreadCrumb("Item_Learning_NewLabel");
        this.master.Titulo = label;

        var tableAssistance = new StringBuilder();

        jsonAssistance = new StringBuilder("[");
        this.assistans = new StringBuilder();
        bool first = true;

        foreach (var assistance in this.learning.Assistance)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                jsonAssistance.Append(",");
                this.assistans.Append(",");
            }

            tableAssistance.Append(assistance.LearningRow(this.dictionary, this.learning.Status));
            jsonAssistance.Append(string.Format(@"{{""EmployeeId"":{0},""AssistantId"":{1}}}", assistance.Employee.Id, assistance.Id));
            this.assistans.Append(assistance.Id);
        }

        jsonAssistance.Append("]");
        this.TableAssistance.Text = tableAssistance.ToString();

        this.LtTrazas.Text = ActivityTrace.RenderTraceTableForItem(this.learningId, TargetType.Learning);

        this.LtYearPrevistos.Text = string.Format(CultureInfo.InvariantCulture, @"<option value="""">{0}</option>", this.dictionary["Common_Year"]);

        for (int x = DateTime.Now.Year; x < DateTime.Now.Year + 3; x++)
        {
            string selected = string.Empty;
            if (this.learning.Id > 0)
            {
                if (this.learning.DateEstimated.Year == x)
                {
                    selected = " selected=\"selected\"";
                }
            }

            this.LtYearPrevistos.Text += string.Format(@"<option value=""{0}""{1}>{0}</option>", x, selected);
        }
    }