コード例 #1
0
    def fetchPriceHistory(self, dialog):
        """Parse the text in the input box"""
        stockstr = self.m_symbolinput.Value.encode('ascii')
        stocks = stockstr.split(",")
        stocks = [s.strip() for s in stocks]
        """Get the historical prices and
		create a new Asset object for each stock symbol"""
        curSymbols = [a.symbol for a in self.portfolio.assets]
        inc = 100 / len(stocks)
        i = 0
        for s in stocks:
            if s not in curSymbols:
                wx.CallAfter(dialog.Update, i * inc,
                             "Fetching %s historical data" % (s))
                i = i + 1
                try:
                    prices = u.getHistoricalPrices(s)
                    asset = fin.Asset(s, prices)
                    self.portfolio.addAsset(asset)
                except:
                    message = "Could not find data for %s \n Perhaps it's not a real stock symbol?" % (
                        s)
                    wx.MessageBox(message, 'Error',
                                  wx.OK | wx.ICON_INFORMATION)
                    continue

        self.m_symbolinput.SetValue("")
        self.updateGridSymbols()
        wx.CallAfter(dialog.Destroy)
コード例 #2
0
	def fetchPriceHistory(self, dialog):
		"""Parse the text in the input box"""
		stockstr = self.m_symbolinput.Value.encode('ascii')
		stocks = stockstr.split(",")
		stocks = [s.strip() for s in stocks]
		
		"""Get the historical prices and
		create a new Asset object for each stock symbol"""
		curSymbols = [a.symbol for a in self.portfolio.assets]
		inc = 100/len(stocks)
		i = 0
		for s in stocks:
			if s not in curSymbols:
				wx.CallAfter(dialog.Update, i*inc, "Fetching %s historical data"%(s))
				i = i+1
				try:
					prices = u.getHistoricalPrices(s)
					asset = fin.Asset(s, prices)
					self.portfolio.addAsset(asset)
				except:
					message = "Could not find data for %s \n Perhaps it's not a real stock symbol?"%(s)			
					wx.MessageBox(message, 'Error', wx.OK | wx.ICON_INFORMATION)
					continue
				
		self.m_symbolinput.SetValue("")
		self.updateGridSymbols()
		wx.CallAfter(dialog.Destroy)
