<jupyter_start><jupyter_text><jupyter_code>%pip install yfinance
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from itertools import product


# %pip install ta-lib
# %pip install zipline
#Trading Libraries
# import talib #Technical Analysis Libraries: Bollinger Bands, Aroon Oscillator, MACD (MA Convergence/Divergence), RSI (Relative Strength Index)
# import zipline #Backtesting and Live Trading<jupyter_output>Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (0.1.59)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance) (0.0.9)
Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.7/dist-packages (from yfinance) (2.23.0)
Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.1.5)
Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance) (4.6.3)
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.19.5)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (1.24.3)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/pyt[...]<jupyter_text>Backtesting Helper Functions<jupyter_code>def backtest_strategy(data, sma, lma):
    data['daily_returns'] = data['Adj Close'].pct_change()

    data['sma'] = data['Adj Close'].rolling(sma).mean()
    data['lma'] = data['Adj Close'].rolling(lma).mean()

    data['signals'] = np.where(data['sma'] >= data['lma'], 1, -1)

    data.dropna(inplace = True)

    data['strategic_returns'] = data['daily_returns'] * data['signals'].shift(1)
    
    cum_s_returns = (data['strategic_returns']+ 1).cumprod()

    return round(cum_s_returns.iloc[-1] -1, 3)

def cumm_returns(ticker_list, sma, lma, start_string, end_string):
    returns = dict()
    for ticker in ticker_list:
        data = yf.download(ticker, start_string, end_string)

        ticker_return = backtest_strategy(data, sma, lma)

        print(f'Cummulative Strategy Returns for {ticker}:', ticker_return)

        returns[ticker] = ticker_return
    else:
        print('Computations Completed!')

def visualize_returns(ticker_list, sma, lma, start_string, end_string):
    returns = dict()
    colors = list()

    for ticker in ticker_list:
        data = yf.download(ticker, start_string, end_string)

        ticker_return = backtest_strategy(data, sma, lma)

        print(f'Cummulative Strategy Returns for {ticker}:', ticker_return)

        returns[ticker] = ticker_return
    
    #colors for visualization
    for k, v in returns.items():
        if v > 0:
            colors.append('lightgreen')
        else:
            colors.append('lightcoral')
    
    plt.figure(figsize = (14,7))
    plt.bar(returns.keys(), returns.values(), color = colors)
    plt.title('MAC Returns on stocks')
    plt.xlabel('Stocks')
    plt.ylabel('Returns')
    plt.show()

def optimize(data, sma_range, lma_range):
    best_returns = -.99
    best_sma = 0
    best_lma = 0
    
    for x in product(sma_range, lma_range):
        sma_val = x[0]
        lma_val = x[1]
       
        print(f'SMA value: {sma_val} and LMA value: {lma_val}')
        returns = backtest_strategy(data, sma_val, lma_val)

        if returns > best_returns:
            best_returns = returns
            best_sma = sma_val
            best_lma = lma_val
        
    return best_returns, best_sma, best_lma

def test_optimize(stock_list, start_string, end_string, sma_range, lma_range):
    ret_values = {}
    sma_values = {}
    lma_values = {}

    for stock in stock_list:
        data = yf.download(stock, start = start_string, end = end_string)

        net_returns, b_sma, b_lma = optimize(data, sma_range, lma_range)

        print(f'Cummulative strategy returns for {stock}:', net_returns)

        ret_values[stock] = net_returns
        sma_values[stock] = b_sma
        lma_values[stock] = b_lma
    else:
        print('Computations completed!')
        print(f'The final values are as follows: \n{ret_values}\n {sma_values}\n {lma_values}')
sma = 14
lma = 60

start = '2016-01-01'
end = '2021-10-21'

#current total range is 20?
sma_range = range(2, 12, 2)
lma_range = range(60, 80, 5)<jupyter_output><empty_output><jupyter_text>Travel (Airlines)- Delta (DAL)- United Airlines (UAL)- Spirit (SAVE)- American Airlines (AAL)- Alaska Airlines (ALK)<jupyter_code>airlines = ['DAL', 'UAL', 'SAVE', 'AAL', 'ALK']
# airlines = ['DAL']
visualize_returns(airlines, sma, lma, start, end)
test_optimize(airlines, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for DAL: 0.189
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for UAL: -0.01
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for SAVE: 0.646
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for AAL: 0.423
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for ALK: 0.37
Computations completed!
The final values are as follows: 
{'DAL': 0.189, 'UAL': -0.01, 'SAVE': 0.646, 'AAL': 0.423, 'ALK': 0.37}
 {'DAL': 10, 'UAL': 10, 'SAVE': 4, 'AAL': 10, 'ALK': 6}
 {'DAL': 70, 'UAL': 75, 'SAVE': 60, 'AAL': 70, 'ALK': 70}<jupyter_text>Finance (Traditional - Banks)- Wells Fargo (WF)- JPMorgan Chase (JPM)- Bank of America (BAC)- Citi (C)<jupyter_code>banks = ['WF', 'JPM', 'BAC', 'C']
visualize_returns(banks, sma, lma, start, end)
test_optimize(banks, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for WF: 0.106
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for JPM: 0.529
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for BAC: 0.42
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for C: 0.953
Computations completed!
The final values are as follows: 
{'WF': 0.106, 'JPM': 0.529, 'BAC': 0.42, 'C': 0.953}
 {'WF': 10, 'JPM': 6, 'BAC': 10, 'C': 4}
 {'WF': 75, 'JPM': 75, 'BAC': 70, 'C': 60}<jupyter_text>Telecommunications (Wireless Carriers)- AT&T (T)- Verizon (VZ)- T-mobile (TMUS)<jupyter_code>telecoms = ['T', 'VZ', 'TMUS']
visualize_returns(telecoms, sma, lma, start, end)
test_optimize(telecoms, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for T: 0.012
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for VZ: -0.024
[*********************100%***********************]  1 of 1 completed
Cummulative strategy returns for TMUS: 0.101
Computations completed!
The final values are as follows: 
{'T': 0.012, 'VZ': -0.024, 'TMUS': 0.101}
 {'T': 4, 'VZ': 10, 'TMUS': 8}
 {'T': 75, 'VZ': 75, 'TMUS': 75}<jupyter_text>Travel (Auto)- Tesla (TSLA)- Ford (F)- BMW (BMWYY)- Toyota (TM)- Honda (HMC)- Nio (NIO)<jupyter_code>autos = ['TSLA', 'F', 'TM', 'HMC', 'NIO', 'BMWYY']
visualize_returns(autos, sma, lma, start, end)
test_optimize(autos, start, end, sma_range, lma_range)
data = yf.download('TSLA', start, end)
# len(data)
backtest_strategy(data, 6, 75)
# start<jupyter_output>[*********************100%***********************]  1 of 1 completed<jupyter_text>HealthCare*   Hospital conglomerates*   Insurance companies*   Institutional services* Drug Manufacturers*   Medical instrument makers*   Biomedical companies**52.3% CAGR** with advent of AI<jupyter_code>healthcare = ['SNSE', 'PDSB', 'LFMD', 'PROG', 'GTH', 'DBTX', 'IMMP', 'PRPO', 'IMAB']
visualize_returns(healthcare, sma, lma, start, end)
test_optimize(healthcare, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65<jupyter_text>Computer and Tech (IT)*   Product Manufacturers*   Service Providers**22% CAGR potential**<jupyter_code>it = ['INTZ', 'LSPD', 'TLS', 'AUUD', 'CPSH', 'TAIT', 'AMPG', 'QRVO']
visualize_returns(it, sma, lma, start, end)
test_optimize(it, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA value: 4 and LMA value: 70
SMA value: 4 and LMA value: 75
SMA value: 6 and LMA value: 60
SMA value: 6 and LMA value: 65
SMA value: 6 and LMA value: 70
SMA value: 6 and LMA value: 75
SMA value: 8 and LMA value: 60
SMA value: 8 and LMA value: 65
SMA value: 8 and LMA value: 70
SMA value: 8 and LMA value: 75
SMA value: 10 and LMA value: 60
SMA value: 10 and LMA value: 65
SMA value: 10 and LMA value: 70
SMA value: 10 and LMA value: 75
Cummulative strategy returns for INTZ: 2.634
[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70<jupyter_text>Business Services<jupyter_code>busiserv = ['BRPA', 'LMFA', 'OXBR', 'GHVI', 'BTCM', 'TIG', 'MFH', 'LYL', 'AMRK', 'FDBC']
busiserv_down = ['HFBL', 'BHV', 'RICE', 'ASPS', 'VERY', 'EMCF', 'MN', 'AEL']
visualize_returns(busiserv, sma, lma, start, end)
cumm_returns(busiserv_down, sma, lma, start, end)
test_optimize(busiserv, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA value: 4 and LMA value: 70
SMA value: 4 and LMA value: 75
SMA value: 6 and LMA value: 60
SMA value: 6 and LMA value: 65
SMA value: 6 and LMA value: 70
SMA value: 6 and LMA value: 75
SMA value: 8 and LMA value: 60
SMA value: 8 and LMA value: 65<jupyter_text>Fast Moving Consumer Goods (FMCG)<jupyter_code>fmcg = ['PLIN', 'REDU', 'HIMS', 'HRL', 'UG', 'AMBO', 'FEDU', 'CELH', 'PETZ', 'CLEU']
fmcg_down = ['COE', 'LXEH', 'PME', 'REED', 'BJ', 'METX', 'ONE', 'RLX']
visualize_returns(fmcg, sma, lma, start, end)
cumm_returns(fmcg_down, sma, lma, start, end)
test_optimize(fmcg, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA value: 4 and LMA value: 70<jupyter_text>Consumer DiscretionaryAKA cylical consumer stocks<jupyter_code>cd = ['BBQ', 'BBIG', 'MRM', 'FORD', 'OCG', 'CATO', 'AUVI', 'RICK', 'POSH', 
      'DIS', 'HLT', 'WMT']
cd_down = ['RIDE', 'FOSL', 'KSS', 'ANF', 'RL', 'URBN', 'JWN', 'LOTZ', 'LCUT']
visualize_returns(cd, sma, lma, start, end)
visualize_returns(cd_down, sma, lma, start, end)
test_optimize(cd, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA value: 4 and LMA value: 70
SMA value: 4 and LMA value: 75
SMA value: 6 and LMA value: 60
SMA value: 6 and LMA value: 65
SMA value: 6 and LMA value: 70
SMA value: 6 and LMA value: 75
SMA value: 8 and LMA value: 60
SMA value: 8 and LMA value: 65
SMA value: 8 and LMA value: 70
SMA value: 8 and LMA value: 75
SMA value: 10 and LMA value: 60
SMA value: 10 and LMA value: 65
SMA value: 10 and LMA value: 70
SMA value: 10 and LMA value: 75
Cummulative strategy returns for BBQ: 2.154
[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA valu[...]<jupyter_text>Real Estate<jupyter_code>real_estate = ['O', 'SPG', 'PSA', 'DLR', 'AMT', 'STAG', 'NTP', 'IHT',
               'AEI', 'CBRE', 'QK', 'HT', 'SKT', 'XHR']
test_optimize(real_estate, start, end, sma_range, lma_range)
visualize_returns(real_estate, sma, lma, start, end)<jupyter_output>[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for O: -0.32
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for SPG: -0.474
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for PSA: -0.218
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for DLR: -0.342
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for AMT: -0.442
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for STAG: 0.478
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for NTP: 2.814
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Returns for IHT: -0.994
[*********************100%***********************]  1 of 1 completed
Cummulative Strategy Re[...]<jupyter_text>Materials<jupyter_code>materials=['VALE', 'HUN', 'SCCO', 'FCX', 'ECL', 'APD', 'DD', 'XLB', 'CE', 'NEU', 'SCCO',
           'NUE', 'RPM', 'CC', 'OLN', 'XLB', 'RIO', 'LYB', 'IP', ]
visualize_returns(materials, sma, lma, start, end)
test_optimize(materials, start, end, sma_range, lma_range)<jupyter_output>[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA value: 4 and LMA value: 70
SMA value: 4 and LMA value: 75
SMA value: 6 and LMA value: 60
SMA value: 6 and LMA value: 65
SMA value: 6 and LMA value: 70
SMA value: 6 and LMA value: 75
SMA value: 8 and LMA value: 60
SMA value: 8 and LMA value: 65
SMA value: 8 and LMA value: 70
SMA value: 8 and LMA value: 75
SMA value: 10 and LMA value: 60
SMA value: 10 and LMA value: 65
SMA value: 10 and LMA value: 70
SMA value: 10 and LMA value: 75
Cummulative strategy returns for VALE: 0.858
[*********************100%***********************]  1 of 1 completed
SMA value: 2 and LMA value: 60
SMA value: 2 and LMA value: 65
SMA value: 2 and LMA value: 70
SMA value: 2 and LMA value: 75
SMA value: 4 and LMA value: 60
SMA value: 4 and LMA value: 65
SMA val[...]<jupyter_text>Utilities/ Energy* Duke Electric<jupyter_code>util = ['NEE', 'CVX', 'DUK', 'D', 'XEL', 'XLU', 'SRE', 'VST', 'UGI', 'WTRG', 'EIX', 'AEP', 
        'AES', 'CNP', 'DTE', 'ETR', 'IDA', 'NFG', 'NI', 'NRG', 'NOVA', 'AWK', 'BIP', 'NEE']
visualize_returns(util, sma, lma, start, end)
test_optimize(util, start, end, sma_range, lma_range)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.21235297898322514, 'fraction_numerical': 0.05032457098785269, 'mean_word_length': 4.871698113207547, 'pattern_counts': {'":': 0, '<': 47, '<?xml version=': 0, '>': 60, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 1}, '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': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '322942', 'license': 'MIT', 'n_tokens_mistral': 6360, 'n_tokens_neox': 5601, 'n_words': 1821, 'path': 'Industry_Analysis.ipynb', 'repo_name': 'siddley1001/Investing', 'size': '15559'}