Skip to content

Commit

Permalink
DEP: Add deprecation warning to timeseries functions, substitute qris…
Browse files Browse the repository at this point in the history
…k functions whenever risk calculations are used
  • Loading branch information
Ana Ruelas committed Jul 7, 2016
1 parent d47f76d commit 22ed88d
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 171 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ before_install:
install:
- conda create -q -n testenv --yes python=$TRAVIS_PYTHON_VERSION ipython pyzmq numpy scipy nose matplotlib pandas Cython patsy statsmodels flake8 scikit-learn seaborn runipy pytables networkx pandas-datareader matplotlib-tests joblib
- source activate testenv
- pip install nose_parameterized
- pip install nose_parameterized qrisk>=0.1.4
#- pip install --no-deps git+https://github.com/quantopian/zipline
- if [ ${TRAVIS_PYTHON_VERSION:0:1} == "2" ]; then conda install --yes mock enum34; fi
- pip install --no-deps git+https://github.com/Theano/Theano.git@rel-0.8.1
Expand Down
2 changes: 1 addition & 1 deletion pyfolio/bayesian.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from pymc3 import T as StudentT

from . import _seaborn as sns
from .timeseries import cum_returns
from qrisk import cum_returns


def model_returns_t_alpha_beta(data, bmark, samples=2000):
Expand Down
4 changes: 2 additions & 2 deletions pyfolio/capacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pandas as pd
import numpy as np
from . import pos
from . import timeseries
import qrisk


