#!/usr/bin/env python # coding: utf-8 # # Example of using the model module # This notebook shows how to use the components defined in the model. The model module is meant as a light-weight trade model which allows flexible portfolio construction and valuation. The portfolio then handles the position management (long/short), and p&l accounting. # In[1]: import tia.analysis.model as model import pandas as pd from tia.util.fmt import new_dynamic_formatter, DynamicColumnFormatter # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt try: plt.style.use('fivethirtyeight') plt.rcParams['lines.linewidth'] = 1.4 except: pass # In[3]: # Load microsoft - note it retrieves the dividends too msft = model.load_yahoo_stock('MSFT', start='1/1/2010') msft.pxs.frame.tail() # In[4]: fig, axes = plt.subplots(1, 2, figsize=(12, 3)) msft.pxs.dvds.resample('Q', how='sum').to_period().plot(kind='bar', ax=axes[0], title='msft dividends') msft.pxs.close.plot(ax=axes[1], title='msft close') # In[5]: # # Create a signal for when the 10x20 moving average (buy/sell single contract) # - you can create your own simulation and build trades (using model.Trade or # model.TradeBlotter) from tia.analysis.ta import cross_signal, sma, Signal ma10, ma20 = sma(msft.pxs.close, 10), sma(msft.pxs.close, 20) sig = cross_signal(ma10, ma20) trades = Signal(sig).close_to_close(msft.pxs.close) # show last 10 trades trades[-10:] # In[6]: # Build the portfolio port = model.SingleAssetPortfolio(msft, trades) # In[7]: # show the ltd transaction level pl frame port.pl.ltd_txn_frame.tail() # In[8]: # show the daily pl frame (rolled up by day) port.pl.dly_frame.tail() # In[9]: # show the positions F = new_dynamic_formatter(method='col', pcts=1, parens=0, trunc_dot_zeros=1) F(port.positions.frame.tail(4)) # In[10]: # Look at basic p/l stats PLFMT = new_dynamic_formatter(method='row', precision=3, pcts=1, trunc_dot_zeros=1) tmp = pd.DataFrame({'dly': port.pl.dly_details.summary, 'wkly': port.pl.weekly_details.summary, 'mthly': port.pl.monthly_details.summary, 'yrly': port.pl.annual_details.summary}) PLFMT(tmp) # In[11]: FMT = new_dynamic_formatter(method='row', precision=2, pcts=1, trunc_dot_zeros=1) # In[12]: # Look at basic ret stats (By default return on initial invest of each position) tmp = pd.DataFrame({'dly': port.performance.dly_details.summary, 'wkly': port.performance.weekly_details.summary, 'mthly': port.performance.monthly_details.summary, 'yrly': port.performance.annual_details.summary}) FMT(tmp) # In[13]: # show the position stats port.positions.stats # In[14]: # Easy to get portfolio subsets such as long/short, winner/losers port.long.positions.frame.tail() # In[15]: # Get a specific position pos = port.long.positions[57] # In[20]: # Get txn level detail associated with the position pos.pl.txn_frame.head() # ### Simple Report Provided (can add own splits but Long/Short, Win/Loss included) # In[21]: summary = model.PortfolioSummary() # defaults included are long/short, win/loss but can provide a method to split as like summary.include_long_short().include_win_loss() # a few simple stats methods provided but easy to create own analyze_fct = model.PortfolioSummary.analyze_returns rpt = summary(port, analyze_fct) FMT(rpt.T) # ### Some graphs # In[22]: tmp = pd.DataFrame({'Long': port.long.pl.ltd_dly, 'Short': port.short.pl.ltd_dly, 'All': port.pl.ltd_dly}) _ = tmp.plot(title='P&L') # In[24]: # Show Daily Drawdowns port.pl.dly_details.plot_ltd() plt.title('P&L Drawdown') # In[28]: port.performance.dly_details.plot_ret_on_dollar(label='All') 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', prop={'size':12}) plt.title('Return on $1') # In[39]: # Show the LTD Returns port.performance.dly_details.plot_ltd() # In[47]: # Show the Monthly Return Histogram port.performance.monthly_details.plot_hist(figsize=(7, 3)) # In[50]: # See the range of returns for the positions fig, ax = plt.subplots(1, 1, figsize=(9, 3)) port.positions.plot_ret_range(ax=ax) plt.title('Position Return Range')