Click here to Skip to main content
15,883,848 members
Articles / Programming Languages / PowerShell
Tip/Trick

Get Real Time Quotes using PowerShell

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
25 Jun 2014CPOL2 min read 28.4K   227   6   4
Get quote using Yahoo finance

Monitor Quote using PowerShell

In this tip, I will demonstrate how to use Powershell to display quotes in real time using Yahoo finance site. I wrote few years ago the same basic code in a C# control and a small application to monitor a basket (many quotes in the same time) in order to produce statistics and other features.

This example could be useful and encourage someone to start learning and use the power of the ... PowerShell.

Using the Code

The code is stored in a text file with the .ps1 extension. For instance, the name of the file is getyfx.ps1 and is stored in the c:\temp directory.

Start PowerShell and at the prompt, type:

PS C:\> . C:\temp\getyfx.ps1

Image 1

The script takes 3 parameters:

  • quote index - must match with the stock listed code
  • quote name - informal
  • number of iterations - default value is 10

The complete source is self explanatory and easy to understand.

param([String]$qindex,[String]$qname ,[Int32]$iterations=10)

 

function getQPreviousCloseAndOpenInfo($index)
{
<#
  .SYNOPSIS
  Returns 2 values of a given qoute
  .DESCRIPTION
  Takes the symbol of a quote and returns the values: 
  Previous Close, Open 
  .EXAMPLE
  $q = getQInfo "BCE.TO"
  .EXAMPLE
  $q = getQInfo "IBM"
  $q = getQInfo "giba.to"
  .PARAMETER $index
  The quote symbol 
  #>


    $url="http://ca.finance.yahoo.com/q?s=$sindex"
    # regex to extract the values
    $pclose="Prev Close:(.*)<td class=(.*)>(.*)</td>(.*)"
    $popen="Open:(.*)<td class=(.*)>(.*)</td>(.*)"
        
    # obtain data from the given url
    $wc = new-object System.Net.WebClient
    $wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
    $data=$wc.OpenRead($url)
    $rd = new-object System.IO.StreamReader($data)
    $s=$rd.ReadToEnd()
    # extract partial strings to be matched with he above regex
    $sprevclose=$s.substring($s.IndexOf("Prev Close:"),59)
    $sopen=$s.substring($s.IndexOf("Open:"),53)
    $open=0.0
    $prevclose=0.0
    
    if ($sprevclose -Match $pclose ) {$prevclose =( $matches[3] -as [double])}
    if ($sopen -Match $popen ){$open = ($matches[3] -as [double])}
    # return values in an object
    $q=new-object PSObject -property @{prevclose=$prevclose;open=$open}
    return $q
}
function getQAskAndBidInfo($index)
{
<#
  .SYNOPSIS
  Returns 2 values of a given qoute
  .DESCRIPTION
  Takes the symbol of a quote and returns the values: 
  Bid and Ask
  .EXAMPLE
  $q = getQInfo "BCE.TO"
  .EXAMPLE
  $q = getQInfo "IBM"
  $q = getQInfo "giba.to"
  .PARAMETER $index
  The quote symbol 
  #>

    $url="http://ca.finance.yahoo.com/q?s=$sindex"
    # regex to extract the values
    $pask="Ask:(.*)<td class=(.*)(.*)(.*)"
    $pbid="Bid:(.*)    $i=0
        $openclose=getQPreviousCloseAndOpenInfo $sindex
        showQOpenClose $openclose
    $prevQ= new-object PSObject -property @{ask=0.0;bid=0.0}
    while ($i -lt $iterations) {
           write-host "---iteration $i : Time: $(get-date -Format ‘HH:mm:ss’)----"
            $q2= getQAskAndBidInfo $sindex
        $lbl =        "*** Ask        : "
        if ($q2.ask -lt $prevQ.ask) {writeQInfo  $openclose.prevclose $q2.ask $lbl "red"}
        if ($q2.ask -gt $prevQ.ask) {writeQInfo  $openclose.prevclose $q2.ask $lbl "green"}
        if ($q2.ask -eq $prevQ.ask) {writeQinfo  $openclose.prevclose $q2.ask $lbl "white"}
        $prevQ.ask=$q2.ask

        $lbl =     "*** Bid        : "
        if ($q2.bid -lt $prevQ.bid) {writeQInfo $openclose.prevclose $q2.bid $lbl "red"  }
        if ($q2.bid -gt $prevQ.bid) {writeQInfo $openclose.prevclose $q2.bid $lbl "green"}
        if ($q2.bid -eq $prevQ.bid) {writeQinfo  $openclose.prevclose $q2.bid $lbl "white"}
        $prevQ.bid = $q2.bid
                
        Start-sleep -seconds 10
        $i=$i+1
    }
    
    
}
function uHelp($script){
     write-host "usage "       $script " quoteindex [quotename] [noiterations]"
     write-host "example: .  " $script " bce.to"
     write-host "example: .  " $script " bce.to 'bce.inc' "
     write-host "example: .  " $script " bce.to 'bce.inc' 100"
     write-host "example running for index giba.to with 3 iterations :  "
    
}
# main program 
if ($qindex -eq "" ){
    uHelp $MyInvocation.MyCommand.Definition
    exit
}
 
runQInfo $qindex $qname $iterations

If no parameters provided the function uHelp() displays the usage of this script. See how the name of the current script is retrieved.

Image 2

Next, the program calls the runQInfo() function passing the parameters read from command line.

The runQInfo() function calls the getQPreviousCloseAndOpenInfo() function that returns an PSObject in which the previous close and the open values are stored.

This is done by accessing the Yahoo finance site for the given quote and using simple regular expression to retrieve the values from the returned HTML string.

These values are stored and used to compare with the current values of the quote: bid and asked values.

Next, the runQInfo() function performs calls to the getQAskAndBidInfo() which is similar to getQPreviousCloseAndOpenInfo() in order to retrieve the bid and ask values.

The program stops when the runQInfo() function terminates the number of iterations. The delay between iterations is 10 seconds:

Start-sleep -seconds 10

Image 3

Points of Interest

I wrote the same functionality (in PowerShell) but using System.Timer object and elapsed event instead of looping a given number of iterations.

I had fun writing this code. It could be useful to someone starting with PowerShell.

History

  • 2014-06-25 - Added source code
  • 2014-03-24 - First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
C,C++,C#,X++,.NET,JavaScript,ASP.NET,MVC,jQuery,Ajax,HTML5,WCF,JAVA,PHP,PowerShell,SharePoint 2010/2013,Dynamics AX,MSSQL,SQLCLR,MySQL,Oracle,Sybase, SSIS,SSRS,Infragistics,BI,CrystalReports,ADO.NET,EntityFramework,Unix,C Shell,PERL,COBOL,Z/OS.

Comments and Discussions

 
SuggestionCode Copy Pin
Larry_Coffey31-Mar-14 7:56
Larry_Coffey31-Mar-14 7:56 
Bugincomplete listing Pin
ajp9831-Mar-14 6:39
ajp9831-Mar-14 6:39 
GeneralRe: incomplete listing Pin
george bolovan31-Mar-14 7:13
professionalgeorge bolovan31-Mar-14 7:13 
GeneralRe: incomplete listing Pin
ajp982-Apr-14 4:49
ajp982-Apr-14 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.