コード例 #1
0
ファイル: resamplebase.py プロジェクト: zxlstoner/pyalgotrade
    def __init__(self, dateTime, frequency):
        assert isinstance(frequency, int)
        assert frequency > 1
        assert frequency < bar.Frequency.DAY

        ts = int(dt.datetime_to_timestamp(dateTime))
        slot = int(ts / frequency)
        slotTs = slot * frequency
        self.__begin = dt.timestamp_to_datetime(slotTs, not dt.datetime_is_naive(dateTime))
        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
        self.__end = self.__begin + datetime.timedelta(seconds=frequency)
コード例 #2
0
    def __init__(self, dateTime, frequency):
        super(IntraDayRange, self).__init__()
        assert isinstance(frequency, int)
        assert frequency > 1
        assert frequency < bar.Frequency.DAY

        ts = int(dt.datetime_to_timestamp(dateTime))
        # slot = ts / frequency # 从31分开始计算
        # slotTs = slot * frequency
        self.__begin = dt.timestamp_to_datetime(
            ts, not dt.datetime_is_naive(dateTime))
        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
        self.__end = self.__begin + \
            datetime.timedelta(seconds=(frequency - bar.Frequency.MINUTE))  # 获取最后一个bar数据时截止
        self.isFirtstCheckingNearly = True
コード例 #3
0
    def testFeedWithQuandl(self):
        class RowFilter(csvfeed.RowFilter):
            def includeRow(self, dateTime, values):
                return dateTime.year == 2013

        feed = csvfeed.Feed("Date", "%Y-%m-%d", maxLen=40, timezone=marketsession.USEquities.timezone)
        feed.setRowFilter(RowFilter())
        feed.setTimeDelta(datetime.timedelta(hours=23, minutes=59, seconds=59))
        feed.addValuesFromCSV(common.get_data_file_path("quandl_gold_2.csv"))

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 0)

        dispatcher = observer.Dispatcher()
        dispatcher.addSubject(feed)
        dispatcher.run()

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 39)

        self.assertEqual(feed["USD"][-1], 1333.0)
        self.assertEqual(feed["GBP"][-1], 831.203)
        self.assertEqual(feed["EUR"][-1], 986.75)
        self.assertFalse(dt.datetime_is_naive(feed["USD"].getDateTimes()[-1]))
        self.assertEqual(feed["USD"].getDateTimes()[-1], dt.localize(datetime.datetime(2013, 9, 29, 23, 59, 59), marketsession.USEquities.timezone))
コード例 #4
0
 def testWithPerFileTimezone(self):
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone())
     barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.getTimezone())
     for dateTime, bars in barFeed:
         bar = bars.getBar(FeedTestCase.TestInstrument)
         self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
コード例 #5
0
ファイル: api.py プロジェクト: Greenwicher/pyalgotrade
def XigniteGlobalRealTime_GetBar(token, identifier, identifierType, endDateTime, precision, period, secureRequest=None):
    if dt.datetime_is_naive(endDateTime):
        raise Exception("endDateTime must have a timezone")

    # Parse the exchange from the identifier.
    instrument, exchange = parse_instrument_exchange(identifier)

    if secureRequest is None:
        secureRequest = USE_SECURE_REQUESTS

    if secureRequest:
        scheme = "https"
    else:
        scheme = "http"

    # print datetime_to_string(endDateTime, exchange)
    params = {
        "_Token": token,
        "Identifier": identifier,
        "IdentifierType": identifierType,
        "EndTime": datetime_to_string(endDateTime, exchange),
        "Precision": precision,
        "Period": period,
    }
    parts = (scheme, "globalrealtime.xignite.com", "v3/xGlobalRealTime.json/GetBar", urllib.urlencode(params), "")
    url = urlparse.urlunsplit(parts)

    ret = json_http_request(url)
    if ret.get("Outcome") != "Success":
        msg = ret.get("Message")
        if msg is None:
            msg = "Error %s" % (ret.get("Outcome"))
        raise XigniteError(msg, ret)

    return ret
