Ejemplo n.º 1
0
    def getTickPrices(self, symbol, startdate, enddate, intervalMins=60):
        """
        Get tick prices for the given ticker symbol.
        @symbol: stock symbol
        @interval: interval in mins(google finance only support query till 1 min)
        @startdate: start date(YYYYMMDD)
        @enddate: end date(YYYYMMDD)

        @Returns a nested list.
        """
        #TODO, parameter checking
        try:
            interval = int(
                intervalMins
            ) * 60 + 1  # plus one so that the time will show as 'a1316784600' instead of '1'
            startdate = string2EpochTime(startdate)
            enddate = string2EpochTime(enddate)
            period = enddate - startdate
            url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (
                symbol, interval, period, startdate)
            try:
                page = self.__request(url)
            except UfException as ufExcep:
                ##if symol is not right, will get 400
                if Errors.NETWORK_400_ERROR == ufExcep.getCode:
                    raise UfException(
                        Errors.STOCK_SYMBOL_ERROR,
                        "Can find data for stock %s, symbol error?" % symbol)
                raise ufExcep

            days = page.readlines()[7:]  # first 7 line is document
            # sample values:'a1316784600,31.41,31.5,31.4,31.43,150911'
            values = [day.split(',') for day in days]

            data = []
            for value in values:
                data.append(
                    StockDailyType(value[0][1:], value[4], value[2], value[3],
                                   value[1], value[5], None))

            return data

        except BaseException:
            raise UfException(
                Errors.UNKNOWN_ERROR,
                "Unknown Error in GoogleFinance.getHistoricalPrices %s" %
                traceback.format_exc())
Ejemplo n.º 2
0
    def __getTimeAndProfitList(self, latestStates):
        ''' get time and profit list '''
        timeAndProfitList = []
        preState = None
        if latestStates:
            for state in latestStates[::5]:
                if preState is not None:
                    timeAndProfitList.append([string2EpochTime(str(state['time'])) * 1000, float(state['account']) - float(preState['account'])])
                preState = state

        return timeAndProfitList
Ejemplo n.º 3
0
    def __getBackTestJson(self, resultName):
        ''' get one backtest result '''
        symbolOrNum, strategyName, startDate, endDate = self.__parseResultName(
            resultName)

        saver = self.__getSaver(resultName)
        latestStates = saver.getStates(0, None)

        metrics = saver.getMetrics()
        return {
            "symbolOrNum":
            symbolOrNum,
            "strategyName":
            strategyName,
            "startDate":
            startDate,
            "endDate":
            endDate,
            "metrics":
            metrics,
            "latestStates":
            latestStates,
            "timeAndPostionList": [[
                string2EpochTime(str(state['time'])) * 1000,
                float(state['account'])
            ] for state in latestStates] if latestStates else [],
            "timeAndHoldingList": [[
                string2EpochTime(str(state['time'])) * 1000,
                float(state['holdingValue']) /
                float(state['account']) if float(state['account']) != 0 else 0
            ] for state in latestStates] if latestStates else [],
            "timeAndProfitList":
            self.__getTimeAndProfitList(latestStates),
            "timeAndBenchmarkList": [[
                string2EpochTime(str(state['time'])) * 1000,
                float(state['indexPrice'])
            ] for state in latestStates] if latestStates else [],
            "holdings":
            metrics["endHoldings"]
        }
Ejemplo n.º 4
0
    def __getBackTestJson(self, resultName):
        ''' get one backtest result '''
        symbolOrNum, strategyName, startDate, endDate = self.__parseResultName(resultName)

        saver = self.__getSaver(resultName)
        latestStates = saver.getStates(0, None)

        metrics = saver.getMetrics()
        return {"symbolOrNum": symbolOrNum,
                "strategyName": strategyName,
                "startDate": startDate,
                "endDate": endDate,
                "metrics": metrics,
                "latestStates": latestStates,
                "timeAndPostionList": [[string2EpochTime(str(state['time'])) * 1000, float(state['account'])]
                                       for state in latestStates] if latestStates else [],
                "timeAndHoldingList": [[string2EpochTime(str(state['time'])) * 1000, float(state['holdingValue']) / float(state['account']) if float(state['account']) != 0 else 0]
                                       for state in latestStates] if latestStates else [],
                "timeAndProfitList": self.__getTimeAndProfitList(latestStates),
                "timeAndBenchmarkList": [[string2EpochTime(str(state['time'])) * 1000, float(state['indexPrice'])]
                                         for state in latestStates] if latestStates else [],
                "holdings": metrics["endHoldings"]}
Ejemplo n.º 5
0
    def __getTimeAndProfitList(self, latestStates):
        ''' get time and profit list '''
        timeAndProfitList = []
        preState = None
        if latestStates:
            for state in latestStates[::5]:
                if preState is not None:
                    timeAndProfitList.append([
                        string2EpochTime(str(state['time'])) * 1000,
                        float(state['account']) - float(preState['account'])
                    ])
                preState = state

        return timeAndProfitList
Ejemplo n.º 6
0
    def getTickPrices(self, symbol, startdate, enddate, intervalMins=60):
        """
        Get tick prices for the given ticker symbol.
        @symbol: stock symbol
        @interval: interval in mins(google finance only support query till 1 min)
        @startdate: start date(YYYYMMDD)
        @enddate: end date(YYYYMMDD)

        @Returns a nested list.
        """
        #TODO, parameter checking
        try:
            interval = int(intervalMins) * 60 + 1 # plus one so that the time will show as 'a1316784600' instead of '1'
            startdate = string2EpochTime(startdate)
            enddate = string2EpochTime(enddate)
            period = enddate - startdate
            url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (symbol, interval, period, startdate)
            try:
                page = self.__request(url)
            except UfException as ufExcep:
                ##if symol is not right, will get 400
                if Errors.NETWORK_400_ERROR == ufExcep.getCode:
                    raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, symbol error?" % symbol)
                raise ufExcep

            days = page.readlines()[7:] # first 7 line is document
            # sample values:'a1316784600,31.41,31.5,31.4,31.43,150911'
            values = [day.split(',') for day in days]

            data = []
            for value in values:
                data.append(StockDailyType(value[0][1:], value[4], value[2], value[3], value[1], value[5], None))

            return data

        except BaseException:
            raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc())