#!/usr/bin/env python # coding: utf-8 # In[1]: import tia.analysis.ta as ta import tia.analysis.talib_wrapper as talib import pandas as pd from pandas.io.data import get_data_yahoo from tia.analysis.model import SingleAssetPortfolio, PortfolioPricer, load_yahoo_stock, PortfolioSummary from tia.analysis.model.ret import RoiiRetCalculator from tia.util.fmt import DynamicColumnFormatter, DynamicRowFormatter, new_dynamic_formatter import matplotlib.pyplot as plt # In[2]: # drop adj close & volume for example sake msft = load_yahoo_stock('MSFT', start='1/1/2010') # In[3]: get_ipython().run_line_magic('matplotlib', 'inline') # In[4]: # build signal when 50d crosses 200d moving_avgs = pd.DataFrame({'50': ta.sma(msft.pxs.close, 50), '200': ta.sma(msft.pxs.close, 200)}) signal = ta.cross_signal(moving_avgs['50'], moving_avgs['200']).dropna() # keep only entry entry_signal = signal.copy() entry_signal[signal.shift(1) == signal] = 0 entry_signal = entry_signal[entry_signal != 0] # show when the signal triggers moving_avgs.plot(color=['b', 'k'], title='MSFT moving averages') for i, v in entry_signal.iteritems(): if v == -1: plt.plot(i, moving_avgs['50'][i], 'rv') else: plt.plot(i, moving_avgs['50'][i], 'k^') # In[5]: # Can get the set of trades created by this signal trades = ta.Signal(signal).close_to_close(msft.pxs.close) trades # In[6]: # construct a portfolio from the trades port = SingleAssetPortfolio(msft, trades, ret_calc=RoiiRetCalculator()) # In[7]: # Show each of the individial transactions port.txns.frame.tail() # In[8]: # Show the position summary port.positions.frame # In[9]: # Transaction Level Profit & Loss port.pl.txn_frame.tail(5) # In[10]: # Daily Profit & Loss Frame port.pl.dly_frame.tail(5) # In[11]: # Show Profit & Loss Report DynamicColumnFormatter(port.pl.report_by_year()) # In[12]: # Show Position Information port.positions.stats # In[13]: # Ability to show different return frequencies fig, axes = plt.subplots(4, 1, figsize=(10, 12)) ax = port.performance.dly_details.plot_ltd(ax=axes[0]) port.performance.weekly_details.plot_ltd(ax=axes[1]) port.performance.monthly_details.plot_ltd(ax=axes[2]) port.performance.quarterly_details.plot_ltd(ax=axes[3]) axes[0].set_ylabel('Daily'), axes[1].set_ylabel('Weekly') axes[2].set_ylabel('Monthly'), axes[3].set_ylabel('Quarterly') # In[14]: # # Show the Return on a dollar # port.performance.dly_details.plot_ret_on_dollar(label='LongShort') port.long.performance.dly_details.plot_ret_on_dollar(label='Long') port.short.performance.dly_details.plot_ret_on_dollar(label='Short') plt.legend(loc='upper left') # In[15]: # Show a return report F = new_dynamic_formatter(method='col', pcts=1, trunc_dot_zeros=1) # Ability to added custom groupps F(port.performance.report_by_year(prior_n_yrs=2, ranges=[(2011, 2012)])) # In[16]: # Build a custom report which shows return information and position level information in single frame RF = new_dynamic_formatter('row', pcts=1, trunc_dot_zeros=1) summary = PortfolioSummary() summary.include_long_short().include_win_loss() RF(summary(port).T) # In[ ]: