<jupyter_start><jupyter_text>Double 7's Portfolio        (optimize period)<jupyter_code>import pandas as pd
import matplotlib.pyplot as plt
import datetime
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>#symbols = ['XLB', 'XLE', 'XLF', 'XLI', 'XLK', 'XLP', 'XLU', 'XLV', 'XLY']
#symbols = ['IWB', 'SPY', 'VGK', 'IEV', 'EWJ', 'EPP', 'IEF', 'SHY', 'GLD']
#symbols = ['FB', 'AMZN', 'NFLX', 'GOOG']
symbols = ['SPY', 'QQQ', 'TLT', 'GLD']
#symbols = ['SPY']

capital = 10000
start = datetime.datetime(1900, 1, 1)
#start = datetime.datetime.strptime(pf.SP500_BEGIN, '%Y-%m-%d')
end = datetime.datetime.now()
#end = datetime.datetime(2019, 1, 1)
period = 6

use_cache = True
use_regime_filter = True
use_vola_weight = True<jupyter_output><empty_output><jupyter_text>Define Optimizations<jupyter_code># pick one
optimize_period = True

# define period
if optimize_period:
    Xs = range(3, 18+1, 1)
    Xs = [str(X) for X in Xs]<jupyter_output><empty_output><jupyter_text>Run Strategy<jupyter_code>strategies = pd.Series(dtype=object)
for X in Xs:
    print("{0}".format(X), end=" ")
    if optimize_period:
        strategies[X] = strategy.Strategy(symbols, capital, start, end, margin=3, period=int(X),
                                          use_cache=use_cache, use_regime_filter=use_regime_filter,
                                          use_vola_weight=use_vola_weight)
    strategies[X].run()
    strategies[X].rlog, strategies[X].tlog, strategies[X].dbal = strategies[X].get_logs()
    strategies[X].stats = strategies[X].get_stats()<jupyter_output>3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18<jupyter_text>Summarize results<jupyter_code>metrics = ('annual_return_rate',
           'max_closed_out_drawdown',
           'annualized_return_over_max_drawdown',
           'best_month',
           'worst_month',
           'sharpe_ratio',
           'sortino_ratio',
           'monthly_std',
           'pct_time_in_market',
           'total_num_trades',
           'pct_profitable_trades',
           'avg_points')

df = strategy.summary(strategies, metrics)
df<jupyter_output><empty_output><jupyter_text>Bar graphs<jupyter_code>strategy.plot_bar_graph(df, 'annual_return_rate')
strategy.plot_bar_graph(df, 'sharpe_ratio')
strategy.plot_bar_graph(df, 'max_closed_out_drawdown')<jupyter_output><empty_output><jupyter_text>Run Benchmark<jupyter_code>s = strategies[Xs[0]]
benchmark = pf.Benchmark('SPY', capital, s.start, s.end, use_adj=True)
benchmark.run()<jupyter_output><empty_output><jupyter_text>Equity curve<jupyter_code>if optimize_period: Y = '7'

pf.plot_equity_curve(strategies[Y].dbal, benchmark=benchmark.dbal)
def plot_equity_curves(strategies):
    """
    Plot Equity Curve: multiple equity curves on same plot
    Arguement is daily balance.
    """
    fig = plt.figure(figsize=(16,12))
    axes = fig.add_subplot(111, ylabel='Portfolio value in $')
    for strategy in strategies:
        axes.plot(strategy.dbal['close'], label=strategy.period)

    plt.legend(loc='best')
plot_equity_curves(strategies[3:10:2])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13198110586273964, 'fraction_numerical': 0.02000555709919422, 'mean_word_length': 4.413533834586466, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '539031', 'license': 'MIT', 'n_tokens_mistral': 1376, 'n_tokens_neox': 1303, 'n_words': 263, 'path': 'examples/double-7s-portfolio/optimize.ipynb', 'repo_name': 'tombohub/pinkfish', 'size': '3599'}