# Path: tia/analysis/perf.py
# PER_YEAR_MAP = {
#     'BA': 1.,
#     'BAS': 1.,
#     'A': 1.,
#     'AS': 1.,
#     'BQ': 4.,
#     'BQS': 4.,
#     'Q': 4.,
#     'QS': 4.,
#     'D': 365.,
#     'B': 252.,
#     'BMS': 12.,
#     'BM': 12.,
#     'MS': 12.,
#     'M': 12.,
#     'W': 52.,
# }
# def guess_freq(index):
# def periodicity(freq_or_frame):
# def _resolve_periods_in_year(scale, frame):
# def excess_returns(returns, bm=0):
# def returns(prices, method='simple', periods=1, fill_method='pad', limit=None, freq=None):
# def returns_cumulative(returns, geometric=True, expanding=False):
# def rolling_returns_cumulative(returns, window, min_periods=1, geometric=True):
# def returns_annualized(returns, geometric=True, scale=None, expanding=False):
# def drawdowns(returns, geometric=True):
# def max_drawdown(returns=None, geometric=True, dd=None, inc_date=False):
# def drawdown_info(returns, geometric=True):
# def std_annualized(returns, scale=None, expanding=0):
# def sharpe(returns, rfr=0, expanding=0):
# def sharpe_annualized(returns, rfr_ann=0, scale=None, expanding=False, geometric=False):
# def downside_deviation(rets, mar=0, expanding=0, full=0, ann=0):
# def sortino_ratio(rets, rfr_ann=0, mar=0, full=0, expanding=0):
# def information_ratio(rets, bm_rets, scale=None, expanding=False):
# def upside_potential_ratio(rets, mar=0, full=0, expanding=0):
# def rolling_percentileofscore(series, window, min_periods=None):
#     def _percentile(arr):
# def expanding_percentileofscore(series, min_periods=None):
#     def _percentile(arr):
# def hurst_exponent(px, lags=range(2, 100)):
# def summarize_returns(period_rets, rollup='M', prefix=1, ret_method='compound', yearly=1, ltd=1):
#     def _analyze(rets):
# 
# Path: tia/analysis/model/interface.py
# class CostCalculator(object):
#     """Define the methods necessary to be able to calculator the premium for a trade."""
# 
#     def get_premium(self, qty, px, ts=None):
#         raise NotImplementedError()
# 
#     def get_mkt_val(self, qty, px, ts=None):
#         raise NotImplementedError()
# 
# class EodMarketData(object):
#     def get_eod_frame(self):
#         """Return an end of day DataFrame with columns ('close', 'mktval', 'dvd')"""
#         raise NotImplementedError()


import pandas as pd
import numpy as np
from pandas.io.data import get_data_yahoo
from tia.analysis.perf import periods_in_year
from tia.analysis.model.interface import CostCalculator, EodMarketData
        from tia.analysis.model.trd import TradeBlotter
        from tia.analysis.model.port import SingleAssetPortfolio
    from pandas.compat import StringIO, bytes_to_str
    from pandas.io.common import urlopen
        from tia.bbg import BbgDataManager
        from tia.bbg import SidAccessor
        from tia.bbg import BbgDataManager
                        ln - use logarithmic price changes
                        pct - use pct price changes
                        bbg - use logarithmic price changes but Bloomberg uses actual business days
        :param rolling:{'simple', 'exp'}, if exp, use ewmstd. if simple, use rolling_std
        :return:
        """
        if model not in ('bbg', 'ln', 'pct'):
            raise ValueError('model must be one of (bbg, ln, pct), not %s' % model)
        if rolling not in ('simple', 'exp'):
            raise ValueError('rolling must be one of (simple, exp), not %s' % rolling)

        px = self.frame[which]
        px = px if not freq else px.resample(freq, how='last')
        if model == 'bbg' and periods_in_year(px) == 252:
            # Bloomberg uses business days, so need to convert and reindex
            orig = px.index
            px = px.resample('B').ffill()
            chg = np.log(px / px.shift(1))
            chg[chg.index - orig] = np.nan
            if rolling == 'simple':
                vol = pd.rolling_std(chg, n, min_periods=min_periods).reindex(orig)
            else:
                vol = pd.ewmstd(chg, span=n, min_periods=n)
            return vol if not ann else vol * np.sqrt(260)
        else:
            chg = px.pct_change() if model == 'pct' else np.log(px / px.shift(1))
            if rolling == 'simple':
                vol = pd.rolling_std(chg, n, min_periods=min_periods)
            else:
                vol = pd.ewmstd(chg, span=n, min_periods=n)

# Path: tia/analysis/perf.py
# PER_YEAR_MAP = {
#     'BA': 1.,
#     'BAS': 1.,
#     'A': 1.,
#     'AS': 1.,
#     'BQ': 4.,
#     'BQS': 4.,
#     'Q': 4.,
#     'QS': 4.,
#     'D': 365.,
#     'B': 252.,
#     'BMS': 12.,
#     'BM': 12.,
#     'MS': 12.,
#     'M': 12.,
#     'W': 52.,
# }
# def guess_freq(index):
# def periodicity(freq_or_frame):
# def _resolve_periods_in_year(scale, frame):
# def excess_returns(returns, bm=0):
# def returns(prices, method='simple', periods=1, fill_method='pad', limit=None, freq=None):
# def returns_cumulative(returns, geometric=True, expanding=False):
# def rolling_returns_cumulative(returns, window, min_periods=1, geometric=True):
# def returns_annualized(returns, geometric=True, scale=None, expanding=False):
# def drawdowns(returns, geometric=True):
# def max_drawdown(returns=None, geometric=True, dd=None, inc_date=False):
# def drawdown_info(returns, geometric=True):
# def std_annualized(returns, scale=None, expanding=0):
# def sharpe(returns, rfr=0, expanding=0):
# def sharpe_annualized(returns, rfr_ann=0, scale=None, expanding=False, geometric=False):
# def downside_deviation(rets, mar=0, expanding=0, full=0, ann=0):
# def sortino_ratio(rets, rfr_ann=0, mar=0, full=0, expanding=0):
# def information_ratio(rets, bm_rets, scale=None, expanding=False):
# def upside_potential_ratio(rets, mar=0, full=0, expanding=0):
# def rolling_percentileofscore(series, window, min_periods=None):
#     def _percentile(arr):
# def expanding_percentileofscore(series, min_periods=None):
#     def _percentile(arr):
# def hurst_exponent(px, lags=range(2, 100)):
# def summarize_returns(period_rets, rollup='M', prefix=1, ret_method='compound', yearly=1, ltd=1):
#     def _analyze(rets):
# 
# Path: tia/analysis/model/interface.py
# class CostCalculator(object):
#     """Define the methods necessary to be able to calculator the premium for a trade."""
# 
#     def get_premium(self, qty, px, ts=None):
#         raise NotImplementedError()
# 
#     def get_mkt_val(self, qty, px, ts=None):
#         raise NotImplementedError()
# 
# class EodMarketData(object):
#     def get_eod_frame(self):
#         """Return an end of day DataFrame with columns ('close', 'mktval', 'dvd')"""
#         raise NotImplementedError()


# Path: tia/analysis/model/ins.py
import pandas as pd
import numpy as np
from pandas.io.data import get_data_yahoo
from tia.analysis.perf import periods_in_year
from tia.analysis.model.interface import CostCalculator, EodMarketData
        from tia.analysis.model.trd import TradeBlotter
        from tia.analysis.model.port import SingleAssetPortfolio
    from pandas.compat import StringIO, bytes_to_str
    from pandas.io.common import urlopen
        from tia.bbg import BbgDataManager
        from tia.bbg import SidAccessor
        from tia.bbg import BbgDataManager

                        ln - use logarithmic price changes
                        pct - use pct price changes
                        bbg - use logarithmic price changes but Bloomberg uses actual business days
        :param rolling:{'simple', 'exp'}, if exp, use ewmstd. if simple, use rolling_std
        :return:
        """
        if model not in ('bbg', 'ln', 'pct'):
            raise ValueError('model must be one of (bbg, ln, pct), not %s' % model)
        if rolling not in ('simple', 'exp'):
            raise ValueError('rolling must be one of (simple, exp), not %s' % rolling)

        px = self.frame[which]
        px = px if not freq else px.resample(freq, how='last')
        if model == 'bbg' and periods_in_year(px) == 252:
            # Bloomberg uses business days, so need to convert and reindex
            orig = px.index
            px = px.resample('B').ffill()
            chg = np.log(px / px.shift(1))
            chg[chg.index - orig] = np.nan
            if rolling == 'simple':
                vol = pd.rolling_std(chg, n, min_periods=min_periods).reindex(orig)
            else:
                vol = pd.ewmstd(chg, span=n, min_periods=n)
            return vol if not ann else vol * np.sqrt(260)
        else:
            chg = px.pct_change() if model == 'pct' else np.log(px / px.shift(1))
            if rolling == 'simple':
                vol = pd.rolling_std(chg, n, min_periods=min_periods)
            else:
                vol = pd.ewmstd(chg, span=n, min_periods=n)

            return vol if not ann else vol * np.sqrt(periods_in_year(vol))