<jupyter_start><jupyter_text>A financial tool that can analyze and maximize investment portfolios on a risk adjusted basis  Description: This notebook is useful for examining potfolios comprised of stocks from the Nasdaq 100.  Construct portfolios from the 100 stocks in the Nasdaq 100 and examine the results of different weighting schemes.<jupyter_code>%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
    return false;
}
# imports
import pandas as pd
import matplotlib.pyplot as plt
import brownbear as bb

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

# display all rows
pd.set_option('display.max_rows', None)

# do not truncate column names
pd.set_option('display.max_colwidth', None)

%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 Globals<jupyter_code>investment_universe = ['nasdaq100-galaxy']
risk_free_rate = 0
annual_returns = '3 Yr'
vola = 'Vola'
ds_vola = 'DS Vola'
# Fetch Investment Options - all values annualized
df = bb.fetch(investment_universe, risk_free_rate, annual_returns, vola, ds_vola)
df
# rank
rank = bb.rank(df, rank_by='Sharpe Ratio', group_by=None, num_per_group=50)
rank_filtered = rank
rank_filtered = rank.loc[(rank['3 mo'] > 0) & rank['1 Yr'] > 0]
rank_filtered = rank_filtered.head(20)
rank_filtered<jupyter_output><empty_output><jupyter_text>Sample PortfoliosFormat 'Investment option': weight<jupyter_code># everything ranked
ranked_portfolio = {
    'Title': 'Ranked Portfolio'
}
everything = list(rank_filtered['Investment Option'])
ranked_portfolio.update(dict.fromkeys(everything, 1/len(everything)))

# top 10
top10_portfolio = {
    'Title': 'Ranked Portfolio'
}
top10 = list(rank_filtered['Investment Option'])[:10]
top10_portfolio.update(dict.fromkeys(top10, 1/len(top10)))<jupyter_output><empty_output><jupyter_text>Custom Portfolios<jupyter_code># My portfolio
my_portfolio = {
    'Title': 'My Portfolio',

}<jupyter_output><empty_output><jupyter_text>Choose Portfolio Option<jupyter_code># Select one of the portfolios from above
portfolio_option = top10_portfolio
# Make a copy so that the original portfolio is preserved
portfolio_option = portfolio_option.copy()<jupyter_output><empty_output><jupyter_text>Analysis Options<jupyter_code># Specify the weighting scheme.  It will replace the weights specified in the portfolio
# You can also fix the weights on some Investent Options, Asset Classes, and Asset Subclasses
# while the others are automatically calculated.

# 'Equal' - will use equal weights.

# 'Sharpe Ratio' - will use proportionally weighted # allocations based on the percent
#  of an investment option's sharpe ratio to the sum of all the sharpe ratios in the portfolio.

# 'Std Dev' - will use standard deviation adjusted weights

# 'Annual Returns' - will use return adjusted weights

# 'Vola' - will use volatility adjusted weights

# 'DS Vola' - will use downside volatility adjusted weights

# None: 'Investment Option' means use user specified weights
#       'Asset Class' means do not group by Asset Class
#       'Asset Subclass means do not group by Asset Subclass 

weight_by = {
    'Asset Class':       {'weight_by': None},
    'Asset Subclass':    {'weight_by': None},
    'Investment Option': {'weight_by': 'DS Vola'},
}
#weight_by = None
bb.DEBUG = False

# Analyze portfolio
annual_ret, std_dev, sharpe_ratio = \
    bb.analyze(df, portfolio_option, weight_by)
# Display Results
summary = bb.summary(df, portfolio_option, annual_ret, std_dev, sharpe_ratio)
summary
# Show pie charts of investment and asset class weights
bb.show_pie_charts(df, portfolio_option, charts=['Investment Option'])
# Show exact weights
bb.print_portfolio(portfolio_option)<jupyter_output>Ranked Portfolio Weights:
    MRNA                           0.0852
    MSFT                           0.1273
    ASML                           0.0706
    TMUS                           0.1056
    SNPS                           0.0971
    CHTR                           0.1269
    CDNS                           0.0908
    COST                           0.1567
    PYPL                           0.0890
    TSLA                           0.0507<jupyter_text>Optimize Portfolio<jupyter_code># Run_portfolio_optimizer = True will run portfolio optimizer after portfolio analysis is complete
run_portfolio_optimizer = True
# Optimize sharpe ratio while specifying Annual Rate, Worst Typical Down Year,
# and Black Swan.  Setting a constraint to None optimizes absolute Sharpe Ratio
# without regard to that constraint.

'''
constraints = {
    'Annual Return': 12,
    'Worst Typical Down Year': -5,
    'Black Swan': None
}
'''

constraints = {
    'Annual Return': 8,
    'Worst Typical Down Year': None,
    'Black Swan': -40
}

if run_portfolio_optimizer:
    bb.optimizer(df, portfolio_option, constraints)<jupyter_output>Running optimizer...........

Ranked Portfolio Metrics:           
    max_sharpe_ratio            2.20
    annual_return              99.08
    std_dev                    44.94
    worst typical down year     9.20
    black_swan                -35.73


Ranked Portfolio Weights:
    MRNA                           0.2900
    MSFT                           0.2500
    ASML                           0.1900
    TMUS                           0.0500
    SNPS                           0.1300
    CHTR                           0.0900
    CDNS                           0.0000
    COST                           0.0000
    PYPL                           0.0000
    TSLA                           0.0000
{'fraction_non_alphanumeric': 0.07909891598915988, 'fraction_numerical': 0.028624661246612466, 'mean_word_length': 2.8469055374592833, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '655707', 'license': 'MIT', 'n_tokens_mistral': 1897, 'n_tokens_neox': 1733, 'n_words': 541, 'path': 'portfolios/nasdaq100/portfolio.ipynb', 'repo_name': 'fja05680/brownbear', 'size': '5904'}