venerdì 7 gennaio 2011

ESERCIZI PER L'ESAME DI FABRIZI CLAUDIA

ESERCIZIO 1 - PARSING




L’obiettivo di questo esercizio è quello di fare il parsing dei dati; ossia si sceglie il file da splittare che viene ripulito da eventuali segni di punteggiatura e con il comando split si fa sì che ogni riga o ogni elemento del file diventi un dato.


Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim apri As New OpenFileDialog
        Dim CulturaUSA As System.Globalization.CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-US")
        Dim FileDeiPrezzi As String = ""


        'CERCHIAMO IL FILE DA SPLITTARE

        With apri
            .ShowDialog()
            If .FileName = String.Empty Then
                MsgBox("File Inesistente")
                Exit Sub
            Else
                FileDeiPrezzi = .FileName
            End If
        End With

        Dim DatiNelFile As String = My.Computer.FileSystem.ReadAllText(FileDeiPrezzi)

        'RIPULIAMO I DATI       

        Dim DatiNelFile_N As String = DatiNelFile.ToLower.Replace(",", " ").Replace(vbCrLf, " ").Replace("  ", " ").Replace(".", " ").Replace("!", " ").Replace("?", " ").Replace(")", " ").Replace("(", " ").Replace("-", " ").Replace("'", " ")

        'FACCIAMO IL PARSING DEI DATI

        Dim parsing As String() = DatiNelFile_N.Split((vbCrLf & " ").ToCharArray, StringSplitOptions.RemoveEmptyEntries)

    End Sub

End Class



ESERCIZIO 2 A – IMMAGINI


L’obiettivo di questo esercizio è quello di visualizzare nel form delle immagini che sono già presenti nel pc. Per tale scopo si inserisce nel form una PictureBox che permette di visualizzare  le immagini.  Per adattare l’immagine alla dimensione della PictureBox bisogna andare sulle proprietà di quest’utima e impostare SizeMode= Stretchimage .

Per visualizzare contemporaneamente due immagini è sufficiente aggiungere una nuova PictureBox .
È’  possibile far alternare automaticamente due diverse immagini in due PictureBox.






Public Class Form1
    Public alterna As Boolean

    'definiamo il timer

    Public WithEvents t As New Timer

    'cosi carico 2 immagini e le scambio nelle 2 picturebox

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.PictureBox1.Image = Image.FromFile("F:\ESERCIZI ESAME\animali_5.jpg")
        Me.PictureBox2.Image = Image.FromFile("F:\ESERCIZI ESAME\animali007.jpg")
        With Me.t
            .Interval = 1000 'millisecondi
            .Start()       'avvio timer
        End With
    End Sub

    'evento tick

    Private Sub t_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles t.Tick
       
        'ora spostiamo le immagini

        Me.scmabiaimmagini()
   End Sub


    Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click, PictureBox1.Click

        If Me.t.Enabled Then
            t.Stop()
        Else
            t.Start()
        End If
    End Sub

    Sub scmabiaimmagini()
        Dim img As Image = Me.PictureBox1.Image
        Me.PictureBox1.Image = Me.PictureBox2.Image
        Me.PictureBox2.Image = img

        Me.PictureBox1.Top += 5
        Me.PictureBox1.Left += 5

        Me.PictureBox2.Top -= 5
        Me.PictureBox2.Left -= 5

    End Sub

End Class

ESERCIZIO 2 B – FORME



Nell’esercizio precedente abbiamo utilizzato immagini già presenti nel pc; quello che però realmente ci interessa è creare da soli immagini per poi visualizzarle nella PicturBox.
L’immagine è un oggetto già predefinito dal programma chiamato Bitmap. Quando si definisce un Bitmap dobbiamo definire la sua largezza e la sua altezza.
Nell’esercizio sono state disegnate alcune figure geometriche che si muovono all’interno della PictureBox.



Public Class Form1

    'definisco il timer

    Public WithEvents timer As New Timer
    Public b As Bitmap
    Public g As Graphics

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.b = New Bitmap(500, 300)
        Me.g = Graphics.FromImage(b)

        'qualita grafica

        Me.g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        Me.g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
        Me.g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

        With Me.timer
            .Interval = 500
            .Start()
        End With

    End Sub

    Private Sub timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles timer.Tick
        Me.disegnaframe()
    End Sub

    Dim x1 As Integer = 50
    Dim y1 As Integer = 50
    Dim x2 As Integer = 30
    Dim y2 As Integer = 20
    Dim x3 As Integer
    Dim y3 As Integer
    Dim direzione1 As Integer = 1
    Dim direzione2 As Integer = 1
    Dim direzione3 As Integer = 1


    Sub disegnaframe()
        g.Clear(Color.DarkTurquoise)

        Dim MyRect As New Rectangle(10, 10, 200, 100)
        g.DrawRectangle(Pens.DarkBlue, MyRect)

        Dim MyRect2 As New Rectangle(x1, y1, 200, 100)
        g.FillRectangle(Brushes.DeepPink, MyRect2)

      




        Dim MyRectcerchio As New Rectangle(x2, y2, 50, 50)
        g.FillEllipse(Brushes.DarkOrchid, MyRectcerchio)

        Me.PictureBox1.Image = b

        Dim p1 As New Point(x3, y3)
        Dim p2 As New Point(0, 0)
        Dim p3 As New Point(b.Width, b.Height)

        Dim puntispezzata As New List(Of Point)
        puntispezzata.Add(p1)
        puntispezzata.Add(p2)
        puntispezzata.Add(p3)

        g.DrawLines(New Pen(Color.Crimson, 2), puntispezzata.ToArray)

        If y1 > Me.b.Height - 50 OrElse y1 < 0 Then
            direzione1 = -direzione1
        End If

        If y2 > Me.b.Height - 50 OrElse y2 < 0 Then
            direzione2 = -direzione2
        End If

        If y3 > Me.b.Height - 50 OrElse y3 < 0 Then
            direzione3 = -direzione3
        End If

        x1 += direzione1 * 10
        y1 += direzione1 * 10
        x2 += direzione2 * 10
        y2 += direzione2 * 10
        x3 += direzione3 * 10
        y3 += direzione3 * 10


    End Sub

End Class



ESERCIZIO 3 – SERIE STORICA




L’obiettivo di questo esercizio è quello di rappresentare una serie storica dei prezzi della domanda e dell’offerta delle azioni nel giorno X. Sono state inoltre rappresentate anche le medie mobili.
In generale, per serie si intende la classificazione di diverse osservazioni di un fenomeno rispetto ad un carattere qualitativo. Se tale carattere è il tempo, la serie viene detta storica o temporale.
Per quanto riguarda il tempo i tipi fondamentali  in vb.net sono date ( indica un preciso istante) e timespan (indica un periodo).
Tra i metodi delle date ricordiamo:
·        subtract che permette di sottrarre ad una data un’altra data ottenendo così un timespan;
·        add che prende come argomento un timespan  e restituisce una data.

Il timespan può essere espresso in qualunque unità di misura: giorni, minuti, secondi. Ad esempio il comando    Dim t As New TimeSpan(4, 3, 4)  permette di definire un timespan della durata di 4ore, 3 minuti e 4 secondi.


Public Class Form1

    Private b As Bitmap
    Private g As Graphics

    Private MargineSinistro As Integer = 40
    Private MargineDestro As Integer = 40

    Private MargineAlto As Integer = 40
    Private MargineBasso As Integer = 40

    Private MinimoPrezzo As Decimal
    Private MassimoPrezzo As Decimal



    Private MinimoTempo As Double
    Private MassimoTempo As Double



    Dim FontPrezzi As New Font("Arial", 10, FontStyle.Bold)

    Dim ListaOsservazioni_BID As List(Of Osservazione)
    Dim ListaOsservazioni_ASK As List(Of Osservazione)





    Dim ListaMedieMobili_BID As List(Of Osservazione)
    Dim ListaMedieMobili_ASK As List(Of Osservazione)

    Dim ListaSigmaPositivi As List(Of Osservazione)
    Dim ListaSigmaNegativi As List(Of Osservazione)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        '---------------
        'apriamo il file
        '---------------

        Dim q As New OpenFileDialog

        Dim FileDeiPrezzi As String

        With q
            .ShowDialog()
            If String.IsNullOrEmpty(q.FileName) Then Exit Sub
            Me.RichTextBox1.Text = q.FileName
            My.Computer.FileSystem.ReadAllText(q.FileName)
            Me.RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(q.FileName)


            If .FileName = String.Empty Then Exit Sub
            FileDeiPrezzi = .FileName
        End With

        Dim DatiTxtContenutiInFile As String = My.Computer.FileSystem.ReadAllText(FileDeiPrezzi)

        Dim RigheDelFile As String() = DatiTxtContenutiInFile.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)

        '----------------------------------
        'Ogni riga diventa una osservazione
        '----------------------------------






        Dim CulturaUSA As System.Globalization.CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-US")

        ListaOsservazioni_BID = New List(Of Osservazione)
        ListaOsservazioni_ASK = New List(Of Osservazione)
        ListaMedieMobili_BID = New List(Of Osservazione)




        ListaMedieMobili_ASK = New List(Of Osservazione)
        ListaSigmaPositivi = New List(Of Osservazione)
        ListaSigmaNegativi = New List(Of Osservazione)

        For Each Riga As String In RigheDelFile

            Dim ValoriInUnaRiga As String() = Riga.Split(" ".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
           



            Dim Ora As Integer = CInt(ValoriInUnaRiga(0))
            Dim Minuti As Integer = CInt(ValoriInUnaRiga(1))
            Dim Secondi As Integer = CInt(ValoriInUnaRiga(2))
            Dim Millisecs As Integer = CInt(ValoriInUnaRiga(3))

            Dim oss As New Osservazione

            With oss
                .Istante = New Date(Now.Year, Now.Month, Now.Day, Ora, Minuti, Secondi, Millisecs)
                .TipoPrezzo = CInt(ValoriInUnaRiga(4))
                .Prezzo = Decimal.Parse(ValoriInUnaRiga(5), CulturaUSA)

                If .TipoPrezzo = 1 Then
                    ListaOsservazioni_BID.Add(oss)
                ElseIf .TipoPrezzo = 2 Then
                    ListaOsservazioni_ASK.Add(oss)
                End If
            End With

        Next Riga

       

        '------------------------
        'Media mobili prezzi ASK
        '------------------------

        For i As Integer = k + 1 To ListaOsservazioni_ASK.Count - k - 2
            Dim mASK As Double = Me.MediaMobile(ListaOsservazioni_ASK, i)
            Dim sASK As Double = Me.sigma(ListaOsservazioni_ASK, i)





            Dim oASK As New Osservazione
            Dim s1ASK As New Osservazione
            Dim s2ASK As New Osservazione

            With oASK
                .Prezzo = mASK
                .Istante = ListaOsservazioni_ASK(i).Istante
            End With

            ListaMedieMobili_ASK.Add(oASK)





            With s1ASK
                .Prezzo = mASK + 2 * sASK
                .Istante = ListaOsservazioni_ASK(i).Istante
            End With

            ListaSigmaPositivi.Add(s1ASK)

            With s2ASK
                .Prezzo = mASK - 2 * sASK
                .Istante = ListaOsservazioni_ASK(i).Istante
            End With

            ListaSigmaNegativi.Add(s2ASK)

        Next

        '-----------------------
        'Media mobile prezzi BID
        '-----------------------

        For j As Integer = k + 1 To ListaOsservazioni_BID.Count - k - 2
            Dim mBID As Double = Me.MediaMobile(ListaOsservazioni_BID, j)
            Dim sBID As Double = Me.sigma(ListaOsservazioni_BID, j)
            Dim oBID As New Osservazione
            Dim s1BID As New Osservazione
            Dim s2BID As New Osservazione

            With oBID
                .Prezzo = mBID
                .Istante = ListaOsservazioni_BID(j).Istante
            End With

            ListaMedieMobili_BID.Add(oBID)

            With s1BID
                .Prezzo = mBID + 2 * sBID
                .Istante = ListaOsservazioni_BID(j).Istante
            End With





            ListaSigmaPositivi.Add(s1BID)

            With s2BID
                .Prezzo = mBID - 2 * sBID
                .Istante = ListaOsservazioni_BID(j).Istante
            End With

            ListaSigmaNegativi.Add(s2BID)

        Next

        Me.DisegnaGRafico()

    End Sub





    Sub DisegnaGRafico()

        If Me.ListaOsservazioni_ASK Is Nothing Then Exit Sub

        b = New Bitmap(Me.PictureBox1.Width, Me.PictureBox1.Height)
        g = Graphics.FromImage(b)

        '--------------------------------------------------------------------------------------------
        ' Adesso le 2 liste osservazioni diventano delle liste di punti da rappresentare su un bitmap
        '--------------------------------------------------------------------------------------------




        Dim ListaDiPunti_BID As List(Of Point) = Me.CreaListaPuntiDaListaOsservazioni(ListaOsservazioni_BID)
        Dim ListaDiPunti_ASK As List(Of Point) = Me.CreaListaPuntiDaListaOsservazioni(ListaOsservazioni_ASK)

        Dim listaDiPunti_MEDIA_ASK As List(Of Point) = Me.CreaListaPuntiDaListaOsservazioni(ListaMedieMobili_ASK)
        Dim listaDiPunti_MEDIA_BID As List(Of Point) = Me.CreaListaPuntiDaListaOsservazioni(ListaMedieMobili_BID)

       

        '------------------
        'Visualizzo margini
        '------------------









        g.DrawRectangle(Pens.White, New Rectangle(Me.MargineSinistro, Me.MargineAlto, b.Width - Me.MargineSinistro - Me.MargineDestro, b.Height - Me.MargineAlto - Me.MargineBasso))

        '----------------
        'Curve dei prezzi
        '----------------

        'BID
        Dim p_BID As New Pen(Color.Red, 1)
        g.DrawLines(p_BID, ListaDiPunti_BID.ToArray)

        'ASK
        Dim p_ASK As New Pen(Color.Blue, 1)
        g.DrawLines(p_ASK, ListaDiPunti_ASK.ToArray)

        'MEDIA BID
        Dim p_MEDIA_BID As New Pen(Color.Magenta, 1)
        g.DrawLines(p_MEDIA_BID, listaDiPunti_MEDIA_BID.ToArray)







        'MEDIA ASK
        Dim p_MEDIA_ASK As New Pen(Color.LightBlue, 1)
        g.DrawLines(p_MEDIA_ASK, listaDiPunti_MEDIA_ASK.ToArray)


     
        'ASSE DEI PREZZI
        Me.DrawPriceRuler()
        Dim drawfont3 As New Font("Arial", 8)
        g.FillRectangle(Brushes.Red, Me.PictureBox1.Width - 100, Me.PictureBox1.Height - 90, 5, 5)
        g.DrawString("Bid", drawfont3, Brushes.White, Me.PictureBox1.Width - 130, Me.PictureBox1.Height - 92)
        g.FillRectangle(Brushes.Blue, Me.PictureBox1.Width - 100, Me.PictureBox1.Height - 75, 5, 5)
        g.DrawString("Ask", drawfont3, Brushes.White, Me.PictureBox1.Width - 130, Me.PictureBox1.Height - 77)
        g.FillRectangle(Brushes.Magenta, Me.PictureBox1.Width - 100, Me.PictureBox1.Height - 105, 5, 5)
        g.DrawString("MM_Bid", drawfont3, Brushes.White, Me.PictureBox1.Width - 150, Me.PictureBox1.Height - 107)
        g.FillRectangle(Brushes.LightBlue, Me.PictureBox1.Width - 100, Me.PictureBox1.Height - 120, 5, 5)
        g.DrawString("MM_Ask", drawfont3, Brushes.White, Me.PictureBox1.Width - 150, Me.PictureBox1.Height - 122)




        Dim drawFont As New Font("Arial", 10)
        Dim drawFont2 As New Font("Arial", 12, FontStyle.Bold)

        g.DrawString("Serie storica dei prezzi", drawFont2, Brushes.Black, 380, 10)
        g.DrawString("Prezzo", drawFont, Brushes.Black, 10, 10)
        g.DrawString("Tempo", drawFont, Brushes.Black, Me.PictureBox1.Width - 67, Me.PictureBox1.Height - 20)

        Me.PictureBox1.Image = b

    End Sub


    Function CreaListaPuntiDaListaOsservazioni(ByVal ListaOsservazioni As List(Of Osservazione)) As List(Of Point)

        '------------------------------------------
        'Determinazione del minimo e massimo prezzo
        '------------------------------------------


        Dim TempoOrigine As Date = New Date(Now.Year, Now.Month, Now.Day, 0, 0, 0)

        Me.MinimoPrezzo = Decimal.MaxValue
        Me.MassimoPrezzo = Decimal.MinValue








        Me.MinimoTempo = Double.MaxValue
        Me.MassimoTempo = Double.MinValue

        For Each h As Osservazione In ListaOsservazioni

            With h

                'prezzo
                If MinimoPrezzo > .Prezzo Then MinimoPrezzo = .Prezzo
                If MassimoPrezzo < .Prezzo Then MassimoPrezzo = .Prezzo

                'tempo
                Dim Tempo As Double = .Istante.Subtract(TempoOrigine).TotalMilliseconds
                If MinimoTempo > Tempo Then MinimoTempo = Tempo
                If MassimoTempo < Tempo Then MassimoTempo = Tempo

            End With

        Next h

        Dim ListaPunti As New List(Of Point)




        For Each o As Osservazione In ListaOsservazioni

            With o

                'Determinazione il punto
                Dim x As Double = .Istante.Subtract(TempoOrigine).TotalMilliseconds
                Dim y As Decimal = .Prezzo

                'Trasformarmazione il punto per rappresentarlo sul bitmap
                Dim X_Sul_Bitmap As Integer = Me.Trasforma_X(x, MinimoTempo, MassimoTempo, MargineSinistro, MargineDestro)
                Dim Y_Sul_Bitmap As Integer = Me.Trasforma_Y(y, MinimoPrezzo, MassimoPrezzo, MargineAlto, MargineBasso)

                Dim p As New Point(X_Sul_Bitmap, Y_Sul_Bitmap)

                ListaPunti.Add(p)

            End With

        Next o

        Return ListaPunti

    End Function








    Function Trasforma_X(ByVal x As Double, ByVal MinX As Double, ByVal MaxX As Double, _
                         ByVal MarginLeft As Integer, ByVal MarginRight As Integer) As Integer

        Dim X_Trasformata As Integer = MarginLeft + CInt((Me.b.Width - MarginLeft - MarginRight) * (x - MinX) / (MaxX - MinX))

        Return X_Trasformata

    End Function

    Function Trasforma_Y(ByVal y As Double, ByVal MinY As Double, ByVal MaxY As Double, _
                         ByVal MarginTop As Integer, ByVal MarginBottom As Integer) As Integer

        Dim Y_Trasformata As Integer = Me.b.Height - MarginTop - CInt((Me.b.Height - MarginTop - MarginBottom) * (y - MinY) / (MaxY - MinY))






        Return Y_Trasformata

    End Function

    Sub DrawPriceRuler()

        Dim NumeroSuddivisioni As Integer = 10
        Dim Passo As Double = (Me.MassimoPrezzo - Me.MinimoPrezzo) / NumeroSuddivisioni
        Dim Prezzo As Double = Me.MinimoPrezzo

        Do
            Prezzo += Passo
            If Prezzo > Me.MassimoPrezzo Then Exit Do





            '--------------------------------
            'Disegno della tacca e del prezzo
            '--------------------------------

            Dim Y_Bitmap = Me.Trasforma_Y(Prezzo, Me.MinimoPrezzo, Me.MassimoPrezzo, Me.MargineAlto, Me.MargineBasso)

            Me.g.DrawString(Prezzo.ToString, Me.FontPrezzi, Brushes.White, Me.MargineSinistro + 5, Y_Bitmap)

        Loop

    End Sub







    Private Sub Form1_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged

        Me.DisegnaGRafico()

    End Sub

    Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged

        Me.k = Me.NumericUpDown1.Value

        Me.DisegnaGRafico()

    End Sub




    Public k As Integer

    Function MediaMobile(ByVal v As List(Of Osservazione), ByVal posizione As Integer)

        Dim somma As Double
        Dim media As Double
        Dim conta As Double

        For i As Integer = posizione - k To posizione + k
            somma += v(i).Prezzo
            conta += 1
        Next

        media = somma / conta

        Return media

    End Function

    Function sigma(ByVal v As List(Of Osservazione), ByVal posizione As Integer)
        Dim somma As Double
        Dim media As Double



        Dim conta As Double
        Dim Scarti As Double
        Dim scartiQuadrati As Double
        Dim varianza As Double
        Dim deviazione As Double


        For i As Integer = posizione - k To posizione + k
            somma += v(i).Prezzo
            conta += 1
            media = somma / conta
            Scarti = v(i).Prezzo – media



            scartiQuadrati = Scarti ^ 2
            varianza = scartiQuadrati / conta

        Next

        deviazione = Math.Sqrt(varianza)

        Return deviazione

    End Function

    Public Class Osservazione





        Public Istante As Date
        Public TipoPrezzo As Integer
        Public Prezzo As Decimal

    End Class
End Class


ESERCIZIO 4 – ACCESSO A DBMS



Vb.net permette in modo molto semplice di leggere da un database. Per fare ciò è necessario utilizzare il linguaggio natural di Vb che è il linguaggio SQL.
Tramite il linguaggio di programmazione si può accedere a qualunque DBMS e scambiare informazioni.
I comandi più utilizzati sono:
·        Select
·        Insert
·        Update
·        Create table

Non esiste un unico linguaggio SQL  da utilizzare per tutti i database anche se questi linguaggi sono tra loro molto simili.
Gli oggetti principali con i quali si riesce a fare tutto ciò che si vuole fare quando si lavora con i database sono tre:
·        Oggetto connessione (connection)
·        Oggetto comando (command)
·        Oggetto lettore (reader)

Tramite l’oggetto connection ci si collega al database con il quale si vuole lavorare e, una volta stabilita la connessone si specifica, attraverso l’oggetto command, il comando che si vuole inviare al DB; infine l’oggetto reader permette di leggere i record ricevuti.
L’esercizio è  un esempio di connessione e lettura da database.


Per fare  ciò  abbiamo scaricato un file access di esempio della Microsoft .Come prima cosa però in Vb.net deve essere attivato lo spazio dei nomi System.data e System.data.oleDb
Nel form bisogna aggiungere un Button e una RichTextBox.




Imports System.Data
Imports System.Data.OleDb


Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim percorsoDB As String = String.Empty

        Dim O As New OpenFileDialog
        With O
            .ShowDialog()
            percorsoDB = .FileName
        End With





        If percorsoDB = String.Empty Then Exit Sub
        Try

            'connessione

            Dim stringaconnessione As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & percorsoDB & ";user Id=admin;Password=;"
            Dim connessione As New OleDbConnection(stringaconnessione)
            connessione.Open()

            'comando

            Dim comandoSQL As String = "SELECT*FROM ORDERS"
            Dim comando As New OleDbCommand(comandoSQL, connessione)
            Dim lettore As OleDbDataReader = comando.ExecuteReader()

            'adesso ho il lettore

            Dim record(lettore.FieldCount - 1) As Object
            Do While lettore.Read
                lettore.GetValues(record)
                Me.RichTextBox1.AppendText(vbCrLf & record(0) & " " & record(1) & " " & record(2))
            Loop

            MsgBox("Connesso ok")

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub
End Class


ESERCIZIO 5 – WORD CLOUD




VB.NET permette di realizzare le “tag cloud”, cioè una rappresentazione visiva delle parole chiavi utilizzate in un testo. La dimensione di ogni parola è proporzionale alla sua frequenza nel testo. “Le nuvole di tag” (questo il loro nome in italiano) hanno una funzione molto utile: permettono, in pochi istanti, di capire i principali argomenti trattati dal testo in questione.
Per svolgere l’esercizio aggiungiamo nel form una PictureBox  e due RichTextBox (la prima servirà per contenere il testo originale, mentre la seconda conterrà il testo normalizzato, cioè depurato da articoli,congiunzioni,preposizioni).
Le principali funzioni legate al text minino sono:
·        la funzione Replace che permette di eleminare quello che ci da fastidio nel testo;
·        la funzione Contains che permette di vedere se una stringa contiene un’altra stringa;
·        la funzione IndexOf ci dice la posizione che occupa all’interno di una stringa un certo carattere;
·        la funzione Length che ci dice la lunghezza della stringa;
·         la funzione ToLower che rende tutto minisculo mentre ToUpper rende tutto maiuscolo.











Public Class Form1

    Public b As Bitmap
    Public g As Graphics
    Public ParoleDaIgnorare As Dictionary(Of String, Boolean)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ParoleDaIgnorare = New Dictionary(Of String, Boolean)(StringComparer.InvariantCultureIgnoreCase)






        Me.ParoleDaIgnorare.Add(" I ", Nothing)
        Me.ParoleDaIgnorare.Add(" IL ", Nothing)
        Me.ParoleDaIgnorare.Add(" LA ", Nothing)
        Me.ParoleDaIgnorare.Add(" LE ", Nothing)
        Me.ParoleDaIgnorare.Add(" GLI ", Nothing)
        Me.ParoleDaIgnorare.Add(" IN ", Nothing)
        Me.ParoleDaIgnorare.Add(" CON ", Nothing)
        Me.ParoleDaIgnorare.Add(" SU ", Nothing)
        Me.ParoleDaIgnorare.Add(" PER ", Nothing)
        Me.ParoleDaIgnorare.Add(" TRA ", Nothing)
        Me.ParoleDaIgnorare.Add(" FRA ", Nothing)
        Me.ParoleDaIgnorare.Add(" UN ", Nothing)
        Me.ParoleDaIgnorare.Add(" UNO ", Nothing)
        Me.ParoleDaIgnorare.Add(" UNA ", Nothing)
        Me.ParoleDaIgnorare.Add(" O ", Nothing)
        Me.ParoleDaIgnorare.Add(" A ", Nothing)
        Me.ParoleDaIgnorare.Add(" DI ", Nothing)
        Me.ParoleDaIgnorare.Add(" CHE ", Nothing)
        Me.ParoleDaIgnorare.Add("PER ", Nothing)
        Me.ParoleDaIgnorare.Add(" SIA ", Nothing)
        Me.ParoleDaIgnorare.Add(" ALLE ", Nothing)
        Me.ParoleDaIgnorare.Add(" ALLA ", Nothing)
        Me.ParoleDaIgnorare.Add(" AL ", Nothing)

        Dim Testoo As String = Me.RichTextBox1.Text
        Dim Testo_Normalizzato As String = Testoo.ToUpper.Replace(",", " ").Replace(vbCrLf, " ").Replace("!", " ").Replace("  ", " ").Replace("(", " ").Replace(")", " ")

        For Each ParolaDaRimuovere As String In Me.ParoleDaIgnorare.Keys
            Testo_Normalizzato = Testo_Normalizzato.Replace(ParolaDaRimuovere, " ")
        Next ParolaDaRimuovere
        Testo_Normalizzato.Replace("  ", " ")

        Me.RichTextBox2.Text = Testo_Normalizzato

        Dim MinimaDimensioneFont As Integer = 10
        Dim MassimaDimensioneFont As Integer = 50
        Dim MinFrequenza = 1
        Dim MaxFrequenza = 0
        Dim temp = 0
        Dim RND As New Random
        Dim colorNames As String() = System.Enum.GetNames(GetType(KnownColor))
        Dim lstColors As New List(Of String)(colorNames)
        Dim Testo As String = Me.RichTextBox1.Text

        Testo.ToUpper()

        Dim Parole() As String = Testo_Normalizzato.Split((vbCrLf & " ").ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        Dim ListaParoleDiverse As New SortedList(Of String, InfoParola)







        For Each parola As String In Parole
            If Not ListaParoleDiverse.ContainsKey(parola) Then
                Dim infoP As New InfoParola
                infoP.numeroOccorrenze = 1
                infoP.PAROLA = parola





                ListaParoleDiverse.Add(parola, infoP)
            Else
                ListaParoleDiverse.Item(parola).numeroOccorrenze += 1
                temp = ListaParoleDiverse.Item(parola).numeroOccorrenze
                If MaxFrequenza < temp Then MaxFrequenza = temp
            End If


        Next

        b = New Bitmap(Me.PictureBox1.Width, Me.PictureBox1.Height)
        g = Graphics.FromImage(b)
        g.SmoothingMode = SmoothingMode.HighQuality
        g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias

        Dim Raggio As Double = b.Width / 3

        'Determiniamo la dimensione del font corrispondente alla frequenza

        For Each InfoParola As InfoParola In ListaParoleDiverse.Values

            With InfoParola

                Dim NumeroCasuale0_1 As Double = RND.NextDouble
                Dim PathRettangoli As New GraphicsPath

                'Rettangolo della stringa

                Dim IndiceCasuale As Integer = RND.Next(0, lstColors.Count - 1)
                .Colore = System.Drawing.Color.FromName(lstColors(IndiceCasuale))
                Dim ANgoloCasuale As Double = RND.NextDouble * 2 * Math.PI
                Dim DIstanzaCasuale As Double = RND.NextDouble * Raggio


                .x = b.Width / 2 + Math.Cos(ANgoloCasuale) * DIstanzaCasuale
                .y = b.Height / 2 + Math.Sin(ANgoloCasuale) * DIstanzaCasuale


                .DimensioneDelFontCorrispondenteAllaFrequenza = CSng(MinimaDimensioneFont + (.numeroOccorrenze - MinFrequenza) * (MassimaDimensioneFont - MinimaDimensioneFont) / (MaxFrequenza - MinFrequenza))
                Dim FontProporzionato As New Font("Arial", .DimensioneDelFontCorrispondenteAllaFrequenza, FontStyle.Regular, GraphicsUnit.Pixel)




                Dim Size As SizeF = g.MeasureString(.PAROLA, FontProporzionato, Point.Empty, StringFormat.GenericDefault)
                Dim LarghezzaParola = Size.Width
                Dim AltezzaParola = Size.Height

                .SIzeFString = g.MeasureString(.PAROLA, FontProporzionato)
                Dim RettangoloStringa As New Rectangle(New Point(.x, .y), .SIzeFString.ToSize)






                Dim R As New Region(PathRettangoli)
                If Not R.IsVisible(RettangoloStringa) Then
                    g.DrawString(.PAROLA, FontProporzionato, New SolidBrush(.Colore), .x, .y)
                    PathRettangoli.AddRectangle(RettangoloStringa)
                End If

            End With
        Next InfoParola


        Me.PictureBox1.Image = b
        Application.DoEvents()

        Me.PictureBox1.Image = b

    End Sub


End Class

Public Class InfoParola
    Public x As Double
    Public y As Double
    Public PAROLA As String
    Public numeroOccorrenze As Integer
    Public DimensioneDelFontCorrispondenteAllaFrequenza As Single
    Public Colore As Color
    Public SIzeFString As SizeF
End Class


ESERCIZIO 6 – QUANT


In questo esercizio è stata realizzata una strategia che permette di vedere se si ha un profitto dall’acquisto e vendita di azioni.
I prezzi delle azioni sono stati calcolati utilizzando la formula
Pn =  Pn-1  -  ( a + b * passo ) * d
dove a ,bd  sono dei  parametri da inserire nelle  NumericUpDown.
In una delle NumericUpDown viene inserita anche la posizione che indica il numero delle azioni che devono essere acquistate ad ogni passo.
Il retracement indica  il rialzo necessario per realizzare un profitto, mentre il retracement relativo indica di quanto deve salire il prezzo rapportato alla caduta totale.
Utilizzando questa formula per calcolare i prezzi delle azioni possiamo vedere però, come quest’ultimi sono soltanto decrescenti e non si ha perciò mai un profitto come si può notare analizzando la colonna PNL.



Public Class Form1

    Public Livello_Prezzi As New List(Of Oss)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim somma As Double = 0
        Dim somma_quantita_acquistata As Integer = 0
        Dim passo As Integer = 1
        Dim a As Integer = CInt(Me.NumericUpDown1.Value)
        Dim b As Integer = CInt(Me.NumericUpDown2.Value)
        Dim Prezzo_iniziale = CDbl(Me.RichTextBox3.Text)
        Dim Decremento_prezzo As Integer = CInt(Me.NumericUpDown3.Value)
        Dim posizione As Integer = CInt(Me.NumericUpDown4.Value)
        Dim quantita_acquistata As Integer = CInt(Me.NumericUpDown4.Value)
        Dim valore As Double = 0
        Dim P As Double = CDbl(Me.RichTextBox3.Text)
        Dim Target As Double = CDbl(Me.RichTextBox2.Text)






        Do While P > 0
            Dim Buy As New Oss
            With buy
                somma_quantita_acquistata += quantita_acquistata
                .passo = passo
                .posizione = posizione
                .Valore = valore + P * quantita_acquistata
                .Prezzo = P
                somma += .Valore
                .perdita = .Prezzo * .posizione - .Valore
                .P = (.Valore + Target) / .posizione
                .retracement = .P - P
                .relative_retracement = .retracement / (Prezzo_iniziale - .Prezzo)
                .prezzo_medio = somma / somma_quantita_acquistata
                .retracement_corrente = .retracement / P

                Livello_Prezzi.Add(Buy)

                P = P - (a + b * passo) * Decremento_prezzo
                passo += 1
                posizione = .posizione + quantita_acquistata
                valore = .Valore

            End With

        Loop

        Dim string_builder As New System.Text.StringBuilder

        string_builder.Append(vbCrLf & "Passo".PadLeft(0) & _
                           "Posizione".PadLeft(10) & _
                           "Valore".PadLeft(10) & _
                           "P_Correnti".PadLeft(20) & _
                           " PNL".PadLeft(13) & _
                           "RTC".PadLeft(14) & _
                           "R_Retracement".PadLeft(17) & _
                           "P_Medio".PadLeft(17) & _
                           "RTC_su_prezzo_corrente".PadLeft(25))


        For Each modifica As Oss In Livello_Prezzi
            With modifica
                string_builder.Append(vbCrLf & .passo.ToString.PadLeft(0) & _
                                   .posizione.ToString.PadLeft(10) & _
                                   .Valore.ToString.PadLeft(13) & _
                                   .Prezzo.ToString.PadLeft(17) & _
                                   .perdita.ToString.PadLeft(17) & _
                                   .retracement.ToString(".##").PadLeft(14) & _
                                   .relative_retracement.ToString(".##").PadLeft(17) & _
                                   .prezzo_medio.ToString.PadLeft(17) & _
                                   .retracement_corrente.ToString(".##").PadLeft(18))
         



  End With
        Next modifica
        Me.RichTextBox1.Text = string_builder.ToString
    End Sub

End Class



Public Class Oss
    Public Prezzo As Double
    Public passo As Integer
    Public posizione As Integer
    Public Valore As Double
    Public perdita As Double
    Public P As Double
    Public prezzo_medio As Double
    Public retracement As Double
    Public relative_retracement As Double
    Public retracement_corrente As Double

End Class


ESERCIZIO 7 – TRADING ALGORITHM




Secondo molte ricerche  condotte da molti centri universitari la formazione del prezzo di un’ azione è indipendente dal precedente prezzo di mercato per quell’azione: la storia dei prezzi di un’azione non costituisce un indicatore affidabile per i prezzi futuri di lungo periodo della medesima azione.  In poche parole il movimento dei prezzi sarebbe casuale ed imprevedibile.
Per questo motivo in questo esercizio i prezzi delle azioni sono stati calcolati utilizzando due diversi metodi: Random Walk  e  Geometric Brownian Motion.
Per generare i prezzi nella Random Walk usiamo la variabile bernoulliana. In questo modo abbiamo generato una passeggiata aleatoria. Utilizzando però questo metodo si possono avere dei prezzi di segno negativo  e questo non è realistico e non ha senso.
Quindi spesso vengono utilizzati metodi alternativi che non presentano questo problema. Il più diffuso è il Geometric Brownian Motion : si fa un’estrazione da una distribuzione Normale e in base a quest’ultima si decide la variazione del prezzo. Dunque il GBM  è un’applicazione della Normale. I paramentri sono:
·        Drift  = direzione ( media )
·        Volatility = volatilità ( varianza )

Nel nostro esercizio è possibile disegnare sia la curva dei prezzi calcolati secondo il metodo Random Walk che la curva dei prezzi calcolati secondo il metodo Geometric Brownian Motion.
Per ogni curva è poi possibile calcolare quanti acquisti e vendite ci saranno.



Public Class Form1
    Private b As Bitmap
    Private g As Graphics

    'imposta i margini
    Private MargineSinistro As Integer = 40
    Private MargineDestro As Integer = 40

    Private MargineAlto As Integer = 40
    Private MargineBasso As Integer = 40

    Private MinimoPrezzo As Decimal
    Private MassimoPrezzo As Decimal

   

Private MinimoTempo As Double
    Private MassimoTempo As Double

    'creiamo la lista dei punti della curva
    Dim ListaPunti As List(Of Point)

    Public PrezziRandom As List(Of Oss)
    Public Ordine = New List(Of DeltaP)


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.resetgrafica()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Me.Button1.Enabled = True
        Me.RichTextBox1.Clear()
        If Me.Button3.CanSelect Then

            RW()
        Else : GBM()
        End If



        DisegnaGRafico()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim Target As Double = Double.Parse(Me.NumericUpDown3.Value)

        Dim PrezzoIniziale = Double.Parse(Me.NumericUpDown4.Value)
        Dim NumeroAcquisti As Integer = 0
        Dim NumeroVendite As Integer = 0
        Dim AmmontareAcquistato As Double = 0
        Dim AmmontareVenduto As Double = 0
        Dim Posizione As Integer = 0
        Dim Profitto As Double = 0
        Dim a As Double = Double.Parse(Me.NumericUpDown1.Value)
        Dim Minimo_Prezzo_Acquisto = PrezzoIniziale
        Button2.Enabled = True




        Dim Decremento As Double = Double.Parse(Me.NumericUpDown2.Value)

        Dim i As Integer = 1 '-1




        For Each o As Oss In PrezziRandom
            i += 1
            'compra titoli
            If o.Prezzo <= Minimo_Prezzo_Acquisto - (a * Decremento) Then

                Dim Acquista As New DeltaP
                With Acquista
                    .Istante = o.Istante
                    .isBuy = True
                    .Quantita = 1
                    .PrezzoCorrente = o.Prezzo
                    AmmontareAcquistato += .PrezzoCorrente * .Quantita
                    Posizione += .Quantita
                    .PNL = AmmontareVenduto - AmmontareAcquistato
                    .Minimo_Prezzo_Acquisto = .PrezzoCorrente
                    Minimo_Prezzo_Acquisto = .PrezzoCorrente

                    Ordine.Add(Acquista)
                End With
                g = Graphics.FromImage(b)
                Dim Penna As New Pen(Color.Blue, 1)
                g.DrawLine(Penna, ListaPunti(i).X, MargineAlto, ListaPunti(i).X, b.Height - Me.MargineBasso)
                Me.PictureBox1.Image = b

                NumeroAcquisti += 1

                'vende titoli
            ElseIf (o.Prezzo * Posizione >= AmmontareAcquistato + Target) Then

                Dim Vendi As New DeltaP
                AmmontareVenduto += o.Prezzo * Posizione
                With Vendi
                    .PrezzoCorrente = o.Prezzo
                    .PNL = AmmontareVenduto - AmmontareAcquistato
                    .isBuy = False
                    .Minimo_Prezzo_Acquisto = .PrezzoCorrente
                    Minimo_Prezzo_Acquisto = .PrezzoCorrente
                    Ordine.Add(Vendi)
                End With

                g = Graphics.FromImage(b)
                Dim Penna As New Pen(Color.Red, 1)
                g.DrawLine(Penna, ListaPunti(i).X, MargineAlto, ListaPunti(i).X, b.Height - Me.MargineBasso)

                Me.PictureBox1.Image = b
                NumeroVendite += 1
                Posizione = 0


                Profitto += Vendi.PNL
                AmmontareAcquistato = 0
                AmmontareVenduto = 0

          



 End If
        Next

        'Visualizziamo nella RichTextBox1 il numero delle vendite, degli acquisti e PNL


        Me.RichTextBox1.Clear()
        Me.RichTextBox1.AppendText(vbCrLf & " Vendite " & NumeroVendite)
        Me.RichTextBox1.AppendText(vbCrLf & " Acquisti " & NumeroAcquisti)
        Me.RichTextBox1.AppendText(vbCrLf & " PNL " & Profitto - AmmontareAcquistato)

    End Sub

    Public r As New Random
    Sub GBM()

        'generiamo i prezzi da un moto browniano

        Dim PrezzoIniziale As Decimal = Double.Parse(Me.NumericUpDown4.Value)
        Dim IstanteIniziale As Date = Now
        Dim T_Size As Decimal = 0.01

        'Primo prezzo della serie

        Dim PrezzoCorrente As Decimal = PrezzoIniziale
        Dim IstanteCorrente As Date = IstanteIniziale

        Dim ListaPrezzi As New List(Of Oss)
        Dim Oss1 As New Oss

        With Oss1
            .Istante = IstanteCorrente
            .Prezzo = PrezzoCorrente
        End With
        ListaPrezzi.Add(Oss1)


        'Prezzi successivi     

        Dim Media As Double = 0
        Dim Volatilita As Double = 0.02


        Do

            Dim T_Span As New TimeSpan(0, 0, 0, 0, r.Next(1, 5) * 1000)

            'Generiamo una normale

            Dim u1 As Double = r.NextDouble






            Dim u2 As Double = r.NextDouble
            Dim Normale_Standard As Double = Math.Sqrt(-2 * Math.Log(u1)) * Math.Sin(2 * Math.PI * u2)

            Dim T As Double = T_Span.TotalDays / 252  'anni
            Dim Mean As Double = (Media - Volatilita * Volatilita / 2) * T
            Dim Sigma As Double = Volatilita * Math.Sqrt(T)
            Dim Normale As Double = Me.Normale_Non_STardard(Normale_Standard, Mean, Sigma)




            ' Discretizzazione incremento

            Dim NuovoPrezzo As Double = PrezzoCorrente * Math.Exp(Normale)
            Dim DifferenzaRispettoPrecedenteInTicks As Integer = CInt((NuovoPrezzo - PrezzoCorrente) / T_Size)

            PrezzoCorrente = PrezzoCorrente + DifferenzaRispettoPrecedenteInTicks * T_Size
            '--------------------------------------

            IstanteCorrente = IstanteCorrente.AddMilliseconds(T_Span.TotalMilliseconds)

            Dim NewOss As New Oss
            With NewOss
                .Istante = IstanteCorrente
                .Prezzo = PrezzoCorrente
            End With

            ListaPrezzi.Add(NewOss)

            If IstanteCorrente.Subtract(IstanteIniziale).TotalHours > 23 Then Exit Do

        Loop
        PrezziRandom = ListaPrezzi

    End Sub


    Function Normale_Non_STardard(ByVal Normale_STandard As Double, ByVal Mean As Double, ByVal Sigma As Double) As Double
        Return Normale_STandard * sigma + Mean
    End Function

    Sub RW()

        'generiamo i prezzi da un Random Walk

        Dim PrezzoIniziale As Decimal = Double.Parse(Me.NumericUpDown4.Value)




        Dim Conta_Minuti As Integer = 0
        Dim IstanteIniziale As Date = Now
        Dim Tick As Decimal = 1
        Dim T_Span As New TimeSpan(0, 0, 0, 0, r.Next(1, 5) * 1000)
        Dim PrezzoCorrente As Decimal = PrezzoIniziale
        Dim IstanteCorrente As Date = IstanteIniziale
        Dim ListaPrezzi As New List(Of Oss)

        Do
            If r.NextDouble > 0.5 Then
                PrezzoCorrente += Tick
            Else
                PrezzoCorrente -= Tick
            End If

            IstanteCorrente = IstanteCorrente.AddMilliseconds(T_Span.TotalMilliseconds)

            Dim NewOss As New Oss
            With NewOss
                .Istante = IstanteCorrente
                .Prezzo = PrezzoCorrente
            End With

            ListaPrezzi.Add(NewOss)

            If IstanteCorrente.Subtract(IstanteIniziale).TotalHours > 23 Then Exit Do
        Loop

        PrezziRandom = ListaPrezzi


    End Sub


    Function CreaListaPuntiDaListaOsservazioni(ByVal ListaOsservazioni As List(Of Oss)) As List(Of Point)

        'modifico TempoOrigine
        Dim TempoOrigine As Date = New Date(Now.Year - 1, Now.Month, Now.Day, 0, 0, 0)

        Me.MinimoPrezzo = Decimal.MaxValue
        Me.MassimoPrezzo = Decimal.MinValue

        Me.MinimoTempo = Double.MaxValue
        Me.MassimoTempo = Double.MinValue

        'Troviamo il minimo ed il massimo per gestire la grafica
        For Each Oss As Oss In ListaOsservazioni
            With Oss






                'prezzo
                If MinimoPrezzo > .Prezzo Then MinimoPrezzo = .Prezzo
                If MassimoPrezzo < .Prezzo Then MassimoPrezzo = .Prezzo

                'tempo
                Dim Tempo As Double = .Istante.Subtract(TempoOrigine).TotalMilliseconds
                If MinimoTempo > Tempo Then MinimoTempo = Tempo
                If MassimoTempo < Tempo Then MassimoTempo = Tempo

            End With
        Next Oss

        Dim ListaPunti As New List(Of Point)
        For Each Oss As Oss In ListaOsservazioni

            With Oss

                'Determinare il punto!
                Dim x As Double = .Istante.Subtract(TempoOrigine).TotalMilliseconds
                Dim y As Decimal = .Prezzo

                'Trasformare il punto per rappresentarlo sul bitmap!
                Dim X_Sul_Bitmap As Integer = Me.Trasforma_X(x, MinimoTempo, MassimoTempo, MargineSinistro, MargineDestro)
                Dim Y_Sul_Bitmap As Integer = Me.Trasforma_Y(y, MinimoPrezzo, MassimoPrezzo, MargineAlto, MargineBasso)


                Dim p As New Point(X_Sul_Bitmap, Y_Sul_Bitmap)


                ListaPunti.Add(p)

            End With

        Next Oss

        Return ListaPunti

    End Function

    'rendiamo la X relativa per usarla nel grafico

    Function Trasforma_X(ByVal x As Double, ByVal MinX As Double, ByVal MaxX As Double, _
                         ByVal MarginLeft As Integer, ByVal MarginRight As Integer) As Integer

        Dim X_Trasformata As Integer = MarginLeft + CInt((Me.b.Width - MarginLeft - MarginRight) * (x - MinX) / (MaxX - MinX))
        Return X_Trasformata

    End Function




    'rendiamo la Y relativa per usarla nel grafico

    Function Trasforma_Y(ByVal y As Double, ByVal MinY As Double, ByVal MaxY As Double, _
                         ByVal MarginTop As Integer, ByVal MarginBottom As Integer) As Integer

        Dim Y_Trasformata As Integer = Me.b.Height - MarginTop - CInt((Me.b.Height - MarginTop - MarginBottom) * (y - MinY) / (MaxY - MinY))
        Return Y_Trasformata

    End Function


    'resetta la grafica

    Sub resetgrafica()
        b = New Bitmap(Me.PictureBox1.Width, Me.PictureBox1.Height)
        g = Graphics.FromImage(b)
    End Sub

    Sub DisegnaGRafico()

        If Me.PrezziRandom Is Nothing Then Exit Sub

        'pulisce l'area del grafico da eventuali grafici precedenti

        g.Clear(Color.Black)


        ' Adesso la lista osservazioni diventa lista di punti da rappresentare su un bitmap

        'creiamo la lista dei punti

        ListaPunti = CreaListaPuntiDaListaOsservazioni(PrezziRandom)


        'Visualizziamo i margini

        g.DrawRectangle(Pens.Black, New Rectangle(Me.MargineSinistro, Me.MargineAlto, _
                                                      b.Width - Me.MargineSinistro - Me.MargineDestro, b.Height - Me.MargineAlto - Me.MargineBasso))
        'Curva dei prezzi

        Dim Penna_Prezzi As New Pen(Color.Red, 1)
        g.DrawLines(Penna_Prezzi, ListaPunti.ToArray)

        Me.PictureBox1.Image = b

    End Sub    







    'ridisegnamo il grafico in caso di resize

    Private Sub Form1_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
        Me.resetgrafica()
        Me.DisegnaGRafico()
    End Sub

   

    Private Sub button3_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.Button4.Enabled = True
        Me.Button3.Enabled = False
        Me.Button2.Text = "plot random walk curve"
        Me.Button1.Text = "buy\sel random walk mode"


    End Sub

    Private Sub button4_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Me.Button3.Enabled = True
        Me.Button4.Enabled = False
        Me.Button2.Text = "plot random brawnian"
        Me.Button1.Text = "buy\sel random brownian mode"
    End Sub
End Class


Public Class DeltaP

    Public Istante As Date
    Public Quantita As Integer
    Public isBuy As Boolean
    Public PrezzoCorrente As Double
    Public PNL As Double
    Public Minimo_Prezzo_Acquisto As Double
End Class


Public Class Oss

    Public Istante As Date
    Public TipoPrezzo As Integer
    Public Prezzo As Decimal

End Class












Nessun commento:

Posta un commento

Nota. Solo i membri di questo blog possono postare un commento.