<jupyter_start><jupyter_text>Weight By Portfolio StrategyBasic buy and hold that allows weighting by user specified weights, Equal, Sharpe Ratio, Annual Returns, Std Dev, Vola, or DS Vola.  Rebalance is yearly, monthly, weekly, or daily.  Option to sell all shares of an investment is regime turns negative.<jupyter_code>import datetime

import matplotlib.pyplot as plt
import pandas as pd
from talib.abstract import *

import pinkfish as pf
import strategy

# Format price data.
pd.options.display.float_format = '{:0.2f}'.format

%matplotlib inline
# Set size of inline plots.
'''note: rcParams can't be in same cell as import matplotlib
   or %matplotlib inline
   
   %matplotlib notebook: will lead to interactive plots embedded within
   the notebook, you can zoom and resize the figure
   
   %matplotlib inline: only draw static images in the notebook
'''
plt.rcParams["figure.figsize"] = (10, 7)<jupyter_output><empty_output><jupyter_text>Some global data<jupyter_code># Symbol Lists.
SP500_Sectors = \
    {'XLB': None, 'XLE': None, 'XLF': None, 'XLI': None,
     'XLK': None, 'XLP': None, 'XLU': None, 'XLV': None, 'XLY': None}

Mixed_Asset_Classes = \
    {'IWB': None, 'SPY': None, 'VGK': None, 'IEV': None,
     'EWJ': None, 'EPP': None, 'IEF': None, 'SHY': None, 'GLD': None}
FANG_Stocks = \
    {'FB': None, 'AMZN': None, 'NFLX': None, 'GOOG': None}

Stocks_Bonds_Gold = \
    {'SPY': None, 'QQQ': None, 'TLT': None, 'GLD': None}

Stocks_Bonds = \
    {'SPY': 0.50, 'AGG': 0.50}

# Pick one of the above.
weights = Stocks_Bonds_Gold
symbols = list(weights)

capital = 100_000
start = datetime.datetime(*pf.ALPHA_BEGIN)
#start = datetime.datetime(*pf.SP500_BEGIN)
end = datetime.datetime.now()
weight_by_choices = ('equal', 'sharpe', 'ret', 'sd', 'vola', 'ds_vola')
rebalance_choices = ('yearly', 'monthly', 'weekly', 'daily')

options = {
    'use_adj'           : True,
    'use_cache'         : True,
    'margin'            : 1,
    'weights'           : weights,
    'weight_by'         : 'vola',
    'rebalance'         : 'monthly',
    'use_regime_filter' : False
}<jupyter_output><empty_output><jupyter_text>Run Strategy<jupyter_code>s = strategy.Strategy(symbols, capital, start, end, options=options)
s.run()<jupyter_output><empty_output><jupyter_text>View log DataFrames: raw trade log, trade log, and daily balance.<jupyter_code>s.rlog.head()
s.tlog.tail()
s.dbal.tail()<jupyter_output><empty_output><jupyter_text>Generate strategy stats - display all available stats.<jupyter_code>pf.print_full(s.stats)<jupyter_output>start                                                   2007-11-20
end                                                     2021-07-14
beginning_balance                                           100000
ending_balance                                           422395.68
total_net_profit                                         322395.68
gross_profit                                             384990.90
gross_loss                                               -62595.21
profit_factor                                                 6.15
return_on_initial_capital                                   322.40
annual_return_rate                                           11.13
trading_period                           13 years 7 months 24 days
pct_time_in_market                                          100.00
margin                                                           1
avg_leverage                                                  1.00
max_leverage                                                  [...]<jupyter_text>View Performance by Symbol<jupyter_code>symbols_no_weights = [k for k,v in weights.items() if v is None]
symbols_weights    = {k:v for k,v in weights.items() if v is not None}
remaining_weight   = 1 - sum(symbols_weights.values())

weights_ = weights.copy()
for symbol in symbols_no_weights:
    weights_[symbol] = (1 / len(symbols_no_weights)) * remaining_weight
totals = s.portfolio.performance_per_symbol(weights=weights_)
totals
corr_df = s.portfolio.correlation_map(s.ts)
corr_df<jupyter_output><empty_output><jupyter_text>Run Benchmark, Retrieve benchmark logs, and Generate benchmark stats.<jupyter_code>benchmark = pf.Benchmark('SPY', s.capital, s.start, s.end, use_adj=True)
benchmark.run()<jupyter_output><empty_output><jupyter_text>Plot Equity Curves: Strategy vs Benchmark<jupyter_code>pf.plot_equity_curve(s.dbal, benchmark=benchmark.dbal)<jupyter_output><empty_output><jupyter_text>Bar Graph: Strategy vs Benchmark<jupyter_code>df = pf.plot_bar_graph(s.stats, benchmark.stats)
df<jupyter_output><empty_output><jupyter_text>Analysis: Kelly Criterian<jupyter_code>kelly = pf.kelly_criterion(s.stats, benchmark.stats)
kelly<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.106553911205074, 'fraction_numerical': 0.022198731501057084, 'mean_word_length': 2.6059451219512195, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 27, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '177947', 'license': 'MIT', 'n_tokens_mistral': 1590, 'n_tokens_neox': 1464, 'n_words': 360, 'path': 'examples/225.weight-by-portfolio/strategy.ipynb', 'repo_name': 'fja05680/pinkfish', 'size': '4730'}