コード例 #3
0
    def calculateGrid(self):
        colcount = self.m_stocklist.ColumnCount
        if colcount < 4:
            self.m_stocklist.InsertColumn(0, "Symbol")
            self.m_stocklist.InsertColumn(1, "Mean Rate")
            self.m_stocklist.InsertColumn(2, "Std. Deviation", width=120)
            self.m_stocklist.InsertColumn(3, "Allocation")
            self.m_stocklist.InsertColumn(4, "Correlation")
            self.m_stocklist.InsertColumn(5, "Beta")
            self.m_stocklist.InsertColumn(6, "Sharpe Ratio")

        if len(self.portfolio.assets) != 0:
            MRAprices = u.getHistoricalPrices("SPY")
            marketRetAsset = fin.Asset("SPY", MRAprices)
            rfr = self.m_rfRadBox.GetStringSelection()

            rfRates = u.getHistoricalRates(rfr)
            mrRates = marketRetAsset.getRatesOfReturn(
                self.portfolio.startdate, self.portfolio.ratemethod)
            dates = u.date_range(self.portfolio.startdate)
            meanrates = []
            ratesmatrix = []
            sharpes = {}
            for asset in self.portfolio.assets:
                rates = asset.getRatesOfReturn(self.portfolio.startdate,
                                               self.portfolio.ratemethod)
                rateBundle = []
                for d in dates:
                    if rfRates.has_key(d) and mrRates.has_key(
                            d) and rates.has_key(d):
                        rateBundle.append((rates[d], rfRates[d], mrRates[d]))

                asset.correlation = asset.getCorrelation(rateBundle)
                asset.beta = asset.getBeta(rateBundle, asset.correlation)
                asset.sharpe = asset.getSharpe(rateBundle)

                mostrecentrfr = max(rfRates.keys())
                if self.portfolio.returnmethod == "CAPM":
                    marketrr = float(self.m_marketReturnRate.Value)
                    """We are multiplying percentages by 100 (for displaying) but then we continue to use the standard deviations."""
                    mean = asset.getMeanROR(rates,
                                            annualized=False,
                                            returnmethod="CAPM",
                                            marketrate=marketrr,
                                            rfrate=rfRates[mostrecentrfr],
                                            B=asset.beta)
                else:
                    mean = asset.getMeanROR(rates,
                                            annualized=False,
                                            returnmethod="Historical")
                asset.rates = rates
                asset.mean = mean
                """ This will make annmeans a percentage of a percentage of annualized means?
					SHOULDN'T BE USING ANNUALIZED FOR OPTIMIZATION?"""
                """annmeans.append(annmean/10000)"""
                meanrates.append(mean)

                sharpes[asset] = asset.sharpe

                ratesmatrix.append(rateBundle)

            self.portfolio.ratesmatrix = ratesmatrix
            cormatrix = self.portfolio.getMatrix(ratesmatrix)
            self.portfolio.cormatrix = cormatrix
            cvmatrix, stdmarket = self.portfolio.getMatrix(
                ratesmatrix, "covariance")
            self.portfolio.cvmatrix = cvmatrix
            self.portfolio.stdmarket = stdmarket
            self.portfolio.meanrates = meanrates

            if self.m_allocRads.GetSelection() == 1:
                #results = u.optimizePortfolio(self.portfolio, step=0.001)
                results = u.efficientFrontier(self.portfolio, step=0.0001)

                self.portfolio.optimizationResults = results

                e = min([res['ExpectedReturn'] for res in results])

                minrisk = 10000000
                optimalSolution = None
                for s in results:
                    tempweights = []
                    for asset in self.portfolio.assets:
                        tempweights.extend([
                            w['Allocation'] for w in s['Results']
                            if w['Symbol'] == asset.symbol
                        ])

                    tempwsharpe = 0
                    i = 0
                    for asset in self.portfolio.assets:
                        tempwsharpe += sharpes[asset] * tempweights[i]
                        i = i + 1
                    print "Weighted Sharpe:"
                    print tempwsharpe

                    tempwcovwithmarket = self.portfolio.getWeightedCovariance(
                        cvmatrix, tempweights, True)
                    tempwvar = self.portfolio.getWeightedCovariance(
                        cvmatrix, tempweights, False)
                    """ getWeightedReturn annualizes the data. I think this means we end up annualizing it twice."""
                    tempwrr = self.portfolio.getWeightedReturn(
                        meanrates, tempweights) * 100
                    tempwcor = self.portfolio.getWeightedCorrelation(
                        tempwcovwithmarket, tempwvar, stdmarket)
                    tempwbeta = self.portfolio.getWeightedBeta(
                        tempwcor, tempwvar, stdmarket)
                    tempwstd = num.sqrt(tempwvar) * num.sqrt(252) * 100
                    if tempwstd < minrisk:
                        i = 0
                        for asset in self.portfolio.assets:
                            asset.weight = tempweights[i]
                            i = i + 1

                        minrisk = tempwstd
                        wrr = tempwrr
                        wcor = tempwcor
                        wbeta = tempwbeta
                        wstd = tempwstd
                        wsharpe = tempwsharpe

                self.m_EFbutton.Show()
                self.m_allocations.Show()
                self.SetSize((self.GetSize().width, self.GetSize().height + 1))
                self.SetSize((self.GetSize().width, self.GetSize().height - 1))
            else:
                weights = [a.weight for a in reversed(self.portfolio.assets)]
                wsharpe = 0
                i = 0
                for asset in self.portfolio.assets:
                    wsharpe += sharpes[asset] * weights[i]
                    i = i + 1
                print "Weighted Sharpe:"
                print wsharpe
                covwithmarket = self.portfolio.getWeightedCovariance(
                    cvmatrix, weights, True)
                wvar = self.portfolio.getWeightedCovariance(
                    cvmatrix, weights, False)
                wrr = self.portfolio.getWeightedReturn(meanrates,
                                                       weights) * 100
                wcor = self.portfolio.getWeightedCorrelation(
                    covwithmarket, wvar, stdmarket)
                wbeta = self.portfolio.getWeightedBeta(wcor, wvar, stdmarket)
                wstd = num.sqrt(wvar) * num.sqrt(252) * 100
                self.m_EFbutton.Hide()

            #wrr = wsharpe*wstd
            """
			print "Weighted annualized mean return rate?"
			print wrr
			print "Weight standard deviation:"
			print wstd
			"""

            for asset in self.portfolio.assets:
                pos = self.m_stocklist.FindItem(-1, asset.symbol)
                """We're for displaying! ANd only displaying!"""
                annmean = 100 * 252 * asset.mean
                annstd = 100 * asset.getStd(asset.rates, annualized=True)
                if pos == -1:
                    pos = self.m_stocklist.ItemCount
                    self.m_stocklist.InsertStringItem(pos, asset.symbol)
                    self.m_stocklist.SetStringItem(0, 1,
                                                   str("%.2f" % asset.weight))
                    self.m_stocklist.SetStringItem(pos, 2,
                                                   str("%.2f" % annmean) + "%")
                    self.m_stocklist.SetStringItem(pos, 3,
                                                   str("%.2f" % annstd) + "%")
                    self.m_stocklist.SetStringItem(
                        pos, 4, str("%.2f" % asset.correlation))
                    self.m_stocklist.SetStringItem(pos, 5,
                                                   str("%.2f" % asset.beta))
                    self.m_stocklist.SetStringItem(pos, 6,
                                                   str("%.2f" % asset.sharpe))
                else:
                    self.m_stocklist.SetStringItem(pos, 1,
                                                   str("%.2f" % asset.weight))
                    self.m_stocklist.SetStringItem(pos, 2,
                                                   str("%.2f" % annmean) + "%")
                    self.m_stocklist.SetStringItem(pos, 3,
                                                   str("%.2f" % annstd) + "%")
                    self.m_stocklist.SetStringItem(
                        pos, 4, str("%.2f" % asset.correlation))
                    self.m_stocklist.SetStringItem(pos, 5,
                                                   str("%.2f" % asset.beta))
                    self.m_stocklist.SetStringItem(pos, 6,
                                                   str("%.2f" % asset.sharpe))

            self.m_portfoliolist.SetStringItem(0, 1, str("%.2f" % 1.00))
            self.m_portfoliolist.SetStringItem(0, 2, str("%.2f" % wrr) + "%")
            self.m_portfoliolist.SetStringItem(0, 3, str("%.2f" % wstd) + "%")
            self.m_portfoliolist.SetStringItem(0, 4, str("%.2f" % wcor))
            self.m_portfoliolist.SetStringItem(0, 5, str("%.2f" % wbeta))
            self.m_portfoliolist.SetStringItem(0, 6, str("%.2f" % wsharpe))

            assets = []
            assets.extend(self.portfolio.assets)
            assets.append(marketRetAsset)
            grid = self.m_corgrid
            grid.ClearGrid()
            while self.m_corgrid.NumberRows != 0:
                self.m_corgrid.DeleteCols()
                self.m_corgrid.DeleteRows()

            grid.AppendCols(len(assets))
            grid.AppendRows(len(assets))
            i = 0
            for asset in assets:
                self.m_corgrid.SetRowLabelValue(i, asset.symbol)
                self.m_corgrid.SetColLabelValue(i, asset.symbol)
                asset.covariances = {}
                i = i + 1

            for i in range(len(assets)):
                for j in range(len(assets)):
                    self.m_corgrid.SetCellValue(i, j,
                                                str("%.2f" % cormatrix[i][j]))
