# Path: alephnull/transforms/utils.py
# class EventWindow(object):
#     """
#     Abstract base class for transform classes that calculate iterative
#     metrics on events within a given timedelta.  Maintains a list of
#     events that are within a certain timedelta of the most recent
#     tick.  Calls self.handle_add(event) for each event added to the
#     window.  Calls self.handle_remove(event) for each event removed
#     from the window.  Subclass these methods along with init(*args,
#     **kwargs) to calculate metrics over the window.
# 
#     If the market_aware flag is True, the EventWindow drops old events
#     based on the number of elapsed trading days between newest and oldest.
#     Otherwise old events are dropped based on a raw timedelta.
# 
#     See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example
#     implementations of moving average and volume-weighted average
#     price.
#     """
#     # Mark this as an abstract base class.
#     __metaclass__ = ABCMeta
# 
#     def __init__(self, market_aware=True, window_length=None, delta=None):
# 
#         check_window_length(window_length)
#         self.window_length = window_length
# 
#         self.ticks = deque()
# 
#         # Only Market-aware mode is now supported.
#         if not market_aware:
#             raise UnsupportedEventWindowFlagValue(
#                 "Non-'market aware' mode is no longer supported."
#             )
#         if delta:
#             raise UnsupportedEventWindowFlagValue(
#                 "delta values are no longer supported."
#             )
#         # Set the behavior for dropping events from the back of the
#         # event window.
#         self.drop_condition = self.out_of_market_window
# 
#     @abstractmethod
#     def handle_add(self, event):
#         raise NotImplementedError()
# 
#     @abstractmethod
#     def handle_remove(self, event):
#         raise NotImplementedError()
# 
#     def __len__(self):
#         return len(self.ticks)
# 
#     def update(self, event):
# 
#         if (hasattr(event, 'type')
#                 and event.type not in (
#                     DATASOURCE_TYPE.TRADE,
#                     DATASOURCE_TYPE.CUSTOM)):
#             return
# 
#         self.assert_well_formed(event)
#         # Add new event and increment totals.
#         self.ticks.append(event)
# 
#         # Subclasses should override handle_add to define behavior for
#         # adding new ticks.
#         self.handle_add(event)
#         # Clear out any expired events.
#         #
#         #                              oldest               newest
#         #                                |                    |
#         #                                V                    V
#         while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt):
# 
#             # popleft removes and returns the oldest tick in self.ticks
#             popped = self.ticks.popleft()
# 
#             # Subclasses should override handle_remove to define
#             # behavior for removing ticks.
#             self.handle_remove(popped)
# 
#     def out_of_market_window(self, oldest, newest):
#         oldest_index = \
#             trading.environment.trading_days.searchsorted(oldest)
#         newest_index = \
#             trading.environment.trading_days.searchsorted(newest)
# 
#         trading_days_between = newest_index - oldest_index
# 
#         # "Put back" a day if oldest is earlier in its day than newest,
#         # reflecting the fact that we haven't yet completed the last
#         # day in the window.
#         if oldest.time() > newest.time():
#             trading_days_between -= 1
# 
#         return trading_days_between >= self.window_length
# 
#     # All event windows expect to receive events with datetime fields
#     # that arrive in sorted order.
#     def assert_well_formed(self, event):
#         assert isinstance(event.dt, datetime), \
#             "Bad dt in EventWindow:%s" % event
#         if len(self.ticks) > 0:
#             # Something is wrong if new event is older than previous.
#             assert event.dt >= self.ticks[-1].dt, \
#                 "Events arrived out of order in EventWindow: %s -> %s" % \
#                 (event, self.ticks[0])
# 
# class TransformMeta(type):
#     """
#     Metaclass that automatically packages a class inside of
#     StatefulTransform on initialization. Specifically, if Foo is a
#     class with its __metaclass__ attribute set to TransformMeta, then
#     calling Foo(*args, **kwargs) will return StatefulTransform(Foo,
#     *args, **kwargs) instead of an instance of Foo. (Note that you can
#     still recover an instance of a "raw" Foo by introspecting the
#     resulting StatefulTransform's 'state' field.)
#     """
# 
#     def __call__(cls, *args, **kwargs):
#         return StatefulTransform(cls, *args, **kwargs)


from collections import defaultdict
from math import sqrt
from alephnull.errors import WrongDataForTransform
from alephnull.transforms.utils import EventWindow, TransformMeta
import alephnull.utils.math_utils as zp_math
        Update the event window for this event's sid.  Return a dict
        from tracked fields to moving averages.
        """
        # This will create a new EventWindow if this is the first
        # message for this sid.
        window = self.sid_windows[event.sid]
        window.update(event)
        return window.get_stddev()

    def assert_required_fields(self, event):
        """
        We only allow events with a price field to be run through
        the returns transform.
        """
        if 'price' not in event:
                raise WrongDataForTransform(
                    transform="StdDevEventWindow",
                    fields='price')


class MovingStandardDevWindow(EventWindow):
    """
    Iteratively calculates standard deviation for a particular sid
    over a given time window.  The expected functionality of this
    class is to be instantiated inside a MovingStandardDev.
    """

    def __init__(self, market_aware=True, window_length=None, delta=None):
        # Call the superclass constructor to set up base EventWindow
        # infrastructure.

# Path: alephnull/transforms/utils.py
# class EventWindow(object):
#     """
#     Abstract base class for transform classes that calculate iterative
#     metrics on events within a given timedelta.  Maintains a list of
#     events that are within a certain timedelta of the most recent
#     tick.  Calls self.handle_add(event) for each event added to the
#     window.  Calls self.handle_remove(event) for each event removed
#     from the window.  Subclass these methods along with init(*args,
#     **kwargs) to calculate metrics over the window.
# 
#     If the market_aware flag is True, the EventWindow drops old events
#     based on the number of elapsed trading days between newest and oldest.
#     Otherwise old events are dropped based on a raw timedelta.
# 
#     See zipline/transforms/mavg.py and zipline/transforms/vwap.py for example
#     implementations of moving average and volume-weighted average
#     price.
#     """
#     # Mark this as an abstract base class.
#     __metaclass__ = ABCMeta
# 
#     def __init__(self, market_aware=True, window_length=None, delta=None):
# 
#         check_window_length(window_length)
#         self.window_length = window_length
# 
#         self.ticks = deque()
# 
#         # Only Market-aware mode is now supported.
#         if not market_aware:
#             raise UnsupportedEventWindowFlagValue(
#                 "Non-'market aware' mode is no longer supported."
#             )
#         if delta:
#             raise UnsupportedEventWindowFlagValue(
#                 "delta values are no longer supported."
#             )
#         # Set the behavior for dropping events from the back of the
#         # event window.
#         self.drop_condition = self.out_of_market_window
# 
#     @abstractmethod
#     def handle_add(self, event):
#         raise NotImplementedError()
# 
#     @abstractmethod
#     def handle_remove(self, event):
#         raise NotImplementedError()
# 
#     def __len__(self):
#         return len(self.ticks)
# 
#     def update(self, event):
# 
#         if (hasattr(event, 'type')
#                 and event.type not in (
#                     DATASOURCE_TYPE.TRADE,
#                     DATASOURCE_TYPE.CUSTOM)):
#             return
# 
#         self.assert_well_formed(event)
#         # Add new event and increment totals.
#         self.ticks.append(event)
# 
#         # Subclasses should override handle_add to define behavior for
#         # adding new ticks.
#         self.handle_add(event)
#         # Clear out any expired events.
#         #
#         #                              oldest               newest
#         #                                |                    |
#         #                                V                    V
#         while self.drop_condition(self.ticks[0].dt, self.ticks[-1].dt):
# 
#             # popleft removes and returns the oldest tick in self.ticks
#             popped = self.ticks.popleft()
# 
#             # Subclasses should override handle_remove to define
#             # behavior for removing ticks.
#             self.handle_remove(popped)
# 
#     def out_of_market_window(self, oldest, newest):
#         oldest_index = \
#             trading.environment.trading_days.searchsorted(oldest)
#         newest_index = \
#             trading.environment.trading_days.searchsorted(newest)
# 
#         trading_days_between = newest_index - oldest_index
# 
#         # "Put back" a day if oldest is earlier in its day than newest,
#         # reflecting the fact that we haven't yet completed the last
#         # day in the window.
#         if oldest.time() > newest.time():
#             trading_days_between -= 1
# 
#         return trading_days_between >= self.window_length
# 
#     # All event windows expect to receive events with datetime fields
#     # that arrive in sorted order.
#     def assert_well_formed(self, event):
#         assert isinstance(event.dt, datetime), \
#             "Bad dt in EventWindow:%s" % event
#         if len(self.ticks) > 0:
#             # Something is wrong if new event is older than previous.
#             assert event.dt >= self.ticks[-1].dt, \
#                 "Events arrived out of order in EventWindow: %s -> %s" % \
#                 (event, self.ticks[0])
# 
# class TransformMeta(type):
#     """
#     Metaclass that automatically packages a class inside of
#     StatefulTransform on initialization. Specifically, if Foo is a
#     class with its __metaclass__ attribute set to TransformMeta, then
#     calling Foo(*args, **kwargs) will return StatefulTransform(Foo,
#     *args, **kwargs) instead of an instance of Foo. (Note that you can
#     still recover an instance of a "raw" Foo by introspecting the
#     resulting StatefulTransform's 'state' field.)
#     """
# 
#     def __call__(cls, *args, **kwargs):
#         return StatefulTransform(cls, *args, **kwargs)


# Path: alephnull/transforms/stddev.py
from collections import defaultdict
from math import sqrt
from alephnull.errors import WrongDataForTransform
from alephnull.transforms.utils import EventWindow, TransformMeta
import alephnull.utils.math_utils as zp_math

        Update the event window for this event's sid.  Return a dict
        from tracked fields to moving averages.
        """
        # This will create a new EventWindow if this is the first
        # message for this sid.
        window = self.sid_windows[event.sid]
        window.update(event)
        return window.get_stddev()

    def assert_required_fields(self, event):
        """
        We only allow events with a price field to be run through
        the returns transform.
        """
        if 'price' not in event:
                raise WrongDataForTransform(
                    transform="StdDevEventWindow",
                    fields='price')


class MovingStandardDevWindow(EventWindow):
    """
    Iteratively calculates standard deviation for a particular sid
    over a given time window.  The expected functionality of this
    class is to be instantiated inside a MovingStandardDev.
    """

    def __init__(self, market_aware=True, window_length=None, delta=None):
        # Call the superclass constructor to set up base EventWindow
        # infrastructure.

        EventWindow.__init__(self, market_aware, window_length, delta)