# Path: alephnull/data/loader.py
# def load_market_data(bm_symbol='^GSPC'):
#     try:
#         fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb")
#     except IOError:
#         print("""
# data files aren't distributed with source.
# Fetching data from Yahoo Finance.
# """).strip()
#         dump_benchmarks(bm_symbol)
#         fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb")
# 
#     saved_benchmarks = pd.Series.from_csv(fp_bm)
#     saved_benchmarks = saved_benchmarks.tz_localize('UTC')
#     fp_bm.close()
# 
#     most_recent = pd.Timestamp('today', tz='UTC') - trading_day
#     most_recent_index = trading_days.searchsorted(most_recent)
#     days_up_to_now = trading_days[:most_recent_index + 1]
# 
#     # Find the offset of the last date for which we have trading data in our
#     # list of valid trading days
#     last_bm_date = saved_benchmarks.index[-1]
#     last_bm_date_offset = days_up_to_now.searchsorted(
#         last_bm_date.strftime('%Y/%m/%d'))
# 
#     # If more than 1 trading days has elapsed since the last day where
#     # we have data,then we need to update
#     if len(days_up_to_now) - last_bm_date_offset > 1:
#         benchmark_returns = update_benchmarks(bm_symbol, last_bm_date)
#         if (
#             benchmark_returns.index.tz is None
#             or
#             benchmark_returns.index.tz.zone != 'UTC'
#         ):
#             benchmark_returns = benchmark_returns.tz_localize('UTC')
#     else:
#         benchmark_returns = saved_benchmarks
#         if (
#             benchmark_returns.index.tz is None
#             or
#             benchmark_returns.index.tz.zone != 'UTC'
#         ):
#             benchmark_returns = benchmark_returns.tz_localize('UTC')
# 
#     #Get treasury curve module, filename & source from mapping.
#     #Default to USA.
#     module, filename, source = INDEX_MAPPING.get(
#         bm_symbol, INDEX_MAPPING['^GSPC'])
# 
#     try:
#         fp_tr = get_datafile(filename, "rb")
#     except IOError:
#         print("""
# data files aren't distributed with source.
# Fetching data from {0}
# """).format(source).strip()
#         dump_treasury_curves(module, filename)
#         fp_tr = get_datafile(filename, "rb")
# 
#     saved_curves = pd.DataFrame.from_csv(fp_tr)
# 
#     # Find the offset of the last date for which we have trading data in our
#     # list of valid trading days
#     last_tr_date = saved_curves.index[-1]
#     last_tr_date_offset = days_up_to_now.searchsorted(
#         last_tr_date.strftime('%Y/%m/%d'))
# 
#     # If more than 1 trading days has elapsed since the last day where
#     # we have data,then we need to update
#     if len(days_up_to_now) - last_tr_date_offset > 1:
#         treasury_curves = dump_treasury_curves(module, filename)
#     else:
#         treasury_curves = saved_curves.tz_localize('UTC')
# 
#     tr_curves = {}
#     for tr_dt, curve in treasury_curves.T.iterkv():
#         # tr_dt = tr_dt.replace(hour=0, minute=0, second=0, microsecond=0,
#         #                       tzinfo=pytz.utc)
#         tr_curves[tr_dt] = curve.to_dict()
# 
#     fp_tr.close()
# 
#     tr_curves = OrderedDict(sorted(
#         ((dt, c) for dt, c in tr_curves.iteritems()),
#         key=lambda t: t[0]))
# 
#     return benchmark_returns, tr_curves


import bisect
import logbook
import datetime
import pandas as pd
from alephnull.data.loader import load_market_data
from alephnull.utils import tradingcalendar
from alephnull.utils.tradingcalendar import get_early_closes
# you can use a TradingEnvironment in a with clause:
#       lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London")
#       with lse:
#           # the code here will have lse as the global trading.environment
#           algo.run(start, end)
#
# User code will not normally need to use TradingEnvironment
# directly. If you are extending zipline's core financial
# compponents and need to use the environment, you must import the module
# NOT the variable. If you import the module, you will get a
# reference to the environment at import time, which will prevent
# your code from responding to user code that changes the global
# state.

environment = None


class TradingEnvironment(object):

    def __init__(
        self,
        load=None,
        bm_symbol='^GSPC',
        exchange_tz="US/Eastern",
        max_date=None,
        extra_dates=None
    ):
        self.prev_environment = self
        self.bm_symbol = bm_symbol
        if not load:

# Path: alephnull/data/loader.py
# def load_market_data(bm_symbol='^GSPC'):
#     try:
#         fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb")
#     except IOError:
#         print("""
# data files aren't distributed with source.
# Fetching data from Yahoo Finance.
# """).strip()
#         dump_benchmarks(bm_symbol)
#         fp_bm = get_datafile(get_benchmark_filename(bm_symbol), "rb")
# 
#     saved_benchmarks = pd.Series.from_csv(fp_bm)
#     saved_benchmarks = saved_benchmarks.tz_localize('UTC')
#     fp_bm.close()
# 
#     most_recent = pd.Timestamp('today', tz='UTC') - trading_day
#     most_recent_index = trading_days.searchsorted(most_recent)
#     days_up_to_now = trading_days[:most_recent_index + 1]
# 
#     # Find the offset of the last date for which we have trading data in our
#     # list of valid trading days
#     last_bm_date = saved_benchmarks.index[-1]
#     last_bm_date_offset = days_up_to_now.searchsorted(
#         last_bm_date.strftime('%Y/%m/%d'))
# 
#     # If more than 1 trading days has elapsed since the last day where
#     # we have data,then we need to update
#     if len(days_up_to_now) - last_bm_date_offset > 1:
#         benchmark_returns = update_benchmarks(bm_symbol, last_bm_date)
#         if (
#             benchmark_returns.index.tz is None
#             or
#             benchmark_returns.index.tz.zone != 'UTC'
#         ):
#             benchmark_returns = benchmark_returns.tz_localize('UTC')
#     else:
#         benchmark_returns = saved_benchmarks
#         if (
#             benchmark_returns.index.tz is None
#             or
#             benchmark_returns.index.tz.zone != 'UTC'
#         ):
#             benchmark_returns = benchmark_returns.tz_localize('UTC')
# 
#     #Get treasury curve module, filename & source from mapping.
#     #Default to USA.
#     module, filename, source = INDEX_MAPPING.get(
#         bm_symbol, INDEX_MAPPING['^GSPC'])
# 
#     try:
#         fp_tr = get_datafile(filename, "rb")
#     except IOError:
#         print("""
# data files aren't distributed with source.
# Fetching data from {0}
# """).format(source).strip()
#         dump_treasury_curves(module, filename)
#         fp_tr = get_datafile(filename, "rb")
# 
#     saved_curves = pd.DataFrame.from_csv(fp_tr)
# 
#     # Find the offset of the last date for which we have trading data in our
#     # list of valid trading days
#     last_tr_date = saved_curves.index[-1]
#     last_tr_date_offset = days_up_to_now.searchsorted(
#         last_tr_date.strftime('%Y/%m/%d'))
# 
#     # If more than 1 trading days has elapsed since the last day where
#     # we have data,then we need to update
#     if len(days_up_to_now) - last_tr_date_offset > 1:
#         treasury_curves = dump_treasury_curves(module, filename)
#     else:
#         treasury_curves = saved_curves.tz_localize('UTC')
# 
#     tr_curves = {}
#     for tr_dt, curve in treasury_curves.T.iterkv():
#         # tr_dt = tr_dt.replace(hour=0, minute=0, second=0, microsecond=0,
#         #                       tzinfo=pytz.utc)
#         tr_curves[tr_dt] = curve.to_dict()
# 
#     fp_tr.close()
# 
#     tr_curves = OrderedDict(sorted(
#         ((dt, c) for dt, c in tr_curves.iteritems()),
#         key=lambda t: t[0]))
# 
#     return benchmark_returns, tr_curves


# Path: alephnull/finance/trading.py
import bisect
import logbook
import datetime
import pandas as pd
from alephnull.data.loader import load_market_data
from alephnull.utils import tradingcalendar
from alephnull.utils.tradingcalendar import get_early_closes

# you can use a TradingEnvironment in a with clause:
#       lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London")
#       with lse:
#           # the code here will have lse as the global trading.environment
#           algo.run(start, end)
#
# User code will not normally need to use TradingEnvironment
# directly. If you are extending zipline's core financial
# compponents and need to use the environment, you must import the module
# NOT the variable. If you import the module, you will get a
# reference to the environment at import time, which will prevent
# your code from responding to user code that changes the global
# state.

environment = None


class TradingEnvironment(object):

    def __init__(
        self,
        load=None,
        bm_symbol='^GSPC',
        exchange_tz="US/Eastern",
        max_date=None,
        extra_dates=None
    ):
        self.prev_environment = self
        self.bm_symbol = bm_symbol
        if not load:

            load = load_market_data