コード例 #4
0
	def calculateGrid(self):
		colcount = self.m_stocklist.ColumnCount
		if colcount < 4:
			self.m_stocklist.InsertColumn(0, "Symbol")
			self.m_stocklist.InsertColumn(1, "Mean Rate")
			self.m_stocklist.InsertColumn(2, "Std. Deviation", width=120)
			self.m_stocklist.InsertColumn(3, "Allocation")
			self.m_stocklist.InsertColumn(4, "Correlation")
			self.m_stocklist.InsertColumn(5, "Beta")
			self.m_stocklist.InsertColumn(6, "Sharpe Ratio")
		
		if len(self.portfolio.assets) != 0:	
			MRAprices = u.getHistoricalPrices("SPY")
			marketRetAsset = fin.Asset("SPY", MRAprices)
			rfr = self.m_rfRadBox.GetStringSelection()
			
			rfRates = u.getHistoricalRates(rfr)
			mrRates = marketRetAsset.getRatesOfReturn(self.portfolio.startdate, self.portfolio.ratemethod)
			dates = u.date_range(self.portfolio.startdate)
			meanrates = []
			ratesmatrix = []
			sharpes = {}
			for asset in self.portfolio.assets:
				rates = asset.getRatesOfReturn(self.portfolio.startdate, self.portfolio.ratemethod)
				rateBundle = []
				for d in dates:
					if rfRates.has_key(d) and mrRates.has_key(d) and rates.has_key(d):
						rateBundle.append((rates[d],rfRates[d],mrRates[d]))
										
				asset.correlation = asset.getCorrelation(rateBundle)
				asset.beta = asset.getBeta(rateBundle, asset.correlation)
				asset.sharpe = asset.getSharpe(rateBundle)
				
				mostrecentrfr = max(rfRates.keys())
				if self.portfolio.returnmethod=="CAPM":	
					marketrr = float(self.m_marketReturnRate.Value)
					"""We are multiplying percentages by 100 (for displaying) but then we continue to use the standard deviations."""
					mean = asset.getMeanROR(rates, annualized=False, returnmethod="CAPM", marketrate=marketrr, rfrate=rfRates[mostrecentrfr], B=asset.beta)
				else:
					mean = asset.getMeanROR(rates, annualized=False, returnmethod="Historical")
				asset.rates =rates
				asset.mean = mean
				
				""" This will make annmeans a percentage of a percentage of annualized means?
					SHOULDN'T BE USING ANNUALIZED FOR OPTIMIZATION?"""
				"""annmeans.append(annmean/10000)"""
				meanrates.append(mean)
			
				sharpes[asset] = asset.sharpe
				
				ratesmatrix.append(rateBundle)
	
			
			self.portfolio.ratesmatrix = ratesmatrix
			cormatrix = self.portfolio.getMatrix(ratesmatrix)
			self.portfolio.cormatrix = cormatrix
			cvmatrix,stdmarket = self.portfolio.getMatrix(ratesmatrix, "covariance")
			self.portfolio.cvmatrix = cvmatrix
			self.portfolio.stdmarket = stdmarket
			self.portfolio.meanrates = meanrates
			
			if self.m_allocRads.GetSelection() == 1:
				#results = u.optimizePortfolio(self.portfolio, step=0.001)
				results = u.efficientFrontier(self.portfolio, step=0.0001)
				
				self.portfolio.optimizationResults = results
				
				e = min([res['ExpectedReturn'] for res in results])
				
				minrisk = 10000000
				optimalSolution = None
				for s in results:		
					tempweights = []
					for asset in self.portfolio.assets:
							tempweights.extend([w['Allocation'] for w in s['Results'] if w['Symbol'] == asset.symbol])
				
					tempwsharpe = 0
					i=0
					for asset in self.portfolio.assets:
						tempwsharpe += sharpes[asset]*tempweights[i]
						i=i+1
					print "Weighted Sharpe:"
					print tempwsharpe
					
					tempwcovwithmarket = self.portfolio.getWeightedCovariance(cvmatrix, tempweights, True)
					tempwvar = self.portfolio.getWeightedCovariance(cvmatrix, tempweights, False)
					""" getWeightedReturn annualizes the data. I think this means we end up annualizing it twice."""
					tempwrr = self.portfolio.getWeightedReturn(meanrates, tempweights)*100
					tempwcor = self.portfolio.getWeightedCorrelation(tempwcovwithmarket,tempwvar,stdmarket)
					tempwbeta = self.portfolio.getWeightedBeta(tempwcor, tempwvar,stdmarket)
					tempwstd = num.sqrt(tempwvar)*num.sqrt(252)*100
					if tempwstd<minrisk:
						i=0
						for asset in self.portfolio.assets:
							asset.weight =tempweights[i]
							i = i+1
						
						minrisk=tempwstd
						wrr = tempwrr
						wcor = tempwcor
						wbeta = tempwbeta
						wstd=tempwstd
						wsharpe=tempwsharpe
						
						
				self.m_EFbutton.Show()
				self.m_allocations.Show()
				self.SetSize((self.GetSize().width, self.GetSize().height+1))
				self.SetSize((self.GetSize().width, self.GetSize().height-1))
			else:
				weights = [a.weight for a in reversed(self.portfolio.assets)]
				wsharpe = 0
				i=0
				for asset in self.portfolio.assets:
					wsharpe += sharpes[asset]*weights[i]
					i=i+1
				print "Weighted Sharpe:"
				print wsharpe
				covwithmarket = self.portfolio.getWeightedCovariance(cvmatrix, weights, True)
				wvar = self.portfolio.getWeightedCovariance(cvmatrix, weights, False)
				wrr = self.portfolio.getWeightedReturn(meanrates, weights)*100
				wcor = self.portfolio.getWeightedCorrelation(covwithmarket,wvar,stdmarket)
				wbeta = self.portfolio.getWeightedBeta(wcor, wvar,stdmarket)
				wstd = num.sqrt(wvar)*num.sqrt(252)*100
				self.m_EFbutton.Hide()
			
			#wrr = wsharpe*wstd
			"""
			print "Weighted annualized mean return rate?"
			print wrr
			print "Weight standard deviation:"
			print wstd
			"""
			
			for asset in self.portfolio.assets:
				pos = self.m_stocklist.FindItem(-1, asset.symbol)	
				"""We're for displaying! ANd only displaying!"""
				annmean = 100*252*asset.mean
				annstd = 100 * asset.getStd(asset.rates, annualized=True)
				if pos ==-1:
					pos = self.m_stocklist.ItemCount
					self.m_stocklist.InsertStringItem(pos, asset.symbol)
					self.m_stocklist.SetStringItem(0,1, str("%.2f" %  asset.weight))
					self.m_stocklist.SetStringItem(pos,2, str("%.2f" % annmean)+"%")
					self.m_stocklist.SetStringItem(pos,3, str("%.2f" % annstd)+"%")
					self.m_stocklist.SetStringItem(pos,4, str("%.2f" % asset.correlation))
					self.m_stocklist.SetStringItem(pos,5, str("%.2f" % asset.beta))
					self.m_stocklist.SetStringItem(pos,6, str("%.2f" % asset.sharpe))
				else:
					self.m_stocklist.SetStringItem(pos,1, str("%.2f" % asset.weight))
					self.m_stocklist.SetStringItem(pos,2, str("%.2f" % annmean)+"%")
					self.m_stocklist.SetStringItem(pos,3, str("%.2f" % annstd)+"%")
					self.m_stocklist.SetStringItem(pos,4, str("%.2f" % asset.correlation))
					self.m_stocklist.SetStringItem(pos,5, str("%.2f" % asset.beta))
					self.m_stocklist.SetStringItem(pos,6, str("%.2f" % asset.sharpe))
			
			self.m_portfoliolist.SetStringItem(0,1, str("%.2f" % 1.00))
			self.m_portfoliolist.SetStringItem(0,2, str("%.2f" % wrr)+"%")
			self.m_portfoliolist.SetStringItem(0,3, str("%.2f" % wstd)+"%")
			self.m_portfoliolist.SetStringItem(0,4, str("%.2f" % wcor))
			self.m_portfoliolist.SetStringItem(0,5, str("%.2f" % wbeta))
			self.m_portfoliolist.SetStringItem(0,6, str("%.2f" % wsharpe))
			
			assets = []
			assets.extend(self.portfolio.assets)
			assets.append(marketRetAsset)
			grid = self.m_corgrid
			grid.ClearGrid()
			while self.m_corgrid.NumberRows != 0:
				self.m_corgrid.DeleteCols()
				self.m_corgrid.DeleteRows()

			grid.AppendCols(len(assets))
			grid.AppendRows(len(assets))
			i = 0
			for asset in assets:
				self.m_corgrid.SetRowLabelValue(i, asset.symbol)
				self.m_corgrid.SetColLabelValue(i, asset.symbol)
				asset.covariances = {}
				i = i+1
							
			for i in range(len(assets)):
				for j in range(len(assets)):
					self.m_corgrid.SetCellValue(i, j, str("%.2f" % cormatrix[i][j]))