def daily_txns_with_bar_data(transactions, market_data):
Expand Down Expand Up @@ -233,7 +233,7 @@ def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital,
# by capital base, it makes the most sense to scale the denominator
# similarly. In other words, since we aren't applying compounding to
# simulate_traded_shares, we shouldn't apply compounding to pv.
portfolio_value = timeseries.cum_returns(
portfolio_value = qrisk.cum_returns(
returns, starting_value=backtest_starting_capital) * mult

adj_returns = returns - (daily_penalty / portfolio_value)
Expand Down
45 changes: 45 additions & 0 deletions pyfolio/deprecate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Utilities for marking deprecated functions."""
# Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings
from functools import wraps


def deprecated(msg=None, stacklevel=2):
"""
Used to mark a function as deprecated.
Parameters
----------
msg : str
The message to display in the deprecation warning.
stacklevel : int
How far up the stack the warning needs to go, before
showing the relevant calling lines.
Usage
-----
@deprecated(msg='function_a is deprecated! Use function_b instead.')
def function_a(*args, **kwargs):
"""
def deprecated_dec(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn(
msg or "Function %s is deprecated." % fn.__name__,
category=DeprecationWarning,
stacklevel=stacklevel
)
return fn(*args, **kwargs)
return wrapper
return deprecated_dec
39 changes: 19 additions & 20 deletions pyfolio/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,7 @@ def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):
if ax is None:
ax = plt.gca()

monthly_ret_table = timeseries.aggregate_returns(returns,
'monthly')
monthly_ret_table = qrisk.aggregate_returns(returns, 'monthly')
monthly_ret_table = monthly_ret_table.unstack().round(3)

sns.heatmap(
Expand Down Expand Up @@ -243,7 +242,7 @@ def plot_annual_returns(returns, ax=None, **kwargs):
ax.tick_params(axis='x', which='major', labelsize=10)

ann_ret_df = pd.DataFrame(
timeseries.aggregate_returns(
qrisk.aggregate_returns(
returns,
'yearly'))

Expand Down Expand Up @@ -292,7 +291,7 @@ def plot_monthly_returns_dist(returns, ax=None, **kwargs):
ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))
ax.tick_params(axis='x', which='major', labelsize=10)

monthly_ret_table = timeseries.aggregate_returns(returns, 'monthly')
monthly_ret_table = qrisk.aggregate_returns(returns, 'monthly')

ax.hist(
100 * monthly_ret_table,
Expand Down Expand Up @@ -405,7 +404,7 @@ def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):
y_axis_formatter = FuncFormatter(utils.one_dec_places)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

df_cum_rets = timeseries.cum_returns(returns, starting_value=1.0)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1.0)
df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)

df_cum_rets.plot(ax=ax, **kwargs)
Expand Down Expand Up @@ -456,7 +455,7 @@ def plot_drawdown_underwater(returns, ax=None, **kwargs):
y_axis_formatter = FuncFormatter(utils.percentage)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

df_cum_rets = timeseries.cum_returns(returns, starting_value=1.0)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1.0)
running_max = np.maximum.accumulate(df_cum_rets)
underwater = -100 * ((running_max - df_cum_rets) / running_max)
(underwater).plot(ax=ax, kind='area', color='coral', alpha=0.7, **kwargs)
Expand Down Expand Up @@ -691,13 +690,13 @@ def cone(in_sample_returns (pd.Series),
bmark_vol = factor_returns.loc[returns.index].std()
returns = (returns / returns.std()) * bmark_vol

cum_rets = timeseries.cum_returns(returns, 1.0)
cum_rets = qrisk.cum_returns(returns, 1.0)

y_axis_formatter = FuncFormatter(utils.one_dec_places)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

if factor_returns is not None:
cum_factor_returns = timeseries.cum_returns(
cum_factor_returns = qrisk.cum_returns(
factor_returns[cum_rets.index], 1.0)
cum_factor_returns.plot(lw=2, color='gray',
label=factor_returns.name, alpha=0.60,
Expand Down Expand Up @@ -917,7 +916,7 @@ def plot_exposures(returns, positions_alloc, ax=None, **kwargs):
df_long_short.plot(
kind='line', style=['-g', '-r', '--k'], alpha=1.0,
ax=ax, **kwargs)
df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1)
ax.set_xlim((df_cum_rets.index[0], df_cum_rets.index[-1]))
ax.set_title("Long/Short Exposure")
ax.set_ylabel('Exposure')
Expand Down Expand Up @@ -1003,7 +1002,7 @@ def show_and_plot_top_positions(returns, positions_alloc,
else:
ax.legend(loc=legend_loc)

df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1)
ax.set_xlim((df_cum_rets.index[0], df_cum_rets.index[-1]))
ax.set_ylabel('Exposure by stock')

Expand Down Expand Up @@ -1114,16 +1113,16 @@ def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):

is_returns = returns if live_start_date is None \
else returns.loc[returns.index < live_start_date]
is_weekly = timeseries.aggregate_returns(is_returns, 'weekly')
is_monthly = timeseries.aggregate_returns(is_returns, 'monthly')
is_weekly = qrisk.aggregate_returns(is_returns, 'weekly')
is_monthly = qrisk.aggregate_returns(is_returns, 'monthly')
sns.boxplot(data=[is_returns, is_weekly, is_monthly],
palette=["#4c72B0", "#55A868", "#CCB974"],
ax=ax, **kwargs)

if live_start_date is not None:
oos_returns = returns.loc[returns.index >= live_start_date]
oos_weekly = timeseries.aggregate_returns(oos_returns, 'weekly')
oos_monthly = timeseries.aggregate_returns(oos_returns, 'monthly')
oos_weekly = qrisk.aggregate_returns(oos_returns, 'weekly')
oos_monthly = qrisk.aggregate_returns(oos_returns, 'monthly')

sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,
color="red",
Expand All @@ -1149,7 +1148,7 @@ def show_return_range(returns):
- See full explanation in tears.create_full_tear_sheet.
"""

df_weekly = timeseries.aggregate_returns(returns, 'weekly')
df_weekly = qrisk.aggregate_returns(returns, 'weekly')

two_sigma_daily = returns.mean() - 2 * returns.std()
two_sigma_weekly = df_weekly.mean() - 2 * df_weekly.std()
Expand Down Expand Up @@ -1218,7 +1217,7 @@ def plot_turnover(returns, transactions, positions,
'Average daily turnover, net'],
loc=legend_loc)
ax.set_title('Daily Turnover')
df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1)
ax.set_xlim((df_cum_rets.index[0], df_cum_rets.index[-1]))
ax.set_ylim((0, 1))
ax.set_ylabel('Turnover')
Expand Down Expand Up @@ -1266,7 +1265,7 @@ def plot_slippage_sweep(returns, transactions, positions,
for bps in slippage_params:
adj_returns = txn.adjust_returns_for_slippage(returns, turnover, bps)
label = str(bps) + " bps"
slippage_sweep[label] = timeseries.cum_returns(adj_returns, 1)
slippage_sweep[label] = qrisk.cum_returns(adj_returns, 1)

slippage_sweep.plot(alpha=1.0, lw=0.5, ax=ax)

Expand Down Expand Up @@ -1422,7 +1421,7 @@ def plot_daily_volume(returns, transactions, ax=None, **kwargs):
ax.axhline(daily_txn.txn_shares.mean(), color='steelblue',
linestyle='--', lw=3, alpha=1.0)
ax.set_title('Daily Trading Volume')
df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1)
ax.set_xlim((df_cum_rets.index[0], df_cum_rets.index[-1]))
ax.set_ylabel('Amount of shares traded')
ax.set_xlabel('')
Expand Down Expand Up @@ -1516,7 +1515,7 @@ def plot_monthly_returns_timeseries(returns, ax=None, **kwargs):
"""

def cumulate_returns(x):
return timeseries.cum_returns(x)[-1]
return qrisk.cum_returns(x)[-1]

if ax is None:
ax = plt.gca()
Expand Down Expand Up @@ -1720,7 +1719,7 @@ def plot_multistrike_cones(is_returns, oos_returns, num_samples=1000,
else:
axes = ax

returns = timeseries.cum_returns(oos_returns, starting_value=1.)
returns = qrisk.cum_returns(oos_returns, starting_value=1.)
bounds = timeseries.forecast_cone_bootstrap(is_returns,
len(oos_returns),
cone_std=cone_std,
Expand Down
7 changes: 4 additions & 3 deletions pyfolio/tears.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from . import plotting
from . import _seaborn as sns
from .plotting import plotting_context
import qrisk

try:
from . import bayesian
Expand Down Expand Up @@ -252,7 +253,7 @@ def create_returns_tear_sheet(returns, live_start_date=None,
if returns.index[0] < benchmark_rets.index[0]:
returns = returns[returns.index > benchmark_rets.index[0]]

df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
df_cum_rets = qrisk.cum_returns(returns, starting_value=1)
print("Entire data start date: " + str(df_cum_rets
.index[0].strftime('%Y-%m-%d')))
print("Entire data end date: " + str(df_cum_rets
Expand Down Expand Up @@ -693,9 +694,9 @@ def create_interesting_times_tear_sheet(

# i=0 -> 0, i=1 -> 0, i=2 -> 1 ;; i=0 -> 0, i=1 -> 1, i=2 -> 0
ax = plt.subplot(gs[int(i / 2.0), i % 2])
timeseries.cum_returns(rets_period).plot(
qrisk.cum_returns(rets_period).plot(
ax=ax, color='forestgreen', label='algo', alpha=0.7, lw=2)
timeseries.cum_returns(bmark_interesting[name]).plot(
qrisk.cum_returns(bmark_interesting[name]).plot(
ax=ax, color='gray', label='SPY', alpha=0.6)
ax.legend(['algo',
'SPY'],
Expand Down
Loading

0 comments on commit 22ed88d

Please sign in to comment.