<jupyter_start><jupyter_text>Example of using the model moduleThis 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.<jupyter_code>import tia.analysis.model as model
import pandas as pd

from tia.util.fmt import new_dynamic_formatter, DynamicColumnFormatter
%matplotlib inline
import matplotlib.pyplot as plt
try:
    plt.style.use('fivethirtyeight')
    plt.rcParams['lines.linewidth'] = 1.4
except:
    pass
# Load microsoft - note it retrieves the dividends too
msft = model.load_yahoo_stock('MSFT', start='1/1/2010')
msft.pxs.frame.tail()
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')
#
# 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:]
# Build the portfolio
port = model.SingleAssetPortfolio(msft, trades)
# show the ltd transaction level pl frame
port.pl.ltd_txn_frame.tail()
# show the daily pl frame (rolled up by day)
port.pl.dly_frame.tail()
# show the positions
F = new_dynamic_formatter(method='col', pcts=1, parens=0, trunc_dot_zeros=1)
F(port.positions.frame.tail(4))
# 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)
FMT = new_dynamic_formatter(method='row', precision=2, pcts=1, trunc_dot_zeros=1)
# 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)
# show the position stats
port.positions.stats
# Easy to get portfolio subsets such as long/short, winner/losers
port.long.positions.frame.tail()
# Get a specific position
pos = port.long.positions[57]

# Get txn level detail associated with the position
pos.pl.txn_frame.head()<jupyter_output><empty_output><jupyter_text>Simple Report Provided (can add own splits but Long/Short, Win/Loss included)<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>Some graphs<jupyter_code>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')
# Show Daily Drawdowns
port.pl.dly_details.plot_ltd()
plt.title('P&L Drawdown')
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')
# Show the LTD Returns
port.performance.dly_details.plot_ltd()

# Show the Monthly Return Histogram
port.performance.monthly_details.plot_hist(figsize=(7, 3))
# 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')<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup