예제 #1
0
def Bchange(args):
    """
    #Use: Bchange(args)
    #Pre: args is a list of strings, args[1] is a optional string that represents a ticker.
    #Post:The stockObject has been changed, to args[1] if provided and correct.
    """
    global stockObj
    if len(args) == 1:
        print "Please enter the ticker of the company/index you wish to check."
        while True:
            ticker = raw_input("Ticker: ")
            try:
                stockObj = stockInfo(ticker)
                print stockObj
                break
            except ValueError:
                print "Ticker '%s'  not found. Please enter valid ticker" % (
                    ticker)
    else:
        try:
            stockObj = stockInfo(args[1])
            print stockObj
        except ValueError:
            print "Ticker '%s'  not found. Please enter valid ticker" % (
                args[1])
예제 #2
0
 def on_new(self, event):
     """Handles creating new tickers"""
     prompt = wx.TextEntryDialog(self, "Enter new ticker", "New ticker",self.panel.stockObj.ticker)
     prompt.ShowModal() 
     #Use this loop and recursion to ensure we get a legal value
     try:
         self.flash_status_message("Fetching data...")
         self.panel.stockObj = stockInfo(prompt.GetValue())
         self.flash_status_message("Fetching data...Done")
         if not (self.panel.stockObj.validDate(self.panel.fromDate) and self.panel.stockObj.validDate(self.panel.toDate)):
             td = self.panel.stockObj.toDate - timedelta(weeks=DEFAULT_PERIOD)
             if self.panel.stockObj.validDate(td):
                 self.panel.fromDate = td
             else:
                 self.panel.fromDate = self.panel.stockObj.fromDate
             self.panel.toDate = self.panel.stockObj.toDate
             
         self.panel.Beta = Beta(self.panel.stockObj,self.panel.fromDate, self.panel.toDate)
         self.updateCurrentData()
         self.updateRSS()
         self.draw_figure()
     except ValueError:
         msg = wx.MessageDialog(self, "Invalid Ticker", "Error", wx.OK|wx.ICON_ERROR)
         msg.ShowModal()
         self.on_new(None)
예제 #3
0
    def on_new(self, event):
        """Handles creating new tickers"""
        prompt = wx.TextEntryDialog(self, "Enter new ticker", "New ticker",
                                    self.panel.stockObj.ticker)
        prompt.ShowModal()
        #Use this loop and recursion to ensure we get a legal value
        try:
            self.flash_status_message("Fetching data...")
            self.panel.stockObj = stockInfo(prompt.GetValue())
            self.flash_status_message("Fetching data...Done")
            if not (self.panel.stockObj.validDate(self.panel.fromDate)
                    and self.panel.stockObj.validDate(self.panel.toDate)):
                td = self.panel.stockObj.toDate - timedelta(
                    weeks=DEFAULT_PERIOD)
                if self.panel.stockObj.validDate(td):
                    self.panel.fromDate = td
                else:
                    self.panel.fromDate = self.panel.stockObj.fromDate
                self.panel.toDate = self.panel.stockObj.toDate

            self.panel.Beta = Beta(self.panel.stockObj, self.panel.fromDate,
                                   self.panel.toDate)
            self.updateCurrentData()
            self.updateRSS()
            self.draw_figure()
        except ValueError:
            msg = wx.MessageDialog(self, "Invalid Ticker", "Error",
                                   wx.OK | wx.ICON_ERROR)
            msg.ShowModal()
            self.on_new(None)
예제 #4
0
def updateStockInfo(stockList):
    filePath = sorted(os.listdir(constants.stockListPath), reverse=True)
    startTime = ''
    currentTime = filePath[0].replace('stockList_', '').replace('.csv', '')
    if len(filePath) > 1:
        startTime = filePath[1].replace('stockList_', '').replace('.csv', '')

    s = stockInfo()
    s.method(stockList, startTime, currentTime)
예제 #5
0
def infoPage(ticker):
    ticker = ticker  # place holder so AttributeError: NoneType isn't thrown on page load
    # functions to be passed as variables in jinja2 template
    info = stockInfo(ticker)
    news = stockNews(ticker)
    bio = stockBio(ticker)
    fin = stockFinancials(ticker)
    return render_template('stockInfo.html',
                           ticker=ticker,
                           news=news,
                           bio=bio,
                           info=info,
                           fin=fin)