コード例 #6
0
 def testWithoutTimezone(self):
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(INSTRUMENT, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     barFeed.addBarsFromCSV(INSTRUMENT, common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     for dateTime, bars in barFeed:
         bar = bars.getBar(INSTRUMENT)
         self.assertTrue(dt.datetime_is_naive(bar.getDateTime()))
コード例 #7
0
 def testWithoutTimezone(self):
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     for dateTime, bars in barFeed:
         bar = bars.getBar(YahooTestCase.TestInstrument)
         self.assertTrue(dt.datetime_is_naive(bar.getDateTime()))
コード例 #8
0
ファイル: yahoofeed_test.py プロジェクト: heber/pyalgotrade
 def testWithPerFileTimezone(self):
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.getTimezone())
     barFeed.addBarsFromCSV(FeedTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.getTimezone())
     for dateTime, bars in barFeed:
         bar = bars.getBar(FeedTestCase.TestInstrument)
         self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
コード例 #9
0
 def testWithDefaultTimezone(self):
     barFeed = yahoofeed.Feed(timezone=marketsession.USEquities.getTimezone())
     barFeed.addBarsFromCSV(INSTRUMENT, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     barFeed.addBarsFromCSV(INSTRUMENT, common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     for dateTime, bars in barFeed:
         bar = bars.getBar(INSTRUMENT)
         self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
コード例 #10
0
    def testFeedWithQuandl(self):
        class RowFilter(csvfeed.RowFilter):
            def includeRow(self, dateTime, values):
                return dateTime.year == 2013

        feed = csvfeed.Feed("Date",
                            "%Y-%m-%d",
                            maxLen=40,
                            timezone=marketsession.USEquities.timezone)
        feed.setRowFilter(RowFilter())
        feed.setTimeDelta(datetime.timedelta(hours=23, minutes=59, seconds=59))
        feed.addValuesFromCSV(common.get_data_file_path("quandl_gold_2.csv"))

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 0)

        dispatcher = observer.Dispatcher()
        dispatcher.addSubject(feed)
        dispatcher.run()

        for col in ["USD", "GBP", "EUR"]:
            self.assertEqual(len(feed[col]), 39)

        self.assertEqual(feed["USD"][-1], 1333.0)
        self.assertEqual(feed["GBP"][-1], 831.203)
        self.assertEqual(feed["EUR"][-1], 986.75)
        self.assertFalse(dt.datetime_is_naive(feed["USD"].getDateTimes()[-1]))
        self.assertEqual(
            feed["USD"].getDateTimes()[-1],
            dt.localize(datetime.datetime(2013, 9, 29, 23, 59, 59),
                        marketsession.USEquities.timezone))
コード例 #11
0
 def __init__(self, dateTime):
     super(DayRange, self).__init__()
     self.__begin = datetime.datetime(dateTime.year, dateTime.month,
                                      dateTime.day)
     if not dt.datetime_is_naive(dateTime):
         self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
     self.__end = self.__begin + datetime.timedelta(days=1)
コード例 #12
0
def get_slot_datetime(dateTime, frequency):
    ts = dt.datetime_to_timestamp(dateTime)
    slot = ts / frequency
    slotTs = (slot + 1) * frequency - 1
    ret = dt.timestamp_to_datetime(slotTs, False)
    if not dt.datetime_is_naive(dateTime):
        ret = dt.localize(ret, dateTime.tzinfo)
    return ret
コード例 #13
0
	def testWithoutTimezone(self):
		barFeed = self.__loadIntradayBarFeed(None)
		ds = barFeed.getDataSeries()

		for i in xrange(ds.getLength()):
			currentBar = ds.getValueAbsolute(i)
			# Datetime must be set to UTC.
			self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
コード例 #14
0
	def testWithTimezone(self):
		timeZone = marketsession.USEquities.getTimezone()
		barFeed = self.__loadIntradayBarFeed(timeZone)
		ds = barFeed.getDataSeries()

		for i in xrange(ds.getLength()):
			currentBar = ds.getValueAbsolute(i)
			self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
コード例 #15
0
    def __init__(self, dateTime):
        super(CtpDayRange, self).__init__()
        self.__initBegin(dateTime)

        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
        self.__end = self.__begin.replace(hour=15, minute=0) + BDay()
        self.isFirtstCheckingNearly = True
コード例 #16
0
    def testWithoutTimezone(self):
        barFeed = self.__loadIntradayBarFeed(None)
        ds = barFeed.getDataSeries()

        for i in xrange(ds.getLength()):
            currentBar = ds.getValueAbsolute(i)
            # Datetime must be set to UTC.
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
コード例 #17
0
    def testWithTimezone(self):
        timeZone = marketsession.USEquities.getTimezone()
        barFeed = self.__loadIntradayBarFeed(timeZone)
        ds = barFeed.getDataSeries()

        for i in xrange(ds.getLength()):
            currentBar = ds.getValueAbsolute(i)
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
コード例 #18
0
    def testWithoutTimezone(self):
        barFeed = self.__loadIntradayBarFeed(None)
        ds = barFeed.getDataSeries(INSTRUMENT)

        for i, currentBar in enumerate(ds):
            # Datetime must be set to UTC.
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
            self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i])
コード例 #19
0
    def testWithoutTimezone(self):
        barFeed = self.__loadIntradayBarFeed(None)
        ds = barFeed.getDataSeries()

        for i, currentBar in enumerate(ds):
            # Datetime must be set to UTC.
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
            self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i])
コード例 #20
0
ファイル: resampled.py プロジェクト: imoran21/Pyalgo-Django
def get_slot_datetime(dateTime, frequency):
	ts = dt.datetime_to_timestamp(dateTime)
	slot = ts / frequency
	slotTs = (slot + 1) * frequency - 1
	ret = dt.timestamp_to_datetime(slotTs, False)
	if not dt.datetime_is_naive(dateTime):
		ret = dt.localize(ret, dateTime.tzinfo)
	return ret
コード例 #21
0
    def testWithTimezone(self):
        timeZone = marketsession.USEquities.getTimezone()
        barFeed = self.__loadIntradayBarFeed(timeZone)
        ds = barFeed.getDataSeries(INSTRUMENT)

        for i, currentBar in enumerate(ds):
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
            self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i])
コード例 #22
0
    def testWithTimezone(self):
        timeZone = marketsession.USEquities.getTimezone()
        barFeed = self.__loadIntradayBarFeed(timeZone)
        ds = barFeed.getDataSeries()

        for i, currentBar in enumerate(ds):
            self.assertFalse(dt.datetime_is_naive(currentBar.getDateTime()))
            self.assertEqual(ds[i].getDateTime(), ds.getDateTimes()[i])
コード例 #23
0
 def __init__(self, dateTime):
     super(CtpWeekRange, self).__init__()
     self.__begin = dateTime - datetime.timedelta(days=dateTime.weekday())
     self.__initBegin(self.__begin)
     self.__end = self.__begin.replace(hour=15) + datetime.timedelta(days=6)
     self.isFirtstCheckingNearly = True
     if not dt.datetime_is_naive(dateTime):
         self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
         self.__end = dt.localize(self.__end, dateTime.tzinfo)
コード例 #24
0
    def testWithTimezone(self):
        timeZone = marketsession.USEquities.getTimezone()
        barFeed = self.__loadIntradayBarFeed(timeZone)
        ds = barFeed.getDataSeries()

        for i in xrange(ds.getLength()):
            currentBar = ds[i]
            assert not dt.datetime_is_naive(currentBar.getDateTime())
            assert ds[i].getDateTime() == ds.getDateTimes()[i]
コード例 #25
0
ファイル: csvbarfeed_test.py プロジェクト: louisr/pyalgotrade
	def testWithDefaultTimezone(self):
		barFeed = yahoofeed.Feed(marketsession.USEquities.getTimezone())
		barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
		barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"))
		barFeed.start()
		for bars in barFeed:
			bar = bars.getBar(YahooTestCase.TestInstrument)
			self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
		barFeed.stop()
		barFeed.join()
コード例 #26
0
    def testWithoutTimezone(self):
        barFeed = self.__loadIntradayBarFeed(None)
        ds = barFeed.getDataSeries()

        for i in xrange(ds.getLength()):
            currentBar = ds[i]
            # Datetime must be set to UTC.
            currentBarDT = currentBar.getDateTime()
            assert not dt.datetime_is_naive(currentBarDT)
            assert ds[i].getDateTime() == ds.getDateTimes()[i]
コード例 #27
0
	def testWithDefaultTimezone(self):
		barFeed = yahoofeed.Feed(marketsession.USEquities.getTimezone())
		barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
		barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"))
		barFeed.start()
		for bars in barFeed:
			bar = bars.getBar(YahooTestCase.TestInstrument)
			self.assertFalse(dt.datetime_is_naive(bar.getDateTime()))
		barFeed.stop()
		barFeed.join()
コード例 #28
0
 def testWithoutTimezone(self):
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(
         FeedTestCase.TestInstrument,
         common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     barFeed.addBarsFromCSV(
         FeedTestCase.TestInstrument,
         common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     for dateTime, bars, _ in barFeed:
         bar = bars.getBar(FeedTestCase.TestInstrument)
         self.assertTrue(dt.datetime_is_naive(bar.getDateTime()))
コード例 #29
0
    def __init__(self, dateTime):
        super(StockDayRange, self).__init__()
        self.__begin = datetime.datetime(dateTime.year,
                                         dateTime.month,
                                         dateTime.day,
                                         hour=9,
                                         minute=31)

        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
        self.__end = self.__begin.replace(hour=15, minute=0)
        self.isFirtstCheckingNearly = True
コード例 #30
0
ファイル: resamplebase.py プロジェクト: zxlstoner/pyalgotrade
    def __init__(self, dateTime):
        self.__begin = datetime.datetime(dateTime.year, dateTime.month, 1)

        # Calculate the ending date.
        if dateTime.month == 12:
            self.__end = datetime.datetime(dateTime.year + 1, 1, 1)
        else:
            self.__end = datetime.datetime(dateTime.year, dateTime.month + 1, 1)

        if not dt.datetime_is_naive(dateTime):
            self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
            self.__end = dt.localize(self.__end, dateTime.tzinfo)
コード例 #31
0
 def testWithoutTimezone(self):
     # At the moment we need to set both the Feed's constructor and addBarsFromCSV to None in order to get a naive
     # datetime
     barFeed = yahoofeed.Feed(timezone=None)
     barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"),
                            timezone=None)
     barFeed.addBarsFromCSV(YahooTestCase.TestInstrument, common.get_data_file_path("orcl-2001-yahoofinance.csv"),
                            timezone=None)
     barFeed.start()
     for bars in barFeed:
         bar = bars.getBar(YahooTestCase.TestInstrument)
         assert dt.datetime_is_naive(bar.getDateTime())
     barFeed.stop()
     barFeed.join()
コード例 #32
0
ファイル: api.py プロジェクト: WESTLIN/PyAlgoTrade_DocCn
def XigniteGlobalRealTime_GetBar(token,
                                 identifier,
                                 identifierType,
                                 endDateTime,
                                 precision,
                                 period,
                                 secureRequest=None):
    if dt.datetime_is_naive(endDateTime):
        raise Exception("endDateTime must have a timezone")

    # Parse the exchange from the identifier.
    instrument, exchange = parse_instrument_exchange(identifier)

    if secureRequest is None:
        secureRequest = USE_SECURE_REQUESTS

    if secureRequest:
        scheme = "https"
    else:
        scheme = "http"

    # print datetime_to_string(endDateTime, exchange)
    params = {
        "_Token": token,
        "Identifier": identifier,
        "IdentifierType": identifierType,
        "EndTime": datetime_to_string(endDateTime, exchange),
        "Precision": precision,
        "Period": period,
    }
    parts = (scheme,
             "globalrealtime.xignite.com", "v3/xGlobalRealTime.json/GetBar",
             urllib.parse.urlencode(params), "")
    url = urllib.parse.urlunsplit(parts)

    ret = json_http_request(url)
    if ret.get("Outcome") != "Success":
        msg = ret.get("Message")
        if msg is None:
            msg = "Error %s" % (ret.get("Outcome"))
        raise XigniteError(msg, ret)

    return ret
コード例 #33
0
ファイル: barfeed.py プロジェクト: Chin-I/pyalgotrade
def to_utc_if_naive(dateTime):
    if dateTime is not None and dt.datetime_is_naive(dateTime):
        dateTime = dt.as_utc(dateTime)
    return dateTime
コード例 #34
0
 def __init__(self, dateTime):
     self.__begin = datetime.datetime(dateTime.year, dateTime.month, dateTime.day)
     if not dt.datetime_is_naive(dateTime):
         self.__begin = dt.localize(self.__begin, dateTime.tzinfo)
     self.__end = self.__begin + datetime.timedelta(days=1)
コード例 #35
0
ファイル: barfeed.py プロジェクト: rickcrook/pyalgotrade
def to_utc_if_naive(dateTime):
    if dateTime is not None and dt.datetime_is_naive(dateTime):
        dateTime = dt.as_utc(dateTime)
    return dateTime