public static void SaveGraph(System.Windows.Forms.DataVisualization.Charting.Chart ChartControl) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "JPEG Image FIle (*.jpeg)|*.jpeg|PNG Image FIle (*.png)|*.png|GIF Image FIle (*.gif)|*.gif"; saveDialog.FilterIndex = 1; if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (saveDialog.FilterIndex == 1) { ChartControl.SaveImage(saveDialog.FileName, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Jpeg); } if (saveDialog.FilterIndex == 2) { ChartControl.SaveImage(saveDialog.FileName, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png); } if (saveDialog.FilterIndex == 3) { ChartControl.SaveImage(saveDialog.FileName, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Gif); } } }
private string GeneratePlot(List <double[]> data, string title) { string file = ""; chart = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart.ChartAreas.Add(new System.Windows.Forms.DataVisualization.Charting.ChartArea()); foreach (var items in data) { int i = 1; foreach (var item in items) { SetChart(title, i, item); i++; } } DateTime d = DateTime.Now; var xxx = String.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond); String chartFilename = ApplicationFolder + "\\" + xxx + ".bmp"; chart.Update(); chart.SaveImage(chartFilename, System.Drawing.Imaging.ImageFormat.Bmp); file = chartFilename; return(file); }
private void PrintChartToFile(List <Tuple <int, long> > executions) { var chart = new System.Windows.Forms.DataVisualization.Charting.Chart { Size = new System.Drawing.Size(640, 320) }; chart.ChartAreas.Add("ChartArea"); chart.Legends.Add("legend"); chart.Series.Add("executions"); chart.Series.Add("compare"); chart.Series["executions"].LegendText = "Clock cycles"; chart.Series["executions"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; chart.Series["compare"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; chart.Series["compare"].BorderWidth = 3; chart.Series["compare"].LegendText = "n^2 log(n)"; foreach (var execution in executions) { chart.Series["executions"].Points.AddXY(execution.Item1, execution.Item2); chart.Series["compare"].Points.AddXY(execution.Item1, _compareFunction(execution.Item1)); } chart.SaveImage(@"..\..\TestFiles\ExecutionTimeChart.png", System.Drawing.Imaging.ImageFormat.Png); }
//显示光谱图形 private void ShowSpectrumGraphic(Border rootBorder, string graphicBorderName, string graphicFile, double graphicWidth, double graphicHeight = double.MaxValue, double DPI = double.MaxValue) { Border graphicBorder = rootBorder.FindName(graphicBorderName) as Border; if (graphicBorder != null) { System.Windows.Forms.DataVisualization.Charting.Chart graphicChart = new System.Windows.Forms.DataVisualization.Charting.Chart(); System.Windows.Forms.DataVisualization.Charting.ChartArea ca = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); graphicChart.ChartAreas.Add(ca); Common.CommonMethod.DrawSpectrumGraphic(graphicChart, ca, graphicFile, System.Drawing.Color.Black); DPI = (DPI == double.MaxValue) ? 96: DPI; graphicHeight = (graphicHeight == double.MaxValue) ? graphicBorder.Height * DPI / 96 : graphicHeight * DPI / 2.54; graphicChart.Width = (int)(graphicWidth * DPI / 2.54); //1cm = 2.54inch = 96dpi graphicChart.Height = (int)(graphicHeight); System.IO.MemoryStream stream = new MemoryStream(); graphicChart.SaveImage(stream, System.Drawing.Imaging.ImageFormat.Png); var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = stream; bitmapImage.EndInit(); Image img = new Image(); graphicBorder.Child = img; img.Source = bitmapImage; img.Stretch = Stretch.Uniform; } }
public static void ChartToPNG(System.Windows.Forms.DataVisualization.Charting.Chart chart) { string filename; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "Portable Network Graphic (*.png)|*.png"; try { saveDialog.InitialDirectory = Properties.Settings.Default.lastFolder; } catch { saveDialog.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString(); } if (saveDialog.ShowDialog() != DialogResult.OK) { return; } filename = saveDialog.FileName; try { chart.SaveImage(filename, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png); } catch (Exception e) { Log.Error("Could not save image file: " + e.ToString()); MessageBox.Show("An error occoured while trying to export chart."); } }
public void addChart2(string bookmark, string chartType, string[][] data) { CHART c = ChartCreator.createChart(chartType, data); string img = Path.GetFullPath(DateTime.Now.Ticks + ".bmp"); c.SaveImage(img, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Bmp); replaceImage(bookmark, img); try { File.Delete(img); } catch (Exception) { } }
public static Image ToImage(this Control ctrl) { if (ctrl is System.Windows.Forms.DataVisualization.Charting.Chart) { System.Windows.Forms.DataVisualization.Charting.Chart chart = ctrl as System.Windows.Forms.DataVisualization.Charting.Chart; MemoryStream ms = new MemoryStream(); chart.SaveImage(ms, ImageFormat.Bmp); Bitmap bmp1 = new Bitmap(ms); return(bmp1); } Bitmap bmp = new Bitmap(ctrl.Width, ctrl.Height); ctrl.DrawToBitmap(bmp, ctrl.ClientRectangle); return(bmp); }
private int CopyMSChart(System.Windows.Forms.DataVisualization.Charting.Chart oMSChart, int iChartRow) { //MS Chart 사용 로직 추가 string sImageFileName = null; int iRowCnt = 0; double dRowHeight = 0; double dPicHeight = 0; Excel.Pictures oPic; sImageFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + @"\Tmp_Chart" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".bmp"; //oChartFx.Export(SoftwareFX.ChartFX.FileFormat.Bitmap, sImageFileName); oMSChart.SaveImage(sImageFileName, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Bmp); xlSheet.get_Range(xlSheet.Cells[iChartRow, 1], xlSheet.Cells[iChartRow, 1]).Select(); oPic = (Excel.Pictures)xlSheet.Pictures(Missing.Value); oPic.Insert(sImageFileName, Missing.Value).Select(true); dPicHeight = oPic.Insert(sImageFileName, Missing.Value).Height; //Row의 폭 dRowHeight = Convert.ToDouble(xlSheet.get_Range(xlSheet.Cells[iChartRow, 1], xlSheet.Cells[iChartRow, 1]).Height); //그림의 폭 iRowCnt = Convert.ToInt16((dPicHeight / dRowHeight)) + 2; System.IO.File.Delete(sImageFileName); return(iChartRow + iRowCnt); }
private void save_as_png(System.Windows.Forms.DataVisualization.Charting.Chart ct, string folder, string prefix, string timestamp) { ct.SaveImage(Path.Combine(folder, prefix + timestamp + ".png"), System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png); }
void chartGraphConstruction(int Id1T, int Id2T, bool sum) { string Series1Name = NameIndex.IndexParse(Id1T); string Series2Name = ""; if (!sum) { Series2Name = NameIndex.IndexParse(Id2T); } else if (sum) { Series2Name = "总计"; } Font Title1Font = new Font("微软雅黑", 15); // 表格真初始化 System.Windows.Forms.DataVisualization.Charting.Chart chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart1.Size = new System.Drawing.Size(640, 320); chart1.ChartAreas.Add("ChartArea1"); chart1.Legends.Add("Legend1"); System.Windows.Forms.DataVisualization.Charting.Chart chart2 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart2.Size = new System.Drawing.Size(640, 320); chart2.ChartAreas.Add("ChartArea1"); chart2.Legends.Add("Legend1"); System.Windows.Forms.DataVisualization.Charting.Chart chart3 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart3.Size = new System.Drawing.Size(640, 320); chart3.ChartAreas.Add("ChartArea1"); chart3.Legends.Add("Legend1"); System.Windows.Forms.DataVisualization.Charting.Chart chart4 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart4.Size = new System.Drawing.Size(640, 320); chart4.ChartAreas.Add("ChartArea1"); chart4.Legends.Add("Legend1"); System.Windows.Forms.DataVisualization.Charting.Chart chart5 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart5.Size = new System.Drawing.Size(640, 320); chart5.ChartAreas.Add("ChartArea1"); chart5.Legends.Add("Legend1"); System.Windows.Forms.DataVisualization.Charting.Chart chart6 = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart6.Size = new System.Drawing.Size(640, 320); chart6.ChartAreas.Add("ChartArea1"); chart6.Legends.Add("Legend1"); #region 表格初始化 //击杀总量表 chart3.Series.Add(Series1Name); chart3.Series.Add(Series2Name); chart3.Legends["Legend1"].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; chart3.Titles.Add("Title1"); chart3.Titles["Title1"].Text = "全等级击杀量对比"; chart3.Titles["Title1"].Font = Title1Font; chart3.ChartAreas["ChartArea1"].AxisX.Title = "等级"; chart3.ChartAreas["ChartArea1"].AxisY.Title = "击杀量"; //单挑表 chart1.Series.Add("单挑流行度"); chart1.Series.Add("单挑胜率"); chart1.Series["单挑胜率"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; chart1.Series["单挑流行度"].YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary; chart1.Series["单挑胜率"].BorderWidth = 5; chart1.Series["单挑胜率"].Color = Color.DodgerBlue; chart1.Series["单挑流行度"].Color = Color.Orange; chart1.Legends["Legend1"].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; chart1.Titles.Add("Title1"); chart1.Titles["Title1"].Text = "全等级单挑分析"; chart1.Titles["Title1"].Font = Title1Font; chart1.ChartAreas["ChartArea1"].AxisX.Title = "等级"; chart1.ChartAreas["ChartArea1"].AxisY.Title = "胜率百分比"; chart1.ChartAreas["ChartArea1"].AxisY2.Title = "流行度百分比"; chart1.ChartAreas["ChartArea1"].AxisY2.MajorGrid.Enabled = false; chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 1.0; //GANK表 chart2.Series.Add("GANK流行度"); chart2.Series.Add("GANK胜率"); chart2.Series["GANK胜率"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; chart2.Series["GANK流行度"].YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary; chart2.Series["GANK胜率"].BorderWidth = 5; chart2.Series["GANK胜率"].Color = Color.DodgerBlue; chart2.Series["GANK流行度"].Color = Color.Orange; chart2.Legends["Legend1"].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; chart2.Titles.Add("Title1"); chart2.Titles["Title1"].Text = "全等级GANK分析"; chart2.Titles["Title1"].Font = Title1Font; chart2.ChartAreas["ChartArea1"].AxisX.Title = "等级"; chart2.ChartAreas["ChartArea1"].AxisY.Title = "胜率百分比"; chart2.ChartAreas["ChartArea1"].AxisY2.Title = "流行度百分比"; chart2.ChartAreas["ChartArea1"].AxisY2.MajorGrid.Enabled = false; chart2.ChartAreas["ChartArea1"].AxisY.Maximum = 1.0; //死亡表 chart4.Series.Add(Series1Name); chart4.Series.Add(Series2Name); chart4.Legends["Legend1"].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; chart4.Titles.Add("Title1"); chart4.Titles["Title1"].Text = "全等级死亡量对比"; chart4.Titles["Title1"].Font = Title1Font; chart4.ChartAreas["ChartArea1"].AxisX.Title = "等级"; chart4.ChartAreas["ChartArea1"].AxisY.Title = "死亡量"; //KDA表 chart5.Series.Add(Series1Name); chart5.Series.Add(Series2Name); chart5.Legends["Legend1"].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; chart5.Titles.Add("Title1"); chart5.Titles["Title1"].Text = "全等级KDA对比"; chart5.Titles["Title1"].Font = Title1Font; chart5.ChartAreas["ChartArea1"].AxisX.Title = "等级"; chart5.ChartAreas["ChartArea1"].AxisY.Title = "KDA"; #endregion if (!sum) { for (int i = 1; i < 19; i++) { chart1.Series["单挑流行度"].Points.AddXY(i, statChart[i, 1]); chart1.Series["单挑胜率"].Points.AddXY(i, statChart[i, 2]); chart2.Series["GANK流行度"].Points.AddXY(i, statChart[i, 3]); chart2.Series["GANK胜率"].Points.AddXY(i, statChart[i, 4]); chart3.Series[Series1Name].Points.AddXY(i, statChart[i, 5]); chart3.Series[Series2Name].Points.AddXY(i, statChart[i, 6]); chart4.Series[Series1Name].Points.AddXY(i, statChart[i, 7]); chart4.Series[Series2Name].Points.AddXY(i, statChart[i, 8]); chart5.Series[Series1Name].Points.AddXY(i, statChart[i, 9]); chart5.Series[Series2Name].Points.AddXY(i, statChart[i, 10]); } Directory.CreateDirectory(@"E:\lolLaneStat\" + Series1Name); chart1.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "_1.png", System.Drawing.Imaging.ImageFormat.Png); chart2.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "_2.png", System.Drawing.Imaging.ImageFormat.Png); chart3.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "_3.png", System.Drawing.Imaging.ImageFormat.Png); chart4.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "_4.png", System.Drawing.Imaging.ImageFormat.Png); chart5.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "_5.png", System.Drawing.Imaging.ImageFormat.Png); } if (sum) { for (int i = 1; i < 19; i++) { chart1.Series["单挑流行度"].Points.AddXY(i, statSumChart[i, 1]); chart1.Series["单挑胜率"].Points.AddXY(i, statSumChart[i, 2]); chart2.Series["GANK流行度"].Points.AddXY(i, statSumChart[i, 3]); chart2.Series["GANK胜率"].Points.AddXY(i, statSumChart[i, 4]); chart3.Series[Series1Name].Points.AddXY(i, statSumChart[i, 5]); chart3.Series[Series2Name].Points.AddXY(i, statSumChart[i, 6]); chart4.Series[Series1Name].Points.AddXY(i, statSumChart[i, 7]); chart4.Series[Series2Name].Points.AddXY(i, statSumChart[i, 8]); chart5.Series[Series1Name].Points.AddXY(i, statSumChart[i, 9]); chart5.Series[Series2Name].Points.AddXY(i, statSumChart[i, 10]); } Directory.CreateDirectory(@"E:\lolLaneStat\" + Series1Name); chart1.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "1.png", System.Drawing.Imaging.ImageFormat.Png); chart2.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "2.png", System.Drawing.Imaging.ImageFormat.Png); chart3.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "3.png", System.Drawing.Imaging.ImageFormat.Png); chart4.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "4.png", System.Drawing.Imaging.ImageFormat.Png); chart5.SaveImage(@"E:\lolLaneStat\" + Series1Name + @"\" + Series2Name + "5.png", System.Drawing.Imaging.ImageFormat.Png); } chart1.Series.Clear(); chart1.Titles.Clear(); chart2.Series.Clear(); chart2.Titles.Clear(); chart3.Series.Clear(); chart3.Titles.Clear(); chart4.Series.Clear(); chart4.Titles.Clear(); chart5.Series.Clear(); chart5.Titles.Clear(); chart1.Dispose(); chart2.Dispose(); chart3.Dispose(); chart4.Dispose(); chart5.Dispose(); GC.Collect(); }
private void openFileDialog3_FileOk(object sender, CancelEventArgs e) { using (StreamReader sr = new StreamReader(openFileDialog3.FileName)) { bool onlyOneRecord = checkBox1.Checked; int m = 0; int errors = 0; float result = 0; float sumActually = 0; float sumPredicted = 0; double error = 0; while (!sr.EndOfStream) { DenseVector X = new DenseVector(network.GetInputs() - 1); string[] str = sr.ReadLine().Split(separator); for (int j = 0; j < network.GetInputs() - 1; j++) { switch (j) { case 6: if (m != 0) { X[j] = result; } else { X[j] = float.Parse(str[j]); } break; default: X[j] = float.Parse(str[j]); break; } } network.Inputs = X; if (onlyOneRecord) { int dayWeek = (int)Math.Round(1 / X[2]); int month = (int)Math.Round(X[3] * 12); for (int i = 1; i < maxDays; i++) { network.Inputs = X; network.ForwardPropagation(); List <float> results = network.GetAswer(); X[X.Count - 10] = (float)(i) / maxDays; dayWeek++; if (dayWeek > 6) { dayWeek = 1; } if (i % 31 == 0) { month++; } X[X.Count - 9] = (float)(1f / (dayWeek)); if (month > 12) { month = 0; } X[X.Count - 8] = (float)(month) / 12; X[X.Count - 1] = results[0]; sumPredicted += (float)(results[0] * maxBoxOffice); chart1.Series[0].Points.Add((results[0])); } MessageBox.Show("Суммарные предсказанные сборы: " + Math.Round(sumPredicted).ToString()); chart1.SaveImage("Chart.png", System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png); chart1.Series[0].Points.Clear(); return; } network.ForwardPropagation(); List <float> h = network.GetAswer(); float diff = 0; for (int j = 0; j < network.GetOutputs(); j++) { float Y = float.Parse(str[network.GetInputs() - 1 + j]); result = (float)h[j]; diff += (float)Math.Abs(Y - h[j]); sumPredicted += (result * maxBoxOffice); sumActually += (Y * maxBoxOffice); chart1.Series[0].Points.Add((result)); chart1.Series[1].Points.Add((Y)); } error += Math.Pow(diff, 2); if (diff / network.GetOutputs() > allowableError) { errors++; } m++; } float success = (1 - ((float)errors / m)) * 100; double middleError = Math.Sqrt(error / (network.GetOutputs() * m)); chart1.SaveImage("Chart.png", System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png); chart1.Series[0].Points.Clear(); chart1.Series[1].Points.Clear(); MessageBox.Show("Суммарные предсказанные сборы: " + Math.Round(sumPredicted).ToString() + Environment.NewLine + "Суммарные сборы на самом деле: " + Math.Round(sumActually).ToString()); } }
/// Main Code. static void Main(string[] args) { ///Defining variables double[] UnderlyingPrice; double[] CallPrice; Random r = new Random(); ///this is the Class used to generate random variables Discretization disc = new Discretization(); ///class that was coded above used to call the Euler function later in the code System.Windows.Forms.DataVisualization.Charting.Chart chart = new System.Windows.Forms.DataVisualization.Charting.Chart(); ///class to set up Plot of underlying price chart.ChartAreas.Add("ChartArea1"); ///set up the initial plot ///The following lines ask the user for the inputs needed to price the option and run the simulation ///Additionally, the inputs provided by the user are assigned the appropriate variables. Console.WriteLine("Please Enter The Initial Asset Price:"); double X0 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter The Strike Price of the Option:"); double K = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter The Time To Expiration:"); double T = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter mu:"); double mu = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter sigma:"); double sigma = Convert.ToDouble(Console.ReadLine()); /// Console.WriteLine("Please enter The Number of Simulations to Run:"); ///int N = Convert.ToInt32(Console.ReadLine()); int N = 5000; ///Number of simulations int m = 200; ///Number of increments between t = 0 and t = T double delta = T / m; ///size of the increment CallPrice = new double[N]; ///now allocating the size of array based on the number of simulations UnderlyingPrice = new double[m + 1]; //now allocating the size of the array based on the number of increments double U1; ///Represents uniform random variable between 0 and 1 double U2; ///Also represents uniform random variable between 0 and 1 double Z; ///Will represent the Normal Random Variable with mean 0 and variance 1 double sum1 = 0; //variable used to keep track of the sum in order to find the average of all the Call Prices for each of the simulations double sum2 = 0; //variable used to keep track of the sum in order to ultimately find the Standard Error of the simulation double OptionPrice; //Final European Call Option Price calculated double StandardError; //Standard error of the simulation for (int i = 0; i < N; i++) ///Each run through this loop represents 1 simulation { ///Set up a new series that will be plotted on the graph chart.Series.Add(Convert.ToString(i)); ///Set chart type to Line graph chart.Series[Convert.ToString(i)].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; ///Initialize the Underlying Price array based on the input given by the user UnderlyingPrice[0] = X0; ///Plot this initial t = 0 and Underlying price on the graph chart.Series[Convert.ToString(i)].Points.AddXY(0, UnderlyingPrice[0]); for (int j = 0; j < m; j++) ///Each run through this loop represents the next increment closer to t = T { ///Because the Random() Class only allows the creation of uniform random variables between 0 and 1, ///a transform must be done to create a normal random variable with mean 0 and variance 1. ///The transform that was done is called the Box-Muller Transform U1 = r.NextDouble(); ///Get first uniform random variable U2 = r.NextDouble(); ///Get second uniform random variable Z = Math.Sqrt(-2 * Math.Log(U1)) * Math.Cos(2 * Math.PI * U2); ///Box-Muller Transform to generate Z ~ N(0,1) UnderlyingPrice[j + 1] = disc.Euler(UnderlyingPrice[j], mu, sigma, delta, Z); ///Generate the next X value based on the Euler Discretization chart.Series[Convert.ToString(i)].Points.AddXY(delta*(j + 1), UnderlyingPrice[j + 1]); ///Plot the t value as well as X(t) value onto the graph for series i } CallPrice[i] = Math.Max(0, UnderlyingPrice[m] - K); ///Value of the call option. } ///Find the sum of all the Call Prices that were simulated (used for the average) for (int a = 0; a < N; a++ ) { sum1 = sum1 + CallPrice[a]; } //Calculate the average which represents the option price OptionPrice = sum1 / N; ///Same procedure, but to calculate the Standard Error for (int b = 0; b < N; b++) { sum2 = sum2 + Math.Pow((CallPrice[b] - OptionPrice), 2); } ///SE = s / sqrt(N), where s is the sample standard deviation StandardError = Math.Sqrt(sum2 / (N - 1)) / Math.Sqrt(N); ///Print out the required output: Price of the European Call Option and the Standard Error of the simulation Console.WriteLine("The Price of the Option is: " + OptionPrice); Console.WriteLine("The Standard Error of the Simulation is: " + StandardError); ///Save the graph of the Asset Prices for each simulation in a png file that is saved in the same folder as the location of the .exe chart.SaveImage("StockPath.png", System.Drawing.Imaging.ImageFormat.Png); ///The console won't close until the user hits any key another time Console.ReadKey(); }
private string GeneratePlot(List<double[]> data, string title) { string file = ""; chart = new System.Windows.Forms.DataVisualization.Charting.Chart(); chart.ChartAreas.Add(new System.Windows.Forms.DataVisualization.Charting.ChartArea()); foreach (var items in data) { int i = 1; foreach (var item in items) { SetChart(title, i, item); i++; } } DateTime d = DateTime.Now; var xxx = String.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond); String chartFilename = ApplicationFolder + "\\" + xxx + ".bmp"; chart.Update(); chart.SaveImage(chartFilename, System.Drawing.Imaging.ImageFormat.Bmp); file = chartFilename; return file; }
/// Main Code. static void Main(string[] args) { ///Defining variables double[] UnderlyingPrice; double[] CallPrice; Random r = new Random(); ///this is the Class used to generate random variables Discretization disc = new Discretization(); ///class that was coded above used to call the Euler function later in the code System.Windows.Forms.DataVisualization.Charting.Chart chart = new System.Windows.Forms.DataVisualization.Charting.Chart(); ///class to set up Plot of underlying price chart.ChartAreas.Add("ChartArea1"); ///set up the initial plot ///The following lines ask the user for the inputs needed to price the option and run the simulation ///Additionally, the inputs provided by the user are assigned the appropriate variables. Console.WriteLine("Please Enter The Initial Asset Price:"); double X0 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter The Strike Price of the Option:"); double K = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter The Time To Expiration:"); double T = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter mu:"); double mu = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please Enter sigma:"); double sigma = Convert.ToDouble(Console.ReadLine()); /// Console.WriteLine("Please enter The Number of Simulations to Run:"); ///int N = Convert.ToInt32(Console.ReadLine()); int N = 5000; ///Number of simulations int m = 200; ///Number of increments between t = 0 and t = T double delta = T / m; ///size of the increment CallPrice = new double[N]; ///now allocating the size of array based on the number of simulations UnderlyingPrice = new double[m + 1]; //now allocating the size of the array based on the number of increments double U1; ///Represents uniform random variable between 0 and 1 double U2; ///Also represents uniform random variable between 0 and 1 double Z; ///Will represent the Normal Random Variable with mean 0 and variance 1 double sum1 = 0; //variable used to keep track of the sum in order to find the average of all the Call Prices for each of the simulations double sum2 = 0; //variable used to keep track of the sum in order to ultimately find the Standard Error of the simulation double OptionPrice; //Final European Call Option Price calculated double StandardError; //Standard error of the simulation for (int i = 0; i < N; i++) ///Each run through this loop represents 1 simulation { ///Set up a new series that will be plotted on the graph chart.Series.Add(Convert.ToString(i)); ///Set chart type to Line graph chart.Series[Convert.ToString(i)].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; ///Initialize the Underlying Price array based on the input given by the user UnderlyingPrice[0] = X0; ///Plot this initial t = 0 and Underlying price on the graph chart.Series[Convert.ToString(i)].Points.AddXY(0, UnderlyingPrice[0]); for (int j = 0; j < m; j++) ///Each run through this loop represents the next increment closer to t = T { ///Because the Random() Class only allows the creation of uniform random variables between 0 and 1, ///a transform must be done to create a normal random variable with mean 0 and variance 1. ///The transform that was done is called the Box-Muller Transform U1 = r.NextDouble(); ///Get first uniform random variable U2 = r.NextDouble(); ///Get second uniform random variable Z = Math.Sqrt(-2 * Math.Log(U1)) * Math.Cos(2 * Math.PI * U2); ///Box-Muller Transform to generate Z ~ N(0,1) UnderlyingPrice[j + 1] = disc.Euler(UnderlyingPrice[j], mu, sigma, delta, Z); ///Generate the next X value based on the Euler Discretization chart.Series[Convert.ToString(i)].Points.AddXY(delta * (j + 1), UnderlyingPrice[j + 1]); ///Plot the t value as well as X(t) value onto the graph for series i } CallPrice[i] = Math.Max(0, UnderlyingPrice[m] - K); ///Value of the call option. } ///Find the sum of all the Call Prices that were simulated (used for the average) for (int a = 0; a < N; a++) { sum1 = sum1 + CallPrice[a]; } //Calculate the average which represents the option price OptionPrice = sum1 / N; ///Same procedure, but to calculate the Standard Error for (int b = 0; b < N; b++) { sum2 = sum2 + Math.Pow((CallPrice[b] - OptionPrice), 2); } ///SE = s / sqrt(N), where s is the sample standard deviation StandardError = Math.Sqrt(sum2 / (N - 1)) / Math.Sqrt(N); ///Print out the required output: Price of the European Call Option and the Standard Error of the simulation Console.WriteLine("The Price of the Option is: " + OptionPrice); Console.WriteLine("The Standard Error of the Simulation is: " + StandardError); ///Save the graph of the Asset Prices for each simulation in a png file that is saved in the same folder as the location of the .exe chart.SaveImage("StockPath.png", System.Drawing.Imaging.ImageFormat.Png); ///The console won't close until the user hits any key another time Console.ReadKey(); }