예제 #6
0
def Bchange(args):
    """
    #Use: Bchange(args)
    #Pre: args is a list of strings, args[1] is a optional string that represents a ticker.
    #Post:The stockObject has been changed, to args[1] if provided and correct.
    """
    global stockObj
    if len(args) == 1:
        print "Please enter the ticker of the company/index you wish to check."
        while True:
            ticker = raw_input("Ticker: ")
            try:
                stockObj = stockInfo(ticker)
                print stockObj
                break
            except ValueError:
                print "Ticker '%s'  not found. Please enter valid ticker" % (ticker)
    else:
        try:
            stockObj = stockInfo(args[1])
            print stockObj
        except ValueError:
            print "Ticker '%s'  not found. Please enter valid ticker" % (args[1])
예제 #7
0
def Beta(s, fromDate=None, toDate=None):
    """
    # U: b=Beta(s,fd,td)
    # Pre: s is stockInfo object, fd, td are optional date objects
    # Post: b is a number describing our stock's Beta value for the time period from fromDate to toDate if data exists for those dates,
    # otherwise raises exception
    """
    if fromDate == None:
        fromDate = s.fromDate
    if toDate == None:
        toDate = s.toDate
    if not (s.validDate(fromDate) and s.validDate(toDate)):
        raise ValueError("Invalid dates")

    price = lambda d: d[6]

    def log_returns(l):
        """
        # U: l_r=log_returns(l)
        # Pre: l is a list of numbers, the length of which is n
        # Post: l_r is a list the length of which is one shorter than the length of l, where
        # l_r[k]=log(l[k]/l[k-1]) for k=1,...,n-1
        """
        l_r = []
        for i in range(1, len(l)):
            r = math.log(l[i] / l[i - 1])
            l_r.append(r)
        return l_r

    datelist = s.listFromTo(fromDate, toDate)
    pricelist = map(price, datelist)
    SP = stockInfo("^GSPC", fromDate, toDate)
    SPlist = SP.listFromTo(fromDate, toDate)
    SPprices = map(price, SPlist)
    r_a = log_returns(pricelist)
    r_b = log_returns(SPprices)
    cov_ab = cov(array(r_a), array(r_b))[0][
        1]  # We extract the covariance between r_a and r_b from the covariance matrix
    return round(cov_ab, 6) / round(
        var(array(r_b)),
        6)  #: some error in cov or var, we must round to get correct value
예제 #8
0
def Beta(s, fromDate=None, toDate=None):
    """
    # U: b=Beta(s,fd,td)
    # Pre: s is stockInfo object, fd, td are optional date objects
    # Post: b is a number describing our stock's Beta value for the time period from fromDate to toDate if data exists for those dates,
    # otherwise raises exception
    """
    if fromDate==None: 
        fromDate=s.fromDate
    if toDate==None:
        toDate=s.toDate
    if not (s.validDate(fromDate) and s.validDate(toDate)):
        raise ValueError("Invalid dates")
    
    price = lambda d: d[6]
    def log_returns(l):
        """
        # U: l_r=log_returns(l)
        # Pre: l is a list of numbers, the length of which is n
        # Post: l_r is a list the length of which is one shorter than the length of l, where
        # l_r[k]=log(l[k]/l[k-1]) for k=1,...,n-1
        """
        l_r=[]           
        for i in range(1,len(l)):
            r=math.log(l[i]/l[i-1])
            l_r.append(r)
        return l_r
        
    datelist=s.listFromTo(fromDate,toDate)
    pricelist=map(price, datelist)
    SP=stockInfo("^GSPC",fromDate,toDate)
    SPlist=SP.listFromTo(fromDate,toDate)
    SPprices=map(price,SPlist)
    r_a=log_returns(pricelist)
    r_b=log_returns(SPprices)
    cov_ab=cov(array(r_a),array(r_b))[0][1] # We extract the covariance between r_a and r_b from the covariance matrix   
    return round(cov_ab,6)/round(var(array(r_b)),6) #: some error in cov or var, we must round to get correct value
예제 #9
0
 def setUp(self):
     self.testobj = stockInfo("MSFT")
예제 #10
0
        # Pre: l is a list of numbers, the length of which is n
        # Post: l_r is a list the length of which is one shorter than the length of l, where
        # l_r[k]=log(l[k]/l[k-1]) for k=1,...,n-1
        """
        l_r = []
        for i in range(1, len(l)):
            r = math.log(l[i] / l[i - 1])
            l_r.append(r)
        return l_r

    datelist = s.listFromTo(fromDate, toDate)
    pricelist = map(price, datelist)
    SP = stockInfo("^GSPC", fromDate, toDate)
    SPlist = SP.listFromTo(fromDate, toDate)
    SPprices = map(price, SPlist)
    r_a = log_returns(pricelist)
    r_b = log_returns(SPprices)
    cov_ab = cov(array(r_a), array(r_b))[0][
        1]  # We extract the covariance between r_a and r_b from the covariance matrix
    return round(cov_ab, 6) / round(
        var(array(r_b)),
        6)  #: some error in cov or var, we must round to get correct value


if __name__ == "__main__":
    SP = stockInfo("^GSPC")
    print Beta(SP)
    #Google = stockInfo("GOOG",date(2000,1,1),date.today())
    #virkar ekki, getum ekki importad i hring.
    #smaPlot(Google,fromDate = date(2010,1,2), toDate = date(2011,1,2)).show()
예제 #11
0
    price = lambda d: d[6]
    def log_returns(l):
        """
        # U: l_r=log_returns(l)
        # Pre: l is a list of numbers, the length of which is n
        # Post: l_r is a list the length of which is one shorter than the length of l, where
        # l_r[k]=log(l[k]/l[k-1]) for k=1,...,n-1
        """
        l_r=[]           
        for i in range(1,len(l)):
            r=math.log(l[i]/l[i-1])
            l_r.append(r)
        return l_r
        
    datelist=s.listFromTo(fromDate,toDate)
    pricelist=map(price, datelist)
    SP=stockInfo("^GSPC",fromDate,toDate)
    SPlist=SP.listFromTo(fromDate,toDate)
    SPprices=map(price,SPlist)
    r_a=log_returns(pricelist)
    r_b=log_returns(SPprices)
    cov_ab=cov(array(r_a),array(r_b))[0][1] # We extract the covariance between r_a and r_b from the covariance matrix   
    return round(cov_ab,6)/round(var(array(r_b)),6) #: some error in cov or var, we must round to get correct value

if __name__ == "__main__":
    SP = stockInfo("^GSPC")
    print Beta(SP)
    #Google = stockInfo("GOOG",date(2000,1,1),date.today())
    #virkar ekki, getum ekki importad i hring.
    #smaPlot(Google,fromDate = date(2010,1,2), toDate = date(2011,1,2)).show()
예제 #12
0
                    ticker)
    else:
        try:
            stockObj = stockInfo(args[1])
            print stockObj
        except ValueError:
            print "Ticker '%s'  not found. Please enter valid ticker" % (
                args[1])


print "Welcome to Bangsimon Stocks!"
print "Please enter the ticker of the company/index you wish to check."
while True:
    ticker = raw_input("Ticker: ")
    try:
        stockObj = stockInfo(ticker)
        break
    except ValueError:
        print "%s ticker not found. Please enter valid ticker" % (ticker)

c = 'help'
print stockObj
commands = {
    'plot': Bplot,
    'help': Bhelp,
    'quit': Bquit,
    'change': Bchange,
    'current': Bcurrent,
    'beta': Bbeta,
    'ma': Bma,
    'news': Bnews
예제 #13
0
    def create_main_panel(self):
        """ Creates the main panel and everything"""

        self.panel = wx.Panel(self)
        self.panel.stockObj = stockInfo(DEFAULT_TICKER)
        
        #Put up some default values that are used in plot
        self.panel.currentAttr = "Adj Close"
        td = self.panel.stockObj.toDate - timedelta(weeks=DEFAULT_PERIOD)
        if self.panel.stockObj.validDate(td):
            self.panel.fromDate = td
        else:
            self.panel.fromDate = self.panel.stockObj.fromDate
            
        self.panel.toDate = self.panel.stockObj.toDate
        self.panel.MovingAvg = False
        self.panel.Volume = False
        self.panel.MovingAvgN = 20
        self.panel.Beta = Beta(self.panel.stockObj,self.panel.fromDate, self.panel.toDate)
       
        #adding the pllot
        self.fig = matplotlib.pyplot.gcf()
        self.canvas = FigCanvas(self.panel, -1, self.fig)
        
        #Add slider to change n of moving average
        self.slider_label = wx.StaticText(self.panel, -1, 
            "Moving Average N: ")
        self.slider_width = wx.Slider(self.panel, -1, 
            value=20, 
            minValue=20,
            maxValue=200,
            style=wx.SL_AUTOTICKS | wx.SL_LABELS)
        self.slider_width.SetTickFreq(10, 1)
        self.Bind(wx.EVT_COMMAND_SCROLL_THUMBTRACK, self.on_slider_width, self.slider_width)
        self.Bind(wx.EVT_COMMAND_SCROLL_CHANGED, self.on_slider_width, self.slider_width)

        #Toolbar of chart
        self.toolbar = NavigationToolbar(self.canvas)
        self.SetToolBar(self.toolbar)
        self.toolbar.Realize()#: Windows fix, does not work
       
        #We use boxes to get a dynamic layout
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 0, wx.LEFT | wx.TOP | wx.EXPAND)
        
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        flags = wx.ALIGN_LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL
        self.hbox.AddSpacer(30)
        self.hbox.Add(self.slider_label, 0, flag=flags)
        self.hbox.Add(self.slider_width, 1, border=3, flag=flags |wx.EXPAND)
        
        self.vbox.Add(self.hbox, 0, flag = wx.ALIGN_LEFT | wx.TOP| wx.EXPAND)

        self.vbox.AddSpacer(10)
        
        #Add NewsFeed
        self.RssBox = wx.BoxSizer(wx.VERTICAL)
        self.RssPanel = wx.lib.scrolledpanel.ScrolledPanel(self.panel)
        self.RssPanel.SetMinSize((-1,100))
        self.RssPanel.SetSizer(self.RssBox)
        self.updateRSS()
        
        self.RssBox.Fit(self.RssPanel)
        self.RssPanel.SetupScrolling()
        self.vbox.Add(self.RssPanel,1, flag= wx.EXPAND | wx.ALIGN_CENTER)
        self.panel.SetSizer(self.vbox)
        
        self.vbox.Fit(self)
        
        self.updateCurrentData()
예제 #14
0
                print "Ticker '%s'  not found. Please enter valid ticker" % (ticker)
    else:
        try:
            stockObj = stockInfo(args[1])
            print stockObj
        except ValueError:
            print "Ticker '%s'  not found. Please enter valid ticker" % (args[1])



print "Welcome to Bangsimon Stocks!"
print "Please enter the ticker of the company/index you wish to check."
while True:
    ticker = raw_input("Ticker: ")
    try:
        stockObj = stockInfo(ticker)
        break
    except ValueError:
        print "%s ticker not found. Please enter valid ticker" % (ticker)

c = 'help'
print stockObj
commands = {'plot': Bplot, 'help':Bhelp, 'quit':Bquit, 'change': Bchange, 'current':Bcurrent, 'beta':Bbeta, 'ma':Bma, 'news':Bnews} #: Dictionary of functions
Bhelp(['help'])
while c != "quit":
    c = raw_input(">> ")
    args = c.split()
    if len(args) >= 1:
        if args[0] not in commands:
            print "invalid command"
            continue
예제 #15
0
    def create_main_panel(self):
        """ Creates the main panel and everything"""

        self.panel = wx.Panel(self)
        self.panel.stockObj = stockInfo(DEFAULT_TICKER)

        #Put up some default values that are used in plot
        self.panel.currentAttr = "Adj Close"
        td = self.panel.stockObj.toDate - timedelta(weeks=DEFAULT_PERIOD)
        if self.panel.stockObj.validDate(td):
            self.panel.fromDate = td
        else:
            self.panel.fromDate = self.panel.stockObj.fromDate

        self.panel.toDate = self.panel.stockObj.toDate
        self.panel.MovingAvg = False
        self.panel.Volume = False
        self.panel.MovingAvgN = 20
        self.panel.Beta = Beta(self.panel.stockObj, self.panel.fromDate,
                               self.panel.toDate)

        #adding the pllot
        self.fig = matplotlib.pyplot.gcf()
        self.canvas = FigCanvas(self.panel, -1, self.fig)

        #Add slider to change n of moving average
        self.slider_label = wx.StaticText(self.panel, -1, "Moving Average N: ")
        self.slider_width = wx.Slider(self.panel,
                                      -1,
                                      value=20,
                                      minValue=20,
                                      maxValue=200,
                                      style=wx.SL_AUTOTICKS | wx.SL_LABELS)
        self.slider_width.SetTickFreq(10, 1)
        self.Bind(wx.EVT_COMMAND_SCROLL_THUMBTRACK, self.on_slider_width,
                  self.slider_width)
        self.Bind(wx.EVT_COMMAND_SCROLL_CHANGED, self.on_slider_width,
                  self.slider_width)

        #Toolbar of chart
        self.toolbar = NavigationToolbar(self.canvas)
        self.SetToolBar(self.toolbar)
        self.toolbar.Realize()  #: Windows fix, does not work

        #We use boxes to get a dynamic layout
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 0, wx.LEFT | wx.TOP | wx.EXPAND)

        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        flags = wx.ALIGN_LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL
        self.hbox.AddSpacer(30)
        self.hbox.Add(self.slider_label, 0, flag=flags)
        self.hbox.Add(self.slider_width, 1, border=3, flag=flags | wx.EXPAND)

        self.vbox.Add(self.hbox, 0, flag=wx.ALIGN_LEFT | wx.TOP | wx.EXPAND)

        self.vbox.AddSpacer(10)

        #Add NewsFeed
        self.RssBox = wx.BoxSizer(wx.VERTICAL)
        self.RssPanel = wx.lib.scrolledpanel.ScrolledPanel(self.panel)
        self.RssPanel.SetMinSize((-1, 100))
        self.RssPanel.SetSizer(self.RssBox)
        self.updateRSS()

        self.RssBox.Fit(self.RssPanel)
        self.RssPanel.SetupScrolling()
        self.vbox.Add(self.RssPanel, 1, flag=wx.EXPAND | wx.ALIGN_CENTER)
        self.panel.SetSizer(self.vbox)

        self.vbox.Fit(self)

        self.updateCurrentData()
예제 #16
0
        vol=lambda d: d[5]

        # create the second axis for the volume bar chart
        ax2 = ax.twinx()

        # set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
        ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.1],[0.9,0.32]]))

        # make bar charts and color differently depending on up/down for the day
        posList=[]
        negList=[]
        for i in infoList:
            if i[1]-i[4]<0:
                posList.append(i)
            else: negList.append(i)
        ax2.bar(map(date,posList),map(vol,posList),color='green',width=1,align='center')
        ax2.bar(map(date,negList),map(vol,negList),color='red',width=1,align='center')

        ax2.yaxis.set_label_position("right")
        ax2.set_ylabel('Volume')
    
    return fig


def smaPlot(s,N=20,fromDate=None,toDate=None):
    return stockPlot(s,"Adj Close",fromDate,toDate,True,N)
    
if __name__ == "__main__":
    Google = stockInfo("GOOG",date(2012,1,1),date.today())
    s = stockPlot(Google,'Adj Close',None,None,False,100,None,True)
예제 #17
0
 def test_Beta(self):
     with self.assertRaises(ValueError):
         Beta(self.testobj, date.min)
     self.assertIsInstance(Beta(self.testobj), float)
     SP500 = stockInfo("^GSPC")
     self.assertEqual(Beta(SP500), 1)
예제 #18
0
 def test_invalidcreation(self):
     with self.assertRaises(ValueError):
         otherobj = stockInfo("ThingThatDoesNotExist")
예제 #19
0
 def test_invalidcreation(self):
     with self.assertRaises(ValueError):
         otherobj = stockInfo("ThingThatDoesNotExist")
예제 #20
0
 def setUp(self):
     self.testobj = stockInfo("MSFT")
예제 #21
0
 def test_Beta(self):
     with self.assertRaises(ValueError):
         Beta(self.testobj,date.min)
     self.assertIsInstance(Beta(self.testobj),float)
     SP500 = stockInfo("^GSPC")
     self.assertEqual(Beta(SP500),1)