domenica 9 gennaio 2011

ESERCIZI PER L'ESAME – FULVIO VENTURINI

Esercizio 1  PARSING

 In informatica il parsing o analisi sintattica è il processo atto ad analizzare uno stream continuo in input, letto da un file o una tastiera, in modo da determinare la sua struttura grammaticale grazie ad una data grammatica formale. Un parser è un programma che esegue questo compito.



CODICE

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 2a  IMMAGINI

Nel codice che segue costruiamo uno strumento che carica due immagini, di cui è stata specificata la posizione, in due picturebox. Le immagini si scambieranno nelle due picturebox ad intervalli regolari da noi definiti e la loro posizione ruoterà nel tempo. Sarà inoltre possibile fermare questo processo cliccando sul bordo per poi ripartire ad un ulteriore click.



CODICE

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\44gatti.jpg")
        Me.PictureBox2.Image = Image.FromFile("F:\ESERCIZI ESAME\gatt.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


    'ora facciamo che se clicco sull'immagine la stoppo e poi se clicco riparte

    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 2b  FORME

Questo esercizio è ancora sulla grafica. Useremo un immagine vuota, un bitmap, per visualizzare grafici raccolti nell'oggetto graphic. Gli oggetti si muoveranno nel bitmap secondo traiettorie da noi stabilite.


CODICE

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 STORICHE

Lo strumento creato con le seguenti righe di codice ci consente di selezionare un file in cui sono contenuti dei prezzi in serie storica e, dopo aver trasformato le osservazioni in punti sul bitmap, visualizzare le loro fluttuazioni. Verranno calcolate e rappresentate graficamente anche le medie mobili dei due tipi di prezzi. Il numero di termini delle medie mobili può essere fissato dall'utente.







CODICE


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  CONESSIONE AD UN DBMS

In informatica un Database Management System (DBMS) è un sistema software progettato per consentire la creazione e manipolazione di database da parte di più utenti. Con il codice che segue si costruisce uno strumento che ci consente di connetterci ad un DBMS. L'oggetto Oledbconnection crea la connessione al database e l'istruzione GetValue ci consente di prendere un record.

CODICE

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

            'connessioe

            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

Il codice che segue ci consente di analizzare un testo da noi inserito in una richtextbox. Questo strumento, dopo aver escluso un lista di parole di nessun interesse come gli articoli o le congiunzioni, conta il numero di presenze di ogni parola nel testo e da in output un immagine sulla  picturebox in cui le parole compaiono con dimensioni proporzionali alla loro frequenza nel testo.

CODICE

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, fissato un prezzo iniziale dall'utente, vengono simulati una serie di prezzi di titoli che vengono acquistati ad ogni variazione di prezzo. La variazione di prezzo induce una situazione che può essere di perdita o di guadagno e una variazione del valore dei titoli di cui siamo in possesso. Lo strumento costruito con il codice qui riportato ci indica: il prezzo corrente, l'ammontare speso fino a quel momento, il prezzo medio, il guadagno o la perdita, il retracement. I parametri a, b e d, determinati nelle numericupdown sono i parametri presenti nella formula di determinazione dei prezzi mentre la quantità indicata con il termine “posizione” indica la quantità di titoli che si desidera acquistare ad ogni passaggio.


CODICE

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

Questo esercizio è un evoluzione dell'esercizio precedente. In questo caso però è possibile scegliere il meccanismo con cui generare la serie dei prezzi ed inoltre vengono rappresentati graficamente l'andamento dei prezzi e i punti in cui vendere o acquistare il titolo. Per la generazione dei prezzi è possibile ricorrere al Geometric Brownian Motion, che determinerà solo prezzi casuali positivi, o il Random Walk.

CODICE

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.