├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── amex_tickers.csv ├── chromedriver ├── find_stocks ├── IBD_RS_Rating.py ├── correlated_stocks.py ├── finviz_growth_screener.py ├── fundamental_screener.py ├── get_rsi_tickers.py ├── green_line_values.py ├── minervini_screener.py ├── price_alert_email.py ├── stock_news_sentiment.py ├── tradingview_signals.py ├── twitter_screener.py └── yahoo_recommendations.py ├── machine_learning ├── arima_time_series.py ├── deep_learning_bot.py ├── etf_graphical_lasso.py ├── kmeans_clustering.py ├── lstm_prediction.py ├── ml_models_accuracy.py ├── neural_network_prediction.py ├── pca_kmeans_clustering.py ├── prophet_price_prediction.py ├── quantitative_indicators_prediction.py ├── sklearn_trading_bot.py ├── sp500_pca_analysis.py ├── stock_probabilistic_analysis.py ├── stock_regression_analysis.py ├── stocker_price_prediction.py └── technical_indicators_clustering.py ├── nasdaq_tickers.csv ├── nyse_tickers.csv ├── portfolio_strategies ├── astral_timing_signals.py ├── backtest_strategies.py ├── backtrader_backtest.py ├── best_moving_averages_analysis.py ├── ema_crossover_strategy.py ├── factor_analysis.py ├── financial_signal_analysis.py ├── geometric_brownian_motion.py ├── long_hold_stats_analysis.py ├── ls_dca_analysis.py ├── monte_carlo.py ├── moving_average_crossover_signals.py ├── moving_avg_strategy.py ├── optimal_portfolio.py ├── optimized_bollinger_bands.py ├── pairs_trading.py ├── portfolio_analysis.py ├── portfolio_optimization.py ├── portfolio_var_simulation.py ├── risk_management.py ├── robinhood_bot.py ├── rsi_trendline_strategy.py ├── rwb_strategy.py ├── sma_trading_strategy.py ├── stock_spread_plotter.py └── support_resistance_finder.py ├── requirements.txt ├── russell3000_tickers.csv ├── s&p500_tickers.csv ├── stock_analysis ├── backest_all_indicators.py ├── capm_analysis.py ├── earnings_call_sentiment_analysis.py ├── estimating_returns.py ├── intrinsic_value.py ├── kelly_criterion.py ├── ma_backtesting.py ├── ols_regression.py ├── performance_risk_analysis.py ├── risk_vs_returns.py ├── seasonal_stock_analysis.py ├── sma_histogram.py ├── sp500_cot_sentiment_analysis.py ├── sp500_valuation.py ├── stock_pivot_resistance.py ├── stock_profit_loss.py ├── stock_returns_statistical_analysis.py ├── twitter_sentiment_analysis.py ├── var_analysis.py └── view_stock_returns.py ├── stock_data ├── autoscraper_finviz_data.py ├── dividend_history.py ├── fibonacci_retracement.py ├── finviz_home_scraper.py ├── finviz_insider_trades.py ├── finviz_news_scraper.py ├── finviz_stock_scraper.py ├── fundamental_ratios.py ├── get_dividend_calendar.py ├── green_line_test.py ├── high_dividend_yield.py ├── historical_sp500_data.py ├── main_indicators_one_graph.py ├── main_indicators_streamlit.py ├── pivots_calculator.py ├── reddit_scraper.py ├── send_top_movers.py ├── stock_VWAP.py ├── stock_data_sms.py ├── stock_earnings.py ├── stock_twilio_server.py ├── tradingview_intraday_data.py ├── tradingview_recommendations.py └── yf_intraday_data.py ├── ta_functions.py ├── technical_indicators ├── EMA.py ├── EMA_volume.py ├── EWMA.py ├── EWMA_Double.py ├── EWMA_Triple.py ├── GANN_lines_angles.py ├── GMMA.py ├── MACD.py ├── MA_high_low.py ├── MFI.py ├── PVI.py ├── PVT.py ├── ROC.py ├── ROI.py ├── RSI.py ├── RSI_BollingerBands.py ├── SMA.py ├── TRIMA.py ├── TWAP.py ├── VWAP.py ├── WMA.py ├── WSMA.py ├── Z_Score_Indicator.py ├── absolute_price_oscillator.py ├── acceleration_bands.py ├── accum_dist_line.py ├── aroon.py ├── aroon_oscillator.py ├── avg_directional_index.py ├── avg_true_range.py ├── balance_of_power.py ├── beta_indicator.py ├── bollinger_bands.py ├── bollinger_bandwidth.py ├── breadth_indicator.py ├── candle_abs_returns.py ├── central_pivot_range_cpr.py ├── chaikin_money_flow.py ├── chaikin_oscillator.py ├── commodity_channel_index.py ├── correlation_coeff.py ├── covariance.py ├── detrended_price_oscillator.py ├── donchain_channel.py ├── double_exp_moving_avg.py ├── dynamic_momentum_index.py ├── ease_of_movement.py ├── force_index.py ├── geometric_return_indicator.py ├── golden_death_cross.py ├── high_minus_low.py ├── hull_moving_average.py ├── keltners_channels.py ├── linear_regression.py ├── linear_regression_slope.py ├── linear_weighted_moving_average.py ├── mcclellan_oscillator.py ├── momentum.py ├── moving_average_envelopes.py ├── moving_average_high_low.py ├── moving_average_ribbon.py ├── moving_avg_env.py ├── moving_linear_regression.py ├── new_highs_new_lows.py ├── pivot_point.py ├── price_channels.py ├── price_relative.py ├── realised_volatility.py ├── relative_volatility_index.py ├── smoothed_moving_average.py ├── speed_resistance_lines.py ├── standard_deviation_volatility.py ├── stochastic_RSI.py ├── stochastic_fast.py ├── stochastic_full.py ├── stochastic_slow.py ├── super_trend.py ├── true_strength_index.py ├── ultimate_oscillator.py ├── variance_indicator.py ├── volume_price_confirmation_Indicator.py └── volume_weighted_moving_average.py └── tickers.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | stock_data/.DS_Store 3 | machine_learning/.DS_Store 4 | find_stocks/.DS_Store 5 | stock_analysis/.DS_Store 6 | portfolio_strategies/.DS_Store 7 | technical_indicators/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Shashank Vemuri 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Finance 2 | 3 | ## Introduction 4 | Welcome! Finance is a collection of 150+ Python for Finance programs for gathering, manipulating, and analyzing stock market data. 5 | 6 | Below you will find more information about how the repository is organized as well as usage and setup instructions! 7 | 8 | ## Organization 9 | Our repository is organized into several key sections: 10 | 11 | ### [find_stocks](/find_stocks) 12 | Programs to screen stocks based on technical and fundamental analysis. 13 | 14 | ### [machine_learning](/machine_learning) 15 | Introductory machine learning applications for stock classification and prediction. 16 | 17 | ### [portfolio_strategies](/portfolio_strategies) 18 | Simulations of trading strategies and portfolio analysis tools. 19 | 20 | ### [stock_analysis](/stock_analysis) 21 | Detailed analysis tools for individual stock assessment. 22 | 23 | ### [stock_data](/stock_data) 24 | Tools for collecting stock price action and company data via APIs and web scraping. 25 | 26 | ### [technical_indicators](/technical_indicators) 27 | Visual tools for popular technical indicators like Bollinger Bands, RSI, and MACD. 28 | 29 | ## Installation 30 | To get started, clone the repository and install the required dependencies: 31 | 32 | ```bash 33 | git clone https://github.com/shashankvemuri/Finance.git 34 | cd Finance 35 | pip install -r requirements.txt 36 | ``` 37 | 38 | ## Usage 39 | Detailed instructions on how to use each program can be found within their respective directories. Explore different modules to discover their functionalities. 40 | 41 | Each script in this collection is stand-alone. Here's how you can run a sample program: 42 | 43 | ```bash 44 | python example_program.py 45 | ``` 46 | 47 | ## Contributing 48 | Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. 49 | 50 | ## Authors 51 | - [@shashankvemuri](https://www.github.com/shashankvemuri) 52 | 53 | ## License 54 | This project is licensed under the [MIT License](LICENSE). 55 | 56 | ## Acknowledgements 57 | - [Stock_Analysis_For_Quant](https://github.com/LastAncientOne/Stock_Analysis_For_Quant/tree/master/Python_Stock/Technical_Indicators) by [LastAncientOne](https://github.com/LastAncientOne) 58 | 59 | ## Disclaimer 60 | *The material in this repository is for educational purposes only and should not be considered professional investment advice.* 61 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashankvemuri/Finance/12dac57c7f62146f7073ccc17f64bc45fd687b5d/__init__.py -------------------------------------------------------------------------------- /chromedriver: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shashankvemuri/Finance/12dac57c7f62146f7073ccc17f64bc45fd687b5d/chromedriver -------------------------------------------------------------------------------- /find_stocks/IBD_RS_Rating.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | import yfinance as yf 3 | import pandas as pd 4 | from pandas_datareader import data as pdr 5 | import datetime 6 | import time 7 | import sys 8 | import os 9 | parent_dir = os.path.dirname(os.getcwd()) 10 | sys.path.append(parent_dir) 11 | import tickers as ti 12 | 13 | # Override yfinance API for pandas datareader 14 | yf.pdr_override() 15 | 16 | # Retrieve S&P 500 tickers and format for Yahoo Finance 17 | sp500_tickers = ti.tickers_sp500() 18 | sp500_tickers = [ticker.replace(".", "-") for ticker in sp500_tickers] 19 | 20 | # Set S&P 500 index ticker 21 | sp500_index = '^GSPC' 22 | 23 | # Define date range for stock data 24 | start_date = datetime.datetime.now() - datetime.timedelta(days=365) 25 | end_date = datetime.date.today() 26 | 27 | # Initialize list for storing relative stock returns 28 | relative_returns = [] 29 | 30 | # Fetch and process S&P 500 historical data 31 | sp500_df = pdr.get_data_yahoo(sp500_index, start_date, end_date) 32 | sp500_df['Percent Change'] = sp500_df['Adj Close'].pct_change() 33 | sp500_cumulative_return = sp500_df['Percent Change'].cumprod().iloc[-1] 34 | 35 | # Compute relative returns for each S&P 500 stock 36 | for ticker in sp500_tickers: 37 | try: 38 | # Download stock data 39 | stock_df = pdr.get_data_yahoo(ticker, start_date, end_date) 40 | stock_df['Percent Change'] = stock_df['Adj Close'].pct_change() 41 | 42 | # Calculate cumulative return with added emphasis on recent quarter 43 | stock_cumulative_return = (stock_df['Percent Change'].cumprod().iloc[-1] * 2 + 44 | stock_df['Percent Change'].cumprod().iloc[-63]) / 3 45 | 46 | # Calculate relative return compared to S&P 500 47 | relative_return = round(stock_cumulative_return / sp500_cumulative_return, 2) 48 | relative_returns.append(relative_return) 49 | 50 | print(f'Ticker: {ticker}; Relative Return against S&P 500: {relative_return}') 51 | time.sleep(1) # Pause to prevent overloading server 52 | except Exception as e: 53 | print(f'Error processing {ticker}: {e}') 54 | 55 | # Create dataframe with relative returns and RS ratings 56 | rs_df = pd.DataFrame({'Ticker': sp500_tickers, 'Relative Return': relative_returns}) 57 | rs_df['RS_Rating'] = rs_df['Relative Return'].rank(pct=True) * 100 58 | print(rs_df) -------------------------------------------------------------------------------- /find_stocks/correlated_stocks.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import datetime as dt 3 | import numpy as np 4 | import pandas as pd 5 | import matplotlib.pyplot as plt 6 | from pandas_datareader import data as pdr 7 | import yfinance as yf 8 | import sys 9 | import os 10 | 11 | # Ensuring parent directory is in path for module import 12 | parent_dir = os.path.dirname(os.getcwd()) 13 | sys.path.append(parent_dir) 14 | import tickers as ti 15 | 16 | # Setting up date range for stock data 17 | num_of_years = 1 18 | start = dt.date.today() - dt.timedelta(days=int(365.25 * num_of_years)) 19 | end = dt.date.today() 20 | 21 | # Retrieve S&P 500 tickers and adjust ticker formatting 22 | tickers = ti.tickers_sp500() 23 | tickers = [item.replace(".", "-") for item in tickers] 24 | 25 | # Fetch and process stock data 26 | dataset = pdr.get_data_yahoo(tickers, start, end)["Adj Close"] 27 | stocks_returns = np.log(dataset / dataset.shift(1)) 28 | 29 | # Compute and print correlation matrix 30 | corr_matrix = stocks_returns.corr() 31 | print("\nCorrelation Matrix\n", corr_matrix) 32 | 33 | # Function to visualize correlation matrix as a heatmap 34 | def visualize_correlation_matrix(df_corr): 35 | data = df_corr.values 36 | plt.rcParams["figure.figsize"] = (15, 10) 37 | fig, ax = plt.subplots() 38 | heatmap = ax.pcolor(data, cmap=plt.cm.RdYlGn) 39 | fig.colorbar(heatmap) 40 | 41 | # Set axis ticks and labels 42 | ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) 43 | ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) 44 | ax.invert_yaxis() 45 | ax.xaxis.tick_top() 46 | ax.set_xticklabels(df_corr.columns, rotation=90) 47 | ax.set_yticklabels(df_corr.index) 48 | 49 | # Setting heatmap color limits 50 | heatmap.set_clim(-1, 1) 51 | plt.tight_layout() 52 | plt.show() 53 | 54 | visualize_correlation_matrix(corr_matrix) 55 | 56 | # Helper functions to identify top correlated stock pairs 57 | def get_redundant_pairs(df): 58 | pairs_to_drop = set() 59 | for i in range(df.shape[1]): 60 | for j in range(i + 1): 61 | pairs_to_drop.add((df.columns[i], df.columns[j])) 62 | return pairs_to_drop 63 | 64 | def get_top_abs_correlations(df, n=25): 65 | au_corr = df.abs().unstack() 66 | labels_to_drop = get_redundant_pairs(df) 67 | au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False) 68 | return au_corr[0:n] 69 | 70 | # Displaying top absolute correlations 71 | print("\nTop Absolute Correlations") 72 | print(get_top_abs_correlations(stocks_returns)) -------------------------------------------------------------------------------- /find_stocks/finviz_growth_screener.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import pandas as pd 3 | from bs4 import BeautifulSoup as soup 4 | from urllib.request import Request, urlopen 5 | 6 | # Set display options for pandas DataFrame 7 | pd.set_option('display.max_columns', None) 8 | pd.set_option('display.max_rows', None) 9 | 10 | def growth_screener(): 11 | try: 12 | frames = [] 13 | # Loop through different pages of FinViz growth screener 14 | for i in range(1, 105, 20): 15 | url = (f"https://finviz.com/screener.ashx?v=151&f=fa_epsqoq_o15,fa_epsyoy_pos,fa_epsyoy1_o25,fa_grossmargin_pos,fa_salesqoq_o25,ind_stocksonly,sh_avgvol_o300,sh_insttrans_pos,sh_price_o10,ta_perf_52w50o,ta_sma200_pa,ta_sma50_pa&ft=4&o=-marketcap&r=0{i}") 16 | req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 17 | webpage = urlopen(req).read() 18 | html = soup(webpage, "html.parser") 19 | 20 | # Extracting stock data from the HTML 21 | stocks = pd.read_html(str(html))[-2] 22 | stocks = stocks.set_index('Ticker') 23 | frames.append(stocks) 24 | 25 | # Concatenate all DataFrame objects from different pages 26 | df = pd.concat(frames) 27 | df = df.drop_duplicates() 28 | df = df.drop(columns=['No.']) 29 | return df 30 | except Exception as e: 31 | print(f"Error occurred: {e}") 32 | return pd.DataFrame() 33 | 34 | # Execute the screener and store the result 35 | df = growth_screener() 36 | 37 | # Display the results 38 | print('\nGrowth Stocks Screener:') 39 | print(df) 40 | 41 | # Extract and print list of tickers 42 | tickers = df.index 43 | print('\nList of Tickers:') 44 | print(*tickers, sep='\n') -------------------------------------------------------------------------------- /find_stocks/get_rsi_tickers.py: -------------------------------------------------------------------------------- 1 | # Import Dependencies 2 | import datetime 3 | from pandas_datareader import data as pdr 4 | import sys 5 | import os 6 | parent_dir = os.path.dirname(os.getcwd()) 7 | sys.path.append(parent_dir) 8 | import ta_functions as ta 9 | import tickers as ti 10 | 11 | # Get dates for the past year 12 | start_date = datetime.datetime.now() - datetime.timedelta(days=365) 13 | end_date = datetime.date.today() 14 | 15 | # Load list of S&P 500 tickers from tickers module 16 | tickers = ti.tickers_sp500() 17 | 18 | # Initialize lists for overbought and oversold tickers 19 | oversold_tickers = [] 20 | overbought_tickers = [] 21 | 22 | # Retrieve adjusted close prices for the tickers 23 | sp500_data = pdr.get_data_yahoo(tickers, start_date, end_date)['Adj Close'] 24 | 25 | # Analyze each ticker for RSI 26 | for ticker in tickers: 27 | try: 28 | # Create a new DataFrame for the ticker 29 | data = sp500_data[[ticker]].copy() 30 | 31 | # Calculate the RSI for the ticker 32 | data["rsi"] = ta.RSI(data[ticker], timeperiod=14) 33 | 34 | # Calculate the mean of the last 14 RSI values 35 | mean_rsi = data["rsi"].tail(14).mean() 36 | 37 | # Print the RSI value 38 | print(f'{ticker} has an RSI value of {round(mean_rsi, 2)}') 39 | 40 | # Classify the ticker based on its RSI value 41 | if mean_rsi <= 30: 42 | oversold_tickers.append(ticker) 43 | elif mean_rsi >= 70: 44 | overbought_tickers.append(ticker) 45 | 46 | except Exception as e: 47 | print(f'Error processing {ticker}: {e}') 48 | 49 | # Output the lists of oversold and overbought tickers 50 | print(f'Oversold tickers: {oversold_tickers}') 51 | print(f'Overbought tickers: {overbought_tickers}') -------------------------------------------------------------------------------- /find_stocks/green_line_values.py: -------------------------------------------------------------------------------- 1 | # Import Dependencies 2 | import datetime as dt 3 | import pandas as pd 4 | import pandas_datareader.data as pdr 5 | import sys 6 | import os 7 | parent_dir = os.path.dirname(os.getcwd()) 8 | sys.path.append(parent_dir) 9 | import tickers as ti 10 | 11 | # Set the date range for analysis 12 | now = dt.date.today() 13 | start_date = now - dt.timedelta(days=365) 14 | end_date = now 15 | 16 | # Retrieve S&P 500 tickers 17 | tickers = ti.tickers_sp500() 18 | tickers = [item.replace(".", "-") for item in tickers] 19 | 20 | # Initialize lists for tracking tickers and their green line values 21 | diff_5 = [] 22 | diff_5_tickers = [] 23 | 24 | # Analyze each ticker 25 | for ticker in tickers: 26 | try: 27 | print(f'Analyzing {ticker}:') 28 | 29 | # Load historical data 30 | df = pdr.get_data_yahoo(ticker) 31 | df.index = pd.to_datetime(df.index) 32 | price = df['Adj Close'][-1] 33 | 34 | # Filter out low volume data 35 | df = df[df["Volume"] >= 1000] 36 | 37 | # Calculate monthly high 38 | monthly_high = df.resample('M')['High'].max() 39 | 40 | # Initialize variables for tracking Green Line values 41 | last_green_line_value = 0 42 | last_green_line_date = None 43 | 44 | # Identify Green Line values 45 | for date, high in monthly_high.items(): 46 | if high > last_green_line_value: 47 | last_green_line_value = high 48 | last_green_line_date = date 49 | 50 | # Check if a green line value has been established 51 | if last_green_line_value == 0: 52 | message = f"{ticker} has not formed a green line yet" 53 | else: 54 | # Calculate the difference from the current price 55 | diff = (last_green_line_value - price) / price * 100 56 | message = f"{ticker}'s last green line value ({round(last_green_line_value, 2)}) is {round(diff, 1)}% different from its current price ({round(price, 2)})" 57 | if abs(diff) <= 5: 58 | diff_5_tickers.append(ticker) 59 | diff_5.append(diff) 60 | 61 | print(message) 62 | print('-' * 100) 63 | 64 | except Exception as e: 65 | print(f'Error processing {ticker}: {e}') 66 | 67 | # Create and display a DataFrame with tickers close to their green line value 68 | df = pd.DataFrame({'Company': diff_5_tickers, 'GLV % Difference': diff_5}) 69 | df.sort_values(by='GLV % Difference', inplace=True, key=abs) 70 | print('Watchlist:') 71 | print(df) -------------------------------------------------------------------------------- /find_stocks/price_alert_email.py: -------------------------------------------------------------------------------- 1 | import os 2 | import smtplib 3 | from email.message import EmailMessage 4 | import yfinance as yf 5 | import datetime as dt 6 | from pandas_datareader import data as pdr 7 | import time 8 | 9 | # Email credentials from environment variables 10 | EMAIL_ADDRESS = os.environ.get('EMAIL_USER') 11 | EMAIL_PASSWORD = os.environ.get('EMAIL_PASS') 12 | 13 | # Stock and target price settings 14 | stock = "QQQ" 15 | target_price = 180 16 | 17 | # Email setup 18 | msg = EmailMessage() 19 | msg['Subject'] = f'Alert on {stock}!' 20 | msg['From'] = EMAIL_ADDRESS 21 | msg['To'] = 'recipient@example.com' # Set the recipient email address 22 | 23 | # Time settings 24 | start = dt.datetime(2018, 12, 1) 25 | now = dt.datetime.now() 26 | 27 | # Initialize alerted flag 28 | alerted = False 29 | 30 | # Main loop 31 | while True: 32 | # Fetch stock data 33 | df = pdr.get_data_yahoo(stock, start, now) 34 | current_close = df["Adj Close"][-1] 35 | 36 | # Check if the target price is reached 37 | if current_close > target_price and not alerted: 38 | alerted = True 39 | message = f"{stock} has reached the alert price of {target_price}\nCurrent Price: {current_close}" 40 | print(message) 41 | msg.set_content(message) 42 | 43 | # Send email 44 | with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: 45 | smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) 46 | smtp.send_message(msg) 47 | print("Email sent successfully.") 48 | else: 49 | print("No new alerts.") 50 | 51 | # Wait for 60 seconds before the next check 52 | time.sleep(60) -------------------------------------------------------------------------------- /find_stocks/stock_news_sentiment.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pandas as pd 3 | from urllib.request import Request, urlopen 4 | from nltk.sentiment.vader import SentimentIntensityAnalyzer 5 | import nltk 6 | from datetime import datetime 7 | 8 | # Download necessary NLTK data 9 | nltk.download('vader_lexicon') 10 | 11 | # Define parameters 12 | num_headlines = 3 # Number of article headlines displayed per ticker 13 | tickers = ['AAPL', 'TSLA', 'AMZN'] # List of tickers to analyze 14 | 15 | # Initialize SentimentIntensityAnalyzer 16 | analyzer = SentimentIntensityAnalyzer() 17 | 18 | # Function to fetch and process news data 19 | def fetch_news(ticker): 20 | finviz_url = 'https://finviz.com/quote.ashx?t=' 21 | url = finviz_url + ticker 22 | req = Request(url=url, headers={'user-agent': 'Mozilla/5.0'}) 23 | response = urlopen(req) 24 | df = pd.read_html(response.read(), attrs={'id': 'news-table'})[0] 25 | df.columns = ['Datetime', 'Headline'] 26 | return df.head(num_headlines) 27 | 28 | # Function to perform sentiment analysis 29 | def sentiment_analysis(df): 30 | df['Sentiment'] = df['Headline'].apply(lambda x: analyzer.polarity_scores(x)['compound']) 31 | return df 32 | 33 | # Process and analyze news for each ticker 34 | for ticker in tickers: 35 | news_df = fetch_news(ticker) 36 | news_df['Ticker'] = ticker 37 | sentiment_df = sentiment_analysis(news_df) 38 | print('\nRecent News Headlines and Sentiment for {}: '.format(ticker)) 39 | print(sentiment_df) 40 | 41 | # Group news by ticker and calculate mean sentiment for each 42 | mean_sentiments = {ticker: sentiment_analysis(fetch_news(ticker))['Sentiment'].mean() for ticker in tickers} 43 | 44 | # Create and display dataframe of tickers with mean sentiment scores 45 | sentiments_df = pd.DataFrame(list(mean_sentiments.items()), columns=['Ticker', 'Mean Sentiment']) 46 | sentiments_df = sentiments_df.set_index('Ticker').sort_values('Mean Sentiment', ascending=False) 47 | print('\nMean Sentiment Scores for Each Ticker:') 48 | print(sentiments_df) -------------------------------------------------------------------------------- /find_stocks/tradingview_signals.py: -------------------------------------------------------------------------------- 1 | # Import Dependencies 2 | from time import sleep 3 | from selenium import webdriver 4 | from selenium.webdriver.chrome.options import Options 5 | from selenium.webdriver.chrome.service import Service 6 | from webdriver_manager.chrome import ChromeDriverManager 7 | import pandas as pd 8 | import datetime 9 | import pandas_datareader.data as pdr 10 | 11 | # Set pandas option and interval 12 | pd.set_option('display.max_rows', None) 13 | interval = '1m' 14 | 15 | # Initialize WebDriver for Chrome 16 | options = Options() 17 | options.add_argument("--headless") 18 | driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) 19 | 20 | # List of tickers and initialization of lists for data 21 | tickers = ['SCHB', 'AAPL', 'AMZN', 'TSLA', 'AMD', 'MSFT', 'NFLX'] 22 | signals, sells, buys, neutrals, valid_tickers, prices = [], [], [], [], [], [] 23 | 24 | # Today's date for file naming 25 | today = datetime.date.today() 26 | 27 | # Process each ticker for trading signals 28 | for ticker in tickers: 29 | try: 30 | driver.get(f"https://s.tradingview.com/embed-widget/technical-analysis/?symbol={ticker}&interval={interval}") 31 | driver.refresh() 32 | sleep(2) # Adjust the sleep time if necessary 33 | 34 | # Extract recommendation and counter values 35 | recommendation = driver.find_element_by_class_name("speedometerSignal-pyzN--tL").text 36 | counters = [element.text for element in driver.find_elements_by_class_name("counterNumber-3l14ys0C")] 37 | 38 | # Append data to lists 39 | signals.append(recommendation) 40 | sells.append(float(counters[0])) 41 | neutrals.append(float(counters[1])) 42 | buys.append(float(counters[2])) 43 | price = pdr.get_data_yahoo(ticker)['Adj Close'][-1] 44 | prices.append(price) 45 | valid_tickers.append(ticker) 46 | 47 | print(f"{ticker} recommendation: {recommendation}") 48 | 49 | except Exception as e: 50 | print(f"Error with {ticker}: {e}") 51 | 52 | # Close WebDriver 53 | driver.close() 54 | 55 | # Create and print DataFrame 56 | dataframe = pd.DataFrame({'Tickers': valid_tickers, 'Current Price': prices, 'Signals': signals, 'Buys': buys, 'Sells': sells, 'Neutrals': neutrals}).set_index('Tickers') 57 | dataframe.sort_values('Signals', ascending=False, inplace=True) 58 | dataframe.to_csv(f'{today}_{interval}.csv') 59 | print(dataframe) -------------------------------------------------------------------------------- /find_stocks/yahoo_recommendations.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import requests 3 | import pandas as pd 4 | import datetime 5 | import time 6 | import sys 7 | import os 8 | sys.path.append(os.path.dirname(os.path.dirname(os.getcwd()))) 9 | import tickers as ti 10 | 11 | # Define today's date 12 | today = datetime.date.today() 13 | 14 | # Prepare ticker symbols 15 | tickers = ti.tickers_sp500() 16 | tickers = [ticker.replace(".", "-") for ticker in tickers] 17 | 18 | # Initialize list for recommendations 19 | recommendations = [] 20 | 21 | # Process each ticker 22 | for ticker in tickers: 23 | try: 24 | url = f'https://query2.finance.yahoo.com/v10/finance/quoteSummary/{ticker}?modules=financialData' 25 | response = requests.get(url) 26 | if response.ok: 27 | result = response.json()['quoteSummary']['result'][0] 28 | recommendation = result['financialData']['recommendationMean']['fmt'] 29 | else: 30 | recommendation = None # None for failed requests 31 | except: 32 | recommendation = None # None for parsing failures 33 | 34 | recommendations.append(recommendation) 35 | time.sleep(1.5) # Delay to avoid overloading server 36 | 37 | print(f"{ticker} has an average recommendation of: {recommendation}") 38 | 39 | # Load existing data and update with new recommendations 40 | try: 41 | df = pd.read_csv('recommendation-values.csv', index_col='Company') 42 | except FileNotFoundError: 43 | df = pd.DataFrame(index=tickers) 44 | 45 | df[today] = recommendations 46 | df.to_csv('recommendation-values.csv') 47 | print(df) -------------------------------------------------------------------------------- /machine_learning/kmeans_clustering.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import pandas as pd 3 | from sklearn.cluster import KMeans 4 | import pylab as pl 5 | from math import sqrt 6 | import yfinance as yf 7 | import datetime as dt 8 | from pandas_datareader import data as pdr 9 | import tickers as ti 10 | 11 | # Load stock data from Dow Jones Index 12 | yf.pdr_override() 13 | stocks = ti.tickers_dow() 14 | start_date = dt.datetime(2010, 1, 1) 15 | end_date = dt.datetime.now() 16 | 17 | # Retrieve adjusted closing prices 18 | data = pdr.get_data_yahoo(stocks, start=start_date, end=end_date)['Close'] 19 | 20 | # Calculate annual mean returns and variances 21 | annual_returns = data.pct_change().mean() * 252 22 | annual_variances = data.pct_change().std() * sqrt(252) 23 | 24 | # Combine returns and variances into a DataFrame 25 | ret_var = pd.concat([annual_returns, annual_variances], axis=1).dropna() 26 | ret_var.columns = ["Returns", "Variance"] 27 | 28 | # KMeans clustering 29 | X = ret_var.values 30 | sse = [KMeans(n_clusters=k).fit(X).inertia_ for k in range(2, 15)] 31 | 32 | # Plotting the elbow curve to find optimal k 33 | pl.plot(range(2, 15), sse) 34 | pl.title("Elbow Curve") 35 | pl.show() 36 | 37 | # Apply KMeans with chosen number of clusters 38 | kmeans = KMeans(n_clusters=5).fit(X) 39 | 40 | # Plotting the clustering result 41 | pl.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap="rainbow") 42 | pl.title("KMeans Clustering of Stocks") 43 | pl.xlabel("Annual Return") 44 | pl.ylabel("Annual Variance") 45 | pl.show() 46 | 47 | # Creating a DataFrame with tickers and their cluster labels 48 | df = pd.DataFrame({'Stock': ret_var.index, 'Cluster': kmeans.labels_}) 49 | df.set_index('Stock', inplace=True) 50 | 51 | print(df) -------------------------------------------------------------------------------- /machine_learning/neural_network_prediction.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | import tensorflow as tf 8 | from tensorflow.keras import layers 9 | from sklearn.preprocessing import MinMaxScaler 10 | 11 | # Download and prepare stock data 12 | symbol = 'AAPL' 13 | start = dt.date.today() - dt.timedelta(days=394) 14 | end = dt.date.today() 15 | df = yf.download(symbol, start, end) 16 | df['Open_Close'] = (df['Open'] - df['Adj Close']) / df['Open'] 17 | df['High_Low'] = (df['High'] - df['Low']) / df['Low'] 18 | df['Increase_Decrease'] = np.where(df['Volume'].shift(-1) > df['Volume'], 1, 0) 19 | df['Buy_Sell_on_Open'] = np.where(df['Open'].shift(-1) > df['Open'], 1, 0) 20 | df['Buy_Sell'] = np.where(df['Adj Close'].shift(-1) > df['Adj Close'], 1, 0) 21 | df['Returns'] = df['Adj Close'].pct_change() 22 | df = df.dropna() 23 | 24 | # Normalize data 25 | scaler = MinMaxScaler() 26 | X = scaler.fit_transform(df[['Returns']]) 27 | Y = scaler.fit_transform(df[['Adj Close']]) 28 | 29 | # Build a neural network model 30 | model = tf.keras.Sequential([ 31 | layers.Dense(64, activation='relu', input_shape=[X.shape[1]]), 32 | layers.Dense(64, activation='relu'), 33 | layers.Dense(1) 34 | ]) 35 | model.compile(optimizer='rmsprop', loss='mean_squared_error', 36 | metrics=['mean_absolute_error', 'mean_squared_error']) 37 | 38 | # Train the model 39 | model.fit(X, Y, epochs=100) 40 | 41 | # Predict future stock price 42 | predicted_price = scaler.inverse_transform(model.predict([[0]]))[0][0] 43 | print(f'Predicted Price: {predicted_price}') 44 | 45 | # Optional: Plotting the model's predictions (for visualization purposes) 46 | plt.figure(figsize=(10,6)) 47 | predicted_prices = model.predict(X) 48 | plt.plot(df['Adj Close'].index, scaler.inverse_transform(predicted_prices), label='Predicted') 49 | plt.plot(df['Adj Close'], label='Actual') 50 | plt.title(f'{symbol} Stock Price Prediction') 51 | plt.xlabel('Date') 52 | plt.ylabel('Price') 53 | plt.legend() 54 | plt.show() -------------------------------------------------------------------------------- /machine_learning/pca_kmeans_clustering.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pandas as pd 3 | import datetime 4 | import numpy as np 5 | from pandas_datareader import DataReader 6 | from sklearn.pipeline import make_pipeline 7 | from sklearn.preprocessing import Normalizer 8 | from sklearn.cluster import KMeans 9 | from sklearn.decomposition import PCA 10 | import matplotlib.pyplot as plt 11 | 12 | # List of companies and date range for data collection 13 | companies = ['TGT', 'AMZN', 'NFLX', 'PG', 'NSRGY', 'MDLZ', 'MRK', 'MSFT', 'AAPL'] 14 | start_date = datetime.datetime(2017, 5, 17) 15 | end_date = datetime.date.today() 16 | 17 | # Fetch stock data 18 | df = DataReader(companies, 'yahoo', start_date, end_date)['Adj Close'] 19 | 20 | # Calculate daily returns 21 | returns = df.pct_change().dropna() 22 | 23 | # Normalize the data 24 | normalizer = Normalizer() 25 | norm_movements = normalizer.fit_transform(returns) 26 | 27 | # KMeans clustering 28 | kmeans = KMeans(n_clusters=5) 29 | pipeline = make_pipeline(normalizer, kmeans) 30 | pipeline.fit(returns) 31 | labels = pipeline.predict(returns) 32 | 33 | # Reduce the data to 2 dimensions with PCA 34 | pca = PCA(n_components=2) 35 | reduced_data = pca.fit_transform(norm_movements) 36 | 37 | # Cluster the reduced data 38 | kmeans.fit(reduced_data) 39 | reduced_labels = kmeans.predict(reduced_data) 40 | 41 | # Create DataFrame for the results 42 | df_labels = pd.DataFrame({'Label': labels, 'Company': companies}).set_index('Company') 43 | df_reduced_labels = pd.DataFrame({'Label': reduced_labels, 'Company': companies}).set_index('Company') 44 | 45 | # Plot the clusters with PCA-reduced data 46 | plt.figure(figsize=(10, 10)) 47 | plt.scatter(reduced_data[:, 0], reduced_data[:, 1], c=reduced_labels) 48 | centroids = kmeans.cluster_centers_ 49 | plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=100, color='red') 50 | plt.title('K-Means Clustering on Stock Market Movements (PCA-Reduced Data)') 51 | plt.show() 52 | 53 | # Print clustering results 54 | print("Clustering Results Without PCA Reduction:") 55 | print(df_labels) 56 | print("\nClustering Results With PCA Reduction:") 57 | print(df_reduced_labels) -------------------------------------------------------------------------------- /machine_learning/prophet_price_prediction.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pandas as pd 3 | import datetime as dt 4 | from pandas_datareader import DataReader 5 | from fbprophet import Prophet 6 | import matplotlib.pyplot as plt 7 | 8 | # Set ticker symbol and data retrieval duration 9 | ticker = 'AAPL' 10 | num_years = 20 11 | start_date = dt.datetime.now() - dt.timedelta(days=365.25 * num_years) 12 | end_date = dt.datetime.now() 13 | 14 | # Fetch stock data 15 | data = DataReader(ticker, 'yahoo', start_date, end_date) 16 | 17 | # Prepare data for Prophet model 18 | data.reset_index(inplace=True) 19 | data = data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'}) 20 | 21 | # Initialize and fit Prophet model 22 | model = Prophet(daily_seasonality=True) 23 | model.fit(data) 24 | 25 | # Prepare future dataframe for prediction 26 | future = model.make_future_dataframe(periods=30) 27 | 28 | # Make predictions 29 | forecast = model.predict(future) 30 | 31 | # Plot predictions 32 | model.plot(forecast) 33 | plt.title(f"Predicted Stock Price of {ticker} using Prophet") 34 | plt.xlabel("Date") 35 | plt.ylabel("Close Price") 36 | plt.show() -------------------------------------------------------------------------------- /machine_learning/stock_probabilistic_analysis.py: -------------------------------------------------------------------------------- 1 | import yfinance 2 | from scipy import stats 3 | import numpy as np 4 | 5 | # Download historical data for AMD stock 6 | data = yfinance.download('AMD', '2015-09-08', '2020-09-08') 7 | 8 | def calculate_prereq(values): 9 | # Calculate standard deviation and mean 10 | std = np.std(values) 11 | mean = np.mean(values) 12 | return std, mean 13 | 14 | def calculate_distribution(mean, std): 15 | # Create normal distribution with given mean and std 16 | return stats.norm(mean, std) 17 | 18 | def extrapolate(norm, x): 19 | # Probability density function 20 | return norm.pdf(x) 21 | 22 | def values_to_norm(dicts): 23 | # Convert lists of values to normal distributions 24 | for dictionary in dicts: 25 | for term in dictionary: 26 | std, mean = calculate_prereq(dictionary[term]) 27 | dictionary[term] = calculate_distribution(mean, std) 28 | return dicts 29 | 30 | def compare_possibilities(dicts, x): 31 | # Compare normal distributions and return index of higher probability 32 | probabilities = [] 33 | for dictionary in dicts: 34 | dict_probs = [extrapolate(dictionary[i], x[i]) for i in range(len(x))] 35 | probabilities.append(np.prod(dict_probs)) 36 | return probabilities.index(max(probabilities)) 37 | 38 | # Prepare data for increase and drop scenarios 39 | drop = {} 40 | increase = {} 41 | for day in range(10, len(data) - 1): 42 | previous_close = data['Close'][day - 10:day] 43 | ratios = [previous_close[i] / previous_close[i - 1] for i in range(1, len(previous_close))] 44 | if data['Close'][day + 1] > data['Close'][day]: 45 | for i, ratio in enumerate(ratios): 46 | increase[i] = increase.get(i, ()) + (ratio,) 47 | elif data['Close'][day + 1] < data['Close'][day]: 48 | for i, ratio in enumerate(ratios): 49 | drop[i] = drop.get(i, ()) + (ratio,) 50 | 51 | # Add new ratios for prediction 52 | new_close = data['Close'][-11:-1] 53 | new_ratios = [new_close[i] / new_close[i - 1] for i in range(1, len(new_close))] 54 | for i, ratio in enumerate(new_ratios): 55 | increase[i] = increase.get(i, ()) + (ratio,) 56 | 57 | # Convert ratio lists to normal distributions and make prediction 58 | dicts = [increase, drop] 59 | dicts = values_to_norm(dicts) 60 | prediction = compare_possibilities(dicts, new_ratios) 61 | print("Predicted Movement: ", "Increase" if prediction == 0 else "Drop") -------------------------------------------------------------------------------- /machine_learning/stock_regression_analysis.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pandas as pd 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import datetime as dt 6 | import yfinance as yf 7 | from sklearn.model_selection import train_test_split 8 | from sklearn.linear_model import LinearRegression 9 | from sklearn.metrics import mean_squared_error 10 | 11 | # Set parameters for stock data 12 | stock = 'AAPL' 13 | start_date = dt.date.today() - dt.timedelta(days=3650) # 10 years of data 14 | end_date = dt.date.today() 15 | 16 | # Download historical data for the specified stock 17 | data = yf.download(stock, start_date, end_date) 18 | 19 | # Drop columns that won't be used in the regression model 20 | data = data.drop(columns=['Adj Close']) 21 | 22 | # Prepare the features (X) and target (y) 23 | X = data.drop(['Close'], axis=1) 24 | y = data['Adj Close'] 25 | 26 | # Split the data into training and testing sets 27 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) 28 | 29 | # Initialize and train a Linear Regression model 30 | regression_model = LinearRegression() 31 | regression_model.fit(X_train, y_train) 32 | 33 | # Output the intercept of the model 34 | intercept = regression_model.intercept_ 35 | print(f"The intercept for our model is: {intercept}") 36 | 37 | # Evaluate the model's performance 38 | score = regression_model.score(X_test, y_test) 39 | print(f"The score for our model is: {score}") 40 | 41 | # Predict the next day's closing price using the latest data 42 | latest_data = data.tail(1).drop(['Close'], axis=1) 43 | next_day_price = regression_model.predict(latest_data)[0] 44 | print(f"The predicted price for the next trading day is: {next_day_price}") -------------------------------------------------------------------------------- /portfolio_strategies/astral_timing_signals.py: -------------------------------------------------------------------------------- 1 | # Importing necessary libraries 2 | import yfinance as yf 3 | from pandas_datareader import data as pdr 4 | import pandas as pd 5 | import datetime as dt 6 | import matplotlib.pyplot as plt 7 | 8 | # Allow pandas_datareader to use Yahoo Finance as a data source 9 | yf.pdr_override() 10 | 11 | # Apply Astral Timing signals to stock data. 12 | def astral(data, completion, step, step_two, what, high, low, where_long, where_short): 13 | data['long_signal'] = 0 14 | data['short_signal'] = 0 15 | 16 | # Iterate through the DataFrame 17 | for i in range(len(data)): 18 | # Long signal logic 19 | if data.iloc[i][what] < data.iloc[i - step][what] and data.iloc[i][low] < data.iloc[i - step_two][low]: 20 | data.at[data.index[i], 'long_signal'] = -1 21 | elif data.iloc[i][what] >= data.iloc[i - step][what]: 22 | data.at[data.index[i], 'long_signal'] = 0 23 | 24 | # Short signal logic 25 | if data.iloc[i][what] > data.iloc[i - step][what] and data.iloc[i][high] > data.iloc[i - step_two][high]: 26 | data.at[data.index[i], 'short_signal'] = 1 27 | elif data.iloc[i][what] <= data.iloc[i - step][what]: 28 | data.at[data.index[i], 'short_signal'] = 0 29 | 30 | return data 31 | 32 | # Define stock ticker and date range 33 | ticker = 'APPS' 34 | start = dt.datetime.today() - dt.timedelta(days=365.25 * 2) 35 | end = dt.datetime.today() 36 | 37 | # Fetch stock data 38 | data = pdr.get_data_yahoo(ticker, start, end) 39 | 40 | # Apply Astral Timing signals 41 | astral_data = astral(data, 8, 1, 5, 'Close', 'High', 'Low', 'long_signal', 'short_signal') 42 | 43 | # Display the results 44 | print(astral_data[['long_signal', 'short_signal']]) -------------------------------------------------------------------------------- /portfolio_strategies/factor_analysis.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import datetime as dt 5 | import seaborn as sns 6 | import yfinance as yf 7 | from factor_analyzer import FactorAnalyzer, calculate_bartlett_sphericity, calculate_kmo 8 | 9 | # Setting plot aesthetics 10 | sns.set(style='darkgrid', context='talk', palette='Dark2') 11 | 12 | # Defining the time frame for data collection 13 | end_date = dt.datetime.now() 14 | start_date = end_date - dt.timedelta(days=365 * 7) 15 | 16 | # List of stock symbols for factor analysis 17 | symbols = ['AAPL', 'MSFT', 'AMD', 'NVDA'] 18 | 19 | # Fetching adjusted close prices for the specified symbols 20 | df = pd.DataFrame({symbol: yf.download(symbol, start_date, end_date)['Adj Close'] 21 | for symbol in symbols}) 22 | 23 | # Initializing FactorAnalyzer and fitting it to our data 24 | fa = FactorAnalyzer(rotation=None, n_factors=df.shape[1]) 25 | fa.fit(df.dropna()) 26 | 27 | # Extracting communalities, eigenvalues, and factor loadings 28 | communalities = fa.get_communalities() 29 | eigenvalues, _ = fa.get_eigenvalues() 30 | loadings = fa.loadings_ 31 | 32 | # Plotting the Scree plot to assess the number of factors 33 | plt.figure(figsize=(10, 6)) 34 | plt.scatter(range(1, df.shape[1] + 1), eigenvalues) 35 | plt.plot(range(1, df.shape[1] + 1), eigenvalues) 36 | plt.title('Scree Plot') 37 | plt.xlabel('Number of Factors') 38 | plt.ylabel('Eigenvalue') 39 | plt.grid(True) 40 | plt.show() 41 | 42 | # Bartlett's test of sphericity 43 | chi_square_value, p_value = calculate_bartlett_sphericity(df.dropna()) 44 | print('Bartlett sphericity test:\nChi-square value:', chi_square_value, '\nP-value:', p_value) 45 | 46 | # Kaiser-Meyer-Olkin (KMO) test 47 | kmo_all, kmo_model = calculate_kmo(df.dropna()) 48 | print('Kaiser-Meyer-Olkin (KMO) Test:\nOverall KMO:', kmo_all, '\nKMO per variable:', kmo_model) 49 | 50 | # Printing results 51 | print("\nFactor Analysis Results:") 52 | print("\nCommunalities:\n", communalities) 53 | print("\nFactor Loadings:\n", loadings) -------------------------------------------------------------------------------- /portfolio_strategies/financial_signal_analysis.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import yfinance as yf 4 | import matplotlib.pyplot as plt 5 | from sklearn.mixture import GaussianMixture 6 | import datetime 7 | 8 | # User input for the stock ticker symbol 9 | ticker = input('Enter a ticker: ') 10 | 11 | # Constants for analysis 12 | index = 'SPY' # S&P500 as the index for comparison 13 | num_of_years = 5 # Number of years for historical data 14 | start = datetime.date.today() - datetime.timedelta(days=int(365.25 * num_of_years)) 15 | 16 | # Download historical stock prices 17 | stock_data = yf.download(ticker, start=start)['Adj Close'] 18 | 19 | # Plotting stock prices and their distribution 20 | fig, ax = plt.subplots(1, 2, figsize=(15, 10)) 21 | stock_data.plot(title=f'{ticker.upper()} Price', ax=ax[0]) 22 | stock_data.plot.hist(title=f'{ticker.upper()} Price Distribution', ax=ax[1], bins=30) 23 | plt.tight_layout() 24 | plt.show() 25 | 26 | # Calculating and plotting stock returns 27 | stock_returns = stock_data.apply(np.log).diff(1) 28 | fig, ax = plt.subplots(1, 2, figsize=(15, 10)) 29 | stock_returns.plot(title=f'{ticker.upper()} Returns', ax=ax[0]) 30 | stock_returns.plot.hist(title=f'{ticker.upper()} Returns Distribution', ax=ax[1], bins=30) 31 | plt.tight_layout() 32 | plt.show() 33 | 34 | # Rolling statistics for stock returns 35 | rolling_window = 22 36 | rolling_mean = stock_returns.rolling(rolling_window).mean() 37 | rolling_std = stock_returns.rolling(rolling_window).std() 38 | rolling_skew = stock_returns.rolling(rolling_window).skew() 39 | rolling_kurtosis = stock_returns.rolling(rolling_window).kurt() 40 | 41 | # Combining rolling statistics into a DataFrame 42 | signals = pd.concat([rolling_mean, rolling_std, rolling_skew, rolling_kurtosis], axis=1) 43 | signals.columns = ['Mean', 'Std Dev', 'Skewness', 'Kurtosis'] 44 | signals.plot(subplots=True, figsize=(15, 10)) 45 | plt.tight_layout() 46 | plt.show() 47 | 48 | # Volatility analysis for S&P500 49 | index_data = yf.download(index, start=start)['Adj Close'] 50 | index_returns = index_data.apply(np.log).diff(1) 51 | index_volatility = index_returns.rolling(rolling_window).std() 52 | 53 | # Gaussian Mixture Model on S&P500 volatility 54 | gmm_labels = GaussianMixture(2).fit_predict(index_volatility.values.reshape(-1, 1)) 55 | index_data = index_data.reindex(index_volatility.index) 56 | 57 | # Plotting volatility regimes 58 | plt.figure() 59 | index_data[gmm_labels == 0].plot(style='bo', alpha=0.2) 60 | index_data[gmm_labels == 1].plot(style='ro', alpha=0.2) 61 | plt.title(f'{index} Volatility Regimes (Gaussian Mixture)') 62 | plt.tight_layout() 63 | plt.show() -------------------------------------------------------------------------------- /portfolio_strategies/long_hold_stats_analysis.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | from scipy.stats import norm 8 | 9 | # Function to download stock data 10 | def download_stock_data(symbol, start, end): 11 | return yf.download(symbol, start, end)['Adj Close'] 12 | 13 | # Function to calculate investment statistics 14 | def calculate_investment_stats(df, investment_amount, symbol): 15 | # Calculate number of shares bought and investment values 16 | shares = int(investment_amount / df.iloc[0]) 17 | begin_value = round(shares * df.iloc[0], 2) 18 | current_value = round(shares * df.iloc[-1], 2) 19 | 20 | # Calculate daily returns and various statistics 21 | returns = df.pct_change().dropna() 22 | stats = { 23 | 'mean': round(returns.mean() * 100, 2), 24 | 'std_dev': round(returns.std() * 100, 2), 25 | 'skew': round(returns.skew(), 2), 26 | 'kurt': round(returns.kurtosis(), 2), 27 | 'total_return': round((1 + returns).cumprod().iloc[-1], 4) * 100 28 | } 29 | return shares, begin_value, current_value, stats 30 | 31 | # User inputs 32 | symbol = input('Enter a ticker: ') 33 | num_of_years = float(input('Enter the number of years: ')) 34 | investment_amount = 100000 35 | 36 | # Calculate date range 37 | start = dt.datetime.now() - dt.timedelta(days=int(365.25 * num_of_years)) 38 | end = dt.datetime.now() 39 | 40 | # Download and process stock data 41 | df = download_stock_data(symbol, start, end) 42 | shares, begin_value, current_value, stats = calculate_investment_stats(df, investment_amount, symbol) 43 | 44 | # Print statistics 45 | print(f'\nNumber of Shares for {symbol}: {shares}') 46 | print(f'Beginning Value: ${begin_value}') 47 | print(f'Current Value: ${current_value}') 48 | print(f"\nStatistics:\nMean: {stats['mean']}%\nStd. Dev: {stats['std_dev']}%\nSkew: {stats['skew']}\nKurt: {stats['kurt']}\nTotal Return: {stats['total_return']}%") 49 | 50 | # Plotting returns and other statistics 51 | plt.figure(figsize=(10, 6)) 52 | df.pct_change().plot(title=f'{symbol} Daily Returns') 53 | plt.show() -------------------------------------------------------------------------------- /portfolio_strategies/ls_dca_analysis.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import matplotlib.ticker as ticker 4 | import numpy as np 5 | from pandas_datareader import data as pdr 6 | import datetime as dt 7 | 8 | # Function to fetch stock data 9 | def fetch_stock_data(symbol, start, end): 10 | return pdr.get_data_yahoo(symbol, start, end) 11 | 12 | # Lump Sum Investment Function 13 | def lump_sum_investment(df, invest_date, principal): 14 | invest_price = df.loc[invest_date]['Adj Close'] 15 | current_price = df['Adj Close'][-1] 16 | return principal * ((current_price / invest_price) - 1) 17 | 18 | # Dollar-Cost Averaging Function 19 | def dca_investment(df, invest_date, periods, freq, principal): 20 | dca_dates = pd.date_range(invest_date, periods=periods, freq=freq) 21 | dca_dates = dca_dates[dca_dates < df.index[-1]] 22 | cut_off_count = 12 - len(dca_dates) 23 | cut_off_value = cut_off_count * (principal / periods) 24 | dca_value = cut_off_value 25 | for date in dca_dates: 26 | trading_date = df.index[df.index.searchsorted(date)] 27 | dca_value += lump_sum_investment(df, trading_date, principal / periods) 28 | return dca_value 29 | 30 | # User Input 31 | symbol = input('Enter a ticker: ') 32 | years = 20 33 | 34 | # Set dates for data retrieval 35 | start_date = dt.datetime.now() - dt.timedelta(days=int(365.25 * years)) 36 | end_date = dt.datetime.now() 37 | 38 | # Fetch Data 39 | stock_data = fetch_stock_data(symbol, start_date, end_date) 40 | 41 | # Analysis for Lump Sum and DCA 42 | lump_sum_values = [lump_sum_investment(stock_data, date) for date in stock_data.index] 43 | dca_values = [dca_investment(stock_data, date, 12, '30D') for date in stock_data.index] 44 | 45 | # Plotting 46 | fig, axs = plt.subplots(3, 1, figsize=(15, 15)) 47 | axs[0].plot(stock_data.index, stock_data['Adj Close'], label=f'{symbol} Price') 48 | axs[1].plot(stock_data.index, lump_sum_values, label='Lump Sum Investment') 49 | axs[1].plot(stock_data.index, dca_values, label='DCA Investment') 50 | axs[2].plot(stock_data.index, np.array(lump_sum_values) - np.array(dca_values), label='Difference in Investment Values') 51 | 52 | # Setting labels, titles, and formats 53 | for ax in axs: 54 | ax.legend() 55 | ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('${x:,.0f}')) 56 | axs[0].set_title(f'{symbol} Stock Price') 57 | axs[1].set_title('Lump Sum vs. DCA Investment Value') 58 | axs[2].set_title('Difference Between Lump Sum and DCA') 59 | 60 | # Display the plots 61 | plt.tight_layout() 62 | plt.show() -------------------------------------------------------------------------------- /portfolio_strategies/monte_carlo.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader as web 2 | import numpy as np 3 | import math 4 | import matplotlib.pyplot as plt 5 | import pandas as pd 6 | from datetime import datetime 7 | 8 | # Function to download stock data 9 | def download_data(symbol, source, start, end): 10 | start = datetime.strptime(start, '%d-%m-%Y') 11 | end = datetime.strptime(end, '%d-%m-%Y') 12 | df = web.DataReader(symbol, data_source=source, start=start, end=end) 13 | return df 14 | 15 | # Function to calculate annual volatility 16 | def annual_volatility(df): 17 | quote = df['Close'] 18 | returns = quote.pct_change() 19 | return returns.std() * np.sqrt(252) 20 | 21 | # Function to calculate CAGR 22 | def cagr(df): 23 | quote = df['Close'] 24 | days = (quote.index[-1] - quote.index[0]).days 25 | return ((((quote[-1]) / quote[1])) ** (365.0/days)) - 1 26 | 27 | # Monte Carlo Simulation Function 28 | def monte_carlo_simulation(symbol, source, start, end, simulations, days_predicted): 29 | df = download_data(symbol, source, start, end) 30 | mu = cagr(df) 31 | vol = annual_volatility(df) 32 | start_price = df['Close'][-1] 33 | 34 | results = [] 35 | plt.figure(figsize=(10, 6)) 36 | 37 | # Run simulations 38 | for _ in range(simulations): 39 | prices = [start_price] 40 | for _ in range(days_predicted): 41 | shock = np.random.normal(mu / days_predicted, vol / math.sqrt(days_predicted)) 42 | prices.append(prices[-1] * (1 + shock)) 43 | plt.plot(prices) 44 | results.append(prices[-1]) 45 | 46 | plt.title(f"{symbol} Monte Carlo Simulation") 47 | plt.xlabel("Days") 48 | plt.ylabel("Price") 49 | plt.show() 50 | 51 | return pd.DataFrame({ 52 | "Results": results, 53 | "Percentile 5%": np.percentile(results, 5), 54 | "Percentile 95%": np.percentile(results, 95) 55 | }) 56 | 57 | # Main function 58 | def main(): 59 | symbol = 'NIO' 60 | start_date = '01-01-2015' 61 | end_date = '01-01-2020' 62 | simulations = 1000 63 | days_predicted = 252 64 | 65 | # Perform Monte Carlo Simulation 66 | simulation_results = monte_carlo_simulation(symbol, 'yahoo', start_date, end_date, simulations, days_predicted) 67 | print(simulation_results) 68 | 69 | if __name__ == "__main__": 70 | main() -------------------------------------------------------------------------------- /portfolio_strategies/moving_average_crossover_signals.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from pandas_datareader import DataReader 3 | import datetime as dt 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | 7 | # Function to retrieve stock data 8 | def get_stock_data(ticker, start_date, end_date): 9 | return DataReader(ticker, 'yahoo', start_date, end_date) 10 | 11 | # Function to calculate Simple Moving Averages (SMA) 12 | def calculate_sma(data, window): 13 | return data['Close'].rolling(window=window).mean() 14 | 15 | # Function to generate buy and sell signals 16 | def generate_signals(data): 17 | signal_buy = [] 18 | signal_sell = [] 19 | flag = -1 20 | 21 | for i in range(len(data)): 22 | if data['SMA 50'][i] > data['SMA 200'][i] and flag != 1: 23 | signal_buy.append(data['stock'][i]) 24 | signal_sell.append(np.nan) 25 | flag = 1 26 | elif data['SMA 50'][i] < data['SMA 200'][i] and flag != 0: 27 | signal_buy.append(np.nan) 28 | signal_sell.append(data['stock'][i]) 29 | flag = 0 30 | else: 31 | signal_buy.append(np.nan) 32 | signal_sell.append(np.nan) 33 | 34 | return signal_buy, signal_sell 35 | 36 | # Main function to run the analysis 37 | def main(): 38 | ticker = input("Enter a ticker: ") 39 | num_of_years = 6 40 | start_date = dt.datetime.now() - dt.timedelta(int(365.25 * num_of_years)) 41 | end_date = dt.datetime.now() 42 | 43 | # Retrieve and process stock data 44 | stock_data = get_stock_data(ticker, start_date, end_date) 45 | stock_data['SMA 50'] = calculate_sma(stock_data, 50) 46 | stock_data['SMA 200'] = calculate_sma(stock_data, 200) 47 | 48 | # Generate buy and sell signals 49 | buy_signals, sell_signals = generate_signals(stock_data) 50 | 51 | # Plotting 52 | plt.figure(figsize=(15,10)) 53 | plt.plot(stock_data['Close'], label='Close Price', alpha=0.35) 54 | plt.plot(stock_data['SMA 50'], label='SMA 50', alpha=0.35) 55 | plt.plot(stock_data['SMA 200'], label='SMA 200', alpha=0.35) 56 | plt.scatter(stock_data.index, buy_signals, label='Buy Signal', marker='^', color='green') 57 | plt.scatter(stock_data.index, sell_signals, label='Sell Signal', marker='v', color='red') 58 | plt.title(f'{ticker.upper()} Close Price History with Buy & Sell Signals') 59 | plt.xlabel('Date') 60 | plt.ylabel('Close Price') 61 | plt.legend() 62 | plt.show() 63 | 64 | if __name__ == "__main__": 65 | main() -------------------------------------------------------------------------------- /portfolio_strategies/moving_avg_strategy.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import yfinance as yf 4 | import datetime as dt 5 | 6 | # Function to download stock data 7 | def download_stock_data(ticker, start_date, end_date): 8 | return yf.download(ticker, start_date, end_date) 9 | 10 | # Function to calculate moving averages 11 | def calculate_moving_averages(data, windows): 12 | for window in windows: 13 | data[f'SMA_{window}'] = data['Adj Close'].rolling(window).mean() 14 | return data 15 | 16 | # Main function 17 | def main(): 18 | symbol = 'NIO' 19 | start_date = dt.date.today() - dt.timedelta(days=365 * 10) # 10 years ago 20 | end_date = dt.date.today() 21 | 22 | # Download and calculate moving averages 23 | stock_data = download_stock_data(symbol, start_date, end_date) 24 | windows = [20, 40, 80] 25 | stock_data = calculate_moving_averages(stock_data, windows) 26 | 27 | # Plotting 28 | plt.figure(figsize=(16,9)) 29 | plt.plot(stock_data['Adj Close'], label='Price', color='black') 30 | for window in windows: 31 | plt.plot(stock_data[f'SMA_{window}'], label=f'{window}-days SMA') 32 | plt.legend(loc='best') 33 | plt.ylabel('Price') 34 | plt.title(f'{symbol} - Big Three Trading Strategy') 35 | plt.show() 36 | 37 | if __name__ == "__main__": 38 | main() -------------------------------------------------------------------------------- /portfolio_strategies/optimal_portfolio.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import seaborn as sns 5 | import yfinance as yf 6 | from scipy.optimize import fmin 7 | import datetime as dt 8 | 9 | # Function to download stock data and calculate annual returns 10 | def annual_returns(symbols, start_date, end_date): 11 | df = yf.download(symbols, start_date, end_date)['Adj Close'] 12 | log_rets = np.log(df / df.shift(1)) 13 | return np.exp(log_rets.groupby(log_rets.index.year).sum()) - 1 14 | 15 | # Function to calculate portfolio variance 16 | def portfolio_var(returns, weights): 17 | cov_matrix = np.cov(returns.T) 18 | return np.dot(weights.T, np.dot(cov_matrix, weights)) 19 | 20 | # Function to calculate Sharpe ratio 21 | def sharpe_ratio(returns, weights, rf_rate): 22 | portfolio_return = np.dot(returns.mean(), weights) 23 | portfolio_volatility = np.sqrt(portfolio_var(returns, weights)) 24 | return (portfolio_return - rf_rate) / portfolio_volatility 25 | 26 | # Function to optimize portfolio for maximum Sharpe ratio 27 | def optimize_portfolio(returns, initial_weights, rf_rate): 28 | constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) 29 | bounds = tuple((0, 1) for _ in range(len(initial_weights))) 30 | optimized = fmin(lambda x: -sharpe_ratio(returns, x, rf_rate), initial_weights, disp=False) 31 | return optimized 32 | 33 | # Main function to execute the script 34 | def main(): 35 | symbols = ['FB', 'AAPL', 'MRK'] 36 | start_date = dt.datetime.now() - dt.timedelta(days=365 * 7) 37 | end_date = dt.datetime.now() 38 | rf_rate = 0.003 39 | 40 | # Calculate annual returns 41 | returns = annual_returns(symbols, start_date, end_date) 42 | 43 | # Initialize equal weights 44 | initial_weights = np.ones(len(symbols)) / len(symbols) 45 | 46 | # Calculate equal weighted portfolio Sharpe ratio 47 | equal_weighted_sharpe = sharpe_ratio(returns, initial_weights, rf_rate) 48 | 49 | # Optimize portfolio 50 | optimal_weights = optimize_portfolio(returns, initial_weights, rf_rate) 51 | optimal_sharpe = sharpe_ratio(returns, optimal_weights, rf_rate) 52 | 53 | # Display results 54 | print("Equal Weighted Portfolio Sharpe Ratio:", equal_weighted_sharpe) 55 | print("Optimal Portfolio Weights:", optimal_weights) 56 | print("Optimal Portfolio Sharpe Ratio:", optimal_sharpe) 57 | 58 | if __name__ == "__main__": 59 | main() -------------------------------------------------------------------------------- /portfolio_strategies/optimized_bollinger_bands.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import pandas_datareader.data as pdr 5 | import yfinance as yf 6 | import datetime as dt 7 | 8 | # Function to download stock data from Yahoo Finance 9 | def get_stock_data(ticker): 10 | df = pdr.get_data_yahoo(ticker) 11 | df = df[['Adj Close']] 12 | return df 13 | 14 | # Function to add Bollinger Bands to DataFrame 15 | def add_bollinger_bands(df, window_size=20, num_std_dev=2): 16 | df['SMA'] = df['Adj Close'].rolling(window=window_size).mean() 17 | df['Upper Band'] = df['SMA'] + (df['Adj Close'].rolling(window=window_size).std() * num_std_dev) 18 | df['Lower Band'] = df['SMA'] - (df['Adj Close'].rolling(window=window_size).std() * num_std_dev) 19 | return df 20 | 21 | # Function to plot stock prices with Bollinger Bands 22 | def plot_with_bollinger_bands(df, ticker): 23 | plt.figure(figsize=(12,6)) 24 | plt.plot(df['Adj Close'], label=f'{ticker} Adjusted Close', color='blue') 25 | plt.plot(df['SMA'], label='20 Day SMA', color='orange') 26 | plt.plot(df['Upper Band'], label='Upper Bollinger Band', color='green') 27 | plt.plot(df['Lower Band'], label='Lower Bollinger Band', color='red') 28 | plt.title(f'{ticker} Stock Price with Bollinger Bands') 29 | plt.xlabel('Date') 30 | plt.ylabel('Price') 31 | plt.legend() 32 | plt.show() 33 | 34 | # Main function to execute the script 35 | def main(): 36 | ticker = input("Enter stock ticker: ") 37 | df = get_stock_data(ticker) 38 | df = add_bollinger_bands(df) 39 | plot_with_bollinger_bands(df, ticker) 40 | 41 | if __name__ == "__main__": 42 | main() -------------------------------------------------------------------------------- /portfolio_strategies/pairs_trading.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import yfinance as yf 5 | from statsmodels.tsa.stattools import coint 6 | import datetime 7 | from pandas_datareader import data as pdr 8 | import seaborn as sns 9 | 10 | # Override pandas_datareader's DataReader method to use Yahoo Finance 11 | yf.pdr_override() 12 | 13 | def download_stock_data(symbols, start_date, end_date): 14 | """Download historical stock data for given symbols from Yahoo Finance.""" 15 | stock_data = pdr.get_data_yahoo(symbols, start_date, end_date)['Adj Close'] 16 | return stock_data.dropna() 17 | 18 | def find_cointegrated_pairs(data): 19 | """Identify cointegrated pairs of stocks.""" 20 | n = data.shape[1] 21 | score_matrix, pvalue_matrix = np.zeros((n, n)), np.ones((n, n)) 22 | pairs = [] 23 | for i in range(n): 24 | for j in range(i+1, n): 25 | S1, S2 = data[data.columns[i]], data[data.columns[j]] 26 | _, pvalue, _ = coint(S1, S2) 27 | score_matrix[i, j], pvalue_matrix[i, j] = _, pvalue 28 | if pvalue < 0.05: # Using a p-value threshold of 0.05 29 | pairs.append((data.columns[i], data.columns[j])) 30 | return score_matrix, pvalue_matrix, pairs 31 | 32 | def plot_cointegration_heatmap(pvalues, tickers): 33 | """Plot heatmap of p-values for cointegration test.""" 34 | plt.figure(figsize=(10, 8)) 35 | sns.heatmap(pvalues, xticklabels=tickers, yticklabels=tickers, cmap='coolwarm', mask=(pvalues >= 0.05)) 36 | plt.title("P-Values for Pairs Cointegration Test") 37 | plt.show() 38 | 39 | def main(): 40 | # Set time period and stock tickers 41 | num_of_years = 5 42 | start = datetime.datetime.now() - datetime.timedelta(days=365 * num_of_years) 43 | end = datetime.datetime.now() 44 | stocks = ['AAPL', 'MSFT', 'GOOG', 'AMZN'] 45 | 46 | # Download and process data 47 | data = download_stock_data(stocks, start, end) 48 | 49 | # Find cointegrated pairs 50 | _, pvalues, pairs = find_cointegrated_pairs(data) 51 | 52 | # Plot heatmap of p-values 53 | plot_cointegration_heatmap(pvalues, stocks) 54 | 55 | # Display the found pairs 56 | print("Cointegrated Pairs:", pairs) 57 | 58 | if __name__ == "__main__": 59 | main() -------------------------------------------------------------------------------- /portfolio_strategies/robinhood_bot.py: -------------------------------------------------------------------------------- 1 | import robin_stocks as r 2 | import pandas as pd 3 | from datetime import datetime 4 | import numpy as np 5 | 6 | # Setting display options for pandas DataFrames 7 | pd.set_option('display.max_columns', None) 8 | pd.set_option('display.max_rows', None) 9 | 10 | # Log in to Robinhood account (replace with your username and password) 11 | r.login('rh_username', 'rh_password') 12 | 13 | # Fetch holdings data and convert it into a DataFrame 14 | my_stocks = r.build_holdings() 15 | df = pd.DataFrame(my_stocks).T # Transpose to get tickers as rows 16 | df['ticker'] = df.index # Add ticker symbols as a column 17 | df = df.reset_index(drop=True) # Reset index 18 | 19 | # Convert numeric columns to appropriate data types 20 | numeric_cols = df.columns.drop(['id', 'type', 'name', 'pe_ratio', 'ticker']) 21 | df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric, errors='coerce') 22 | 23 | # Criteria for selecting stocks to buy and sell 24 | buy_criteria = (df['average_buy_price'] <= 25.00) & (df['quantity'] == 1.00) & (df['percent_change'] <= -0.50) 25 | sell_criteria = (df['quantity'] == 5.00) & (df['percent_change'] >= 0.50) 26 | 27 | # Filter DataFrame based on criteria 28 | df_buy = df[buy_criteria] 29 | df_sell = df[sell_criteria] 30 | 31 | # Display filtered DataFrames 32 | print(df_buy) 33 | print(df_sell) 34 | 35 | # Create lists of tickers to buy and sell 36 | tickers_to_buy = df_buy['ticker'].tolist() 37 | tickers_to_sell = df_sell['ticker'].tolist() 38 | 39 | # Cancel all open orders 40 | open_orders = r.orders.get_all_open_orders() 41 | print(f"{len(open_orders)} open order(s)") 42 | r.orders.cancel_all_open_orders() 43 | 44 | # Sell stocks based on the sell list 45 | if tickers_to_sell: 46 | for ticker in tickers_to_sell: 47 | sell_order = r.orders.order_sell_market(ticker, 4, timeInForce='gfd') 48 | print(f"Selling {ticker}: {sell_order}") 49 | else: 50 | print('Nothing to sell right now!') 51 | 52 | # Buy stocks based on the buy list 53 | if tickers_to_buy: 54 | for ticker in tickers_to_buy: 55 | buy_order = r.orders.order_buy_market(ticker, 4, timeInForce='gfd') 56 | print(f"Buying {ticker}: {buy_order}") 57 | else: 58 | print('Nothing to buy right now!') 59 | 60 | # Additional data retrieval: Cryptocurrency pairs and TSLA stock earnings 61 | crypto_pairs = r.get_crypto_currency_pairs() 62 | tsla_earnings = r.stocks.get_earnings('TSLA', info='report') -------------------------------------------------------------------------------- /portfolio_strategies/rsi_trendline_strategy.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import time 3 | import pandas as pd 4 | import yfinance as yf 5 | from pandas_datareader import data as pdr 6 | from pandas import ExcelWriter 7 | import sys 8 | import os 9 | 10 | # Adding path for ta_functions and ticker modules 11 | parent_dir = os.path.dirname(os.getcwd()) 12 | sys.path.append(parent_dir) 13 | import ta_functions as ta 14 | import tickers as ti 15 | 16 | # Override the yfinance module 17 | yf.pdr_override() 18 | 19 | # Define the date range for data retrieval 20 | num_of_years = 10 21 | start = datetime.datetime.now() - datetime.timedelta(days=365.25 * num_of_years) 22 | end = datetime.datetime.now() 23 | 24 | # Load stock symbols 25 | stocklist = ti.tickers_sp500() 26 | stocklist = [stock.replace(".", "-") for stock in stocklist] # Adjusting ticker format for Yahoo Finance 27 | 28 | # Initialize the DataFrame for exporting results 29 | exportList = pd.DataFrame(columns=['Stock', "RSI", "200 Day MA"]) 30 | 31 | # Process a limited number of stocks for demonstration 32 | for stock in stocklist[:5]: 33 | time.sleep(1.5) # To avoid hitting API rate limits 34 | print(f"\npulling {stock}") 35 | 36 | # Fetch stock data 37 | df = pdr.get_data_yahoo(stock, start=start, end=end) 38 | 39 | try: 40 | # Calculate indicators: 200-day MA, RSI 41 | df["SMA_200"] = df.iloc[:, 4].rolling(window=200).mean() 42 | df["rsi"] = ta.RSI(df["Close"]) 43 | currentClose, moving_average_200, RSI = df["Adj Close"][-1], df["SMA_200"][-1], df["rsi"].tail(14).mean() 44 | two_day_rsi_avg = (df.rsi[-1] + df.rsi[-2]) / 2 45 | 46 | # Define entry criteria 47 | if currentClose > moving_average_200 and two_day_rsi_avg < 33: 48 | exportList = exportList.append({'Stock': stock, "RSI": RSI, "200 Day MA": moving_average_200}, ignore_index=True) 49 | print(f"{stock} made the requirements") 50 | 51 | except Exception as e: 52 | print(e) # Handling exceptions 53 | 54 | # Exporting the list to an Excel file 55 | today = datetime.date.today() 56 | print(exportList) 57 | writer = ExcelWriter(f'Export-Output_{today}.xlsx') 58 | exportList.to_excel(writer, "Sheet1") 59 | writer.save() -------------------------------------------------------------------------------- /portfolio_strategies/rwb_strategy.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | import yfinance as yf 3 | from pandas_datareader import data as pdr 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | 7 | yf.pdr_override() 8 | 9 | emas_used = [3, 5, 8, 10, 12, 15, 30, 35, 40, 45, 50, 60] 10 | 11 | def get_stock_data(ticker, num_of_years): 12 | start_date = dt.date.today() - dt.timedelta(days=365.25 * num_of_years) 13 | end_date = dt.datetime.now() 14 | df = pdr.get_data_yahoo(ticker, start_date, end_date).dropna() 15 | for ema in emas_used: 16 | df[f"Ema_{ema}"] = df.iloc[:, 4].ewm(span=ema, adjust=False).mean() 17 | return df.iloc[60:] 18 | 19 | def rwb_strategy(df): 20 | pos, num, percent_change = 0, 0, [] 21 | for i in df.index: 22 | cmin = min(df[f"Ema_{ema}"][i] for ema in emas_used[:6]) 23 | cmax = max(df[f"Ema_{ema}"][i] for ema in emas_used[6:]) 24 | close = df["Adj Close"][i] 25 | if cmin > cmax and pos == 0: 26 | bp, pos = close, 1 27 | print(f"Buying now at {bp}") 28 | elif cmin < cmax and pos == 1: 29 | pos, sp = 0, close 30 | print(f"Selling now at {sp}") 31 | percent_change.append((sp / bp - 1) * 100) 32 | if num == df["Adj Close"].count() - 1 and pos == 1: 33 | pos, sp = 0, close 34 | print(f"Selling now at {sp}") 35 | percent_change.append((sp / bp - 1) * 100) 36 | num += 1 37 | return percent_change 38 | 39 | stock = input("Enter a ticker: ") 40 | num_of_years = float(input("Enter number of years: ")) 41 | df = get_stock_data(stock, num_of_years) 42 | percent_change = rwb_strategy(df) 43 | 44 | gains = sum(i for i in percent_change if i > 0) 45 | losses = sum(i for i in percent_change if i < 0) 46 | total_trades = len(percent_change) 47 | total_return = round((np.prod([1 + i/100 for i in percent_change]) - 1) * 100, 2) 48 | 49 | print(f"Results for {stock.upper()} going back to {num_of_years} years:") 50 | print(f"Number of Trades: {total_trades}") 51 | print(f"Total return: {total_return}%") 52 | 53 | plt.figure(figsize=(15, 10)) 54 | for ema in emas_used: 55 | plt.plot(df[f"Ema_{ema}"], label=f"Ema_{ema}") 56 | plt.plot(df["Adj Close"], color="g", label="Adj Close") 57 | plt.title(f"RWB Strategy for {stock.upper()}") 58 | plt.ylabel("Price") 59 | plt.xlabel("Date") 60 | plt.legend() 61 | plt.show() -------------------------------------------------------------------------------- /portfolio_strategies/stock_spread_plotter.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import seaborn as sns 4 | import pandas_datareader.data as pdr 5 | import yfinance as yf 6 | import datetime as dt 7 | 8 | # Override the pandas_datareader's default Yahoo API with yfinance 9 | yf.pdr_override() 10 | 11 | # Function to fetch stock data 12 | def fetch_stock_data(tickers, start_date, end_date): 13 | data = pdr.get_data_yahoo(tickers, start=start_date, end=end_date)['Adj Close'] 14 | data.index = pd.to_datetime(data.index) 15 | return data 16 | 17 | # Function to plot the spread of two stocks 18 | def plot_stock_spread(df, ticker1, ticker2, threshold=0.5, stop_loss=1): 19 | spread = df[ticker1] - df[ticker2] 20 | mean_spread = spread.mean() 21 | sell_threshold = mean_spread + threshold 22 | buy_threshold = mean_spread - threshold 23 | sell_stop = mean_spread + stop_loss 24 | buy_stop = mean_spread - stop_loss 25 | 26 | sns.set(style='white') 27 | fig, axes = plt.subplots(2, 1, figsize=(10, 6), gridspec_kw={'height_ratios': [2, 1]}) 28 | df[[ticker1, ticker2]].plot(ax=axes[0]) 29 | spread.plot(ax=axes[1], color='#85929E', linewidth=1.2) 30 | 31 | axes[1].axhline(sell_threshold, color='b', ls='--', linewidth=1) 32 | axes[1].axhline(buy_threshold, color='r', ls='--', linewidth=1) 33 | axes[1].axhline(sell_stop, color='g', ls='--', linewidth=1) 34 | axes[1].axhline(buy_stop, color='y', ls='--', linewidth=1) 35 | axes[1].fill_between(spread.index, sell_threshold, buy_threshold, facecolors='r', alpha=0.3) 36 | 37 | plt.legend(['Spread', 'Sell Threshold', 'Buy Threshold', 'Sell Stop', 'Buy Stop']) 38 | plt.show() 39 | 40 | # Main 41 | stocks = ['CFG', 'JPM'] 42 | start_date = dt.date.today() - dt.timedelta(days=365) 43 | end_date = dt.date.today() 44 | df = fetch_stock_data(stocks, start_date, end_date) 45 | plot_stock_spread(df, stocks[0], stocks[1]) -------------------------------------------------------------------------------- /portfolio_strategies/support_resistance_finder.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import yfinance as yf 4 | import matplotlib.pyplot as plt 5 | from mplfinance.original_flavor import candlestick_ohlc 6 | import matplotlib.dates as mpl_dates 7 | from pandas_datareader import data as pdr 8 | import datetime 9 | 10 | # Function to retrieve stock data 11 | def fetch_stock_data(ticker, start_date, end_date): 12 | df = pdr.get_data_yahoo(ticker, start=start_date, end=end_date).reset_index() 13 | df["Date"] = df["Date"].apply(mpl_dates.date2num) 14 | return df[['Date', 'Open', 'High', 'Low', 'Close']] 15 | 16 | # Function to identify support and resistance levels 17 | def identify_levels(df): 18 | levels = [] 19 | for i in range(2, df.shape[0] - 2): 20 | if is_support(df, i): 21 | levels.append((i, df["Low"][i], "Support")) 22 | elif is_resistance(df, i): 23 | levels.append((i, df["High"][i], "Resistance")) 24 | return levels 25 | 26 | # Define support and resistance checks 27 | def is_support(df, i): 28 | return df["Low"][i] < min(df["Low"][i - 1], df["Low"][i + 1]) 29 | 30 | def is_resistance(df, i): 31 | return df["High"][i] > max(df["High"][i - 1], df["High"][i + 1]) 32 | 33 | # Function to plot support and resistance levels 34 | def plot_support_resistance(df, levels): 35 | fig, ax = plt.subplots() 36 | candlestick_ohlc(ax, df.values, width=0.6, colorup='green', colordown='red', alpha=0.8) 37 | ax.xaxis.set_major_formatter(mpl_dates.DateFormatter('%d-%m-%Y')) 38 | 39 | for level in levels: 40 | plt.hlines(level[1], xmin=df["Date"][level[0]], xmax=max(df["Date"]), colors="blue") 41 | plt.title(f"Support and Resistance for {ticker.upper()}") 42 | plt.xlabel("Date") 43 | plt.ylabel("Price") 44 | plt.show() 45 | 46 | # Main 47 | ticker = input("Enter a ticker: ") 48 | num_of_years = 0.2 49 | start_date = datetime.date.today() - datetime.timedelta(days=int(365.25 * num_of_years)) 50 | end_date = datetime.date.today() 51 | 52 | df = fetch_stock_data(ticker, start_date, end_date) 53 | levels = identify_levels(df) 54 | plot_support_resistance(df, levels) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | autoscraper==1.1.14 2 | backtrader==1.9.78.123 3 | beautifulsoup4==4.12.2 4 | config==0.5.1 5 | factor_analyzer==0.5.0 6 | fastai==2.7.13 7 | fbprophet==0.7.1 8 | Flask==2.2.2 9 | FundamentalAnalysis==0.3.1 10 | googletrans==3.0.0 11 | ipython==8.15.0 12 | keras==3.0.2 13 | lxml==4.9.3 14 | matplotlib==3.7.2 15 | mplfinance==0.12.10b0 16 | networkx==3.1 17 | nltk==3.9 18 | numpy==1.24.3 19 | numpy_financial==1.0.0 20 | pandas==2.0.3 21 | pandas_datareader==0.10.0 22 | pmdarima==2.0.4 23 | praw==7.7.1 24 | pyfolio==0.9.2 25 | python_dateutil==2.8.2 26 | quandl==3.7.0 27 | Requests==2.31.0 28 | robin_stocks==3.0.6 29 | schedule==1.2.1 30 | scikit_learn==1.3.0 31 | scipy==1.11.4 32 | seaborn==0.13.1 33 | selenium==4.16.0 34 | statsmodels==0.14.0 35 | streamlit==1.37.0 36 | ta==0.10.2 37 | tensorflow==2.15.0.post1 38 | textblob==0.17.1 39 | tweepy==4.14.0 40 | twilio==8.11.0 41 | vaderSentiment==3.3.2 42 | webdriver_manager==4.0.1 43 | websocket_client==0.58.0 44 | wordcloud==1.9.3 45 | yahoo_earnings_calendar==0.6.0 46 | yfinance==0.2.33 47 | -------------------------------------------------------------------------------- /stock_analysis/capm_analysis.py: -------------------------------------------------------------------------------- 1 | from pandas_datareader import data as pdr 2 | import numpy as np 3 | import pandas as pd 4 | import datetime 5 | from socket import gaierror 6 | from pandas_datareader._utils import RemoteDataError 7 | import tickers as ti 8 | 9 | # Fetches stock data for a given ticker. 10 | def get_stock_data(ticker, start, end): 11 | return pdr.DataReader(ticker, 'yahoo', start, end) 12 | 13 | # Calculates expected return using CAPM. 14 | def calculate_expected_return(stock, index, risk_free_return): 15 | # Resample to monthly data 16 | return_stock = stock.resample('M').last()['Adj Close'] 17 | return_index = index.resample('M').last()['Adj Close'] 18 | 19 | # Create DataFrame with returns 20 | df = pd.DataFrame({'stock_close': return_stock, 'index_close': return_index}) 21 | df[['stock_return', 'index_return']] = np.log(df / df.shift(1)) 22 | df = df.dropna() 23 | 24 | # Calculate beta and alpha 25 | beta, alpha = np.polyfit(df['index_return'], df['stock_return'], deg=1) 26 | 27 | # Calculate expected return 28 | expected_return = risk_free_return + beta * (df['index_return'].mean() * 12 - risk_free_return) 29 | return expected_return 30 | 31 | def main(): 32 | # Risk-free return rate 33 | risk_free_return = 0.02 34 | 35 | # Define time period 36 | start = datetime.datetime.now() - datetime.timedelta(days=365) 37 | end = datetime.date.today() 38 | 39 | # Get all tickers in NASDAQ 40 | nasdaq_tickers = ti.tickers_nasdaq() 41 | 42 | # Index ticker 43 | index_ticker = '^GSPC' 44 | 45 | # Fetch index data 46 | try: 47 | index_data = get_stock_data(index_ticker, start, end) 48 | except RemoteDataError: 49 | print("Failed to fetch index data.") 50 | return 51 | 52 | # Loop through NASDAQ tickers 53 | for ticker in nasdaq_tickers: 54 | try: 55 | # Fetch stock data 56 | stock_data = get_stock_data(ticker, start, end) 57 | 58 | # Calculate expected return 59 | expected_return = calculate_expected_return(stock_data, index_data, risk_free_return) 60 | 61 | # Output expected return 62 | print(f'{ticker}: Expected Return: {expected_return}') 63 | 64 | except (RemoteDataError, gaierror): 65 | print(f"Data not available for ticker: {ticker}") 66 | 67 | if __name__ == "__main__": 68 | main() -------------------------------------------------------------------------------- /stock_analysis/earnings_call_sentiment_analysis.py: -------------------------------------------------------------------------------- 1 | from textblob import TextBlob 2 | import requests 3 | import numpy as np 4 | 5 | # Retrieves earnings call transcript from API. 6 | def get_earnings_call_transcript(api_key, company, quarter, year): 7 | url = f'https://financialmodelingprep.com/api/v3/earning_call_transcript/{company}?quarter={quarter}&year={year}&apikey={api_key}' 8 | response = requests.get(url) 9 | return response.json()[0]['content'] 10 | 11 | # Performs sentiment analysis on the transcript. 12 | def analyze_sentiment(transcript): 13 | sentiment_call = TextBlob(transcript) 14 | return sentiment_call 15 | 16 | # Counts the number of positive, negative, and neutral sentences. 17 | def count_sentiments(sentiment_call): 18 | positive, negative, neutral = 0, 0, 0 19 | all_sentences = [] 20 | 21 | for sentence in sentiment_call.sentences: 22 | polarity = sentence.sentiment.polarity 23 | if polarity < 0: 24 | negative += 1 25 | elif polarity > 0: 26 | positive += 1 27 | else: 28 | neutral += 1 29 | all_sentences.append(polarity) 30 | 31 | return positive, negative, neutral, np.array(all_sentences) 32 | 33 | def main(): 34 | api_key = 'your api key' 35 | company = 'AAPL' 36 | 37 | # Get transcript and perform sentiment analysis 38 | transcript = get_earnings_call_transcript(api_key, company, 3, 2020) 39 | sentiment_call = analyze_sentiment(transcript) 40 | 41 | # Count sentiments and calculate mean polarity 42 | positive, negative, neutral, all_sentences = count_sentiments(sentiment_call) 43 | mean_polarity = all_sentences.mean() 44 | 45 | # Print results 46 | print(f"Earnings Call Transcript for {company}:\n{transcript}\n") 47 | print(f"Overall Sentiment: {sentiment_call.sentiment}") 48 | print(f"Positive Sentences: {positive}, Negative Sentences: {negative}, Neutral Sentences: {neutral}") 49 | print(f"Average Sentence Polarity: {mean_polarity}") 50 | 51 | # Print very positive sentences 52 | print("\nHighly Positive Sentences:") 53 | for sentence in sentiment_call.sentences: 54 | if sentence.sentiment.polarity > 0.8: 55 | print(sentence) 56 | 57 | if __name__ == "__main__": 58 | main() -------------------------------------------------------------------------------- /stock_analysis/estimating_returns.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | from scipy.stats import norm 5 | import datetime as dt 6 | from pandas_datareader import DataReader 7 | 8 | # Fetches stock data and calculates annual returns. 9 | def get_stock_returns(ticker, start_date, end_date): 10 | stock_data = DataReader(ticker, 'yahoo', start_date, end_date) 11 | stock_data = stock_data.reset_index() 12 | open_prices = stock_data['Open'].tolist() 13 | open_prices = open_prices[::253] # Annual data, assuming 253 trading days per year 14 | df_returns = pd.DataFrame({'Open': open_prices}) 15 | df_returns['Return'] = df_returns['Open'].pct_change() 16 | return df_returns.dropna() 17 | 18 | # Plots the normal distribution of returns. 19 | def plot_return_distribution(returns, ticker): 20 | x = np.linspace(min(returns), max(returns), 100) 21 | mean, std = np.mean(returns), np.std(returns) 22 | plt.plot(x, norm.pdf(x, mean, std)) 23 | plt.title(f'Normal Distribution of Returns for {ticker.upper()}') 24 | plt.xlabel('Returns') 25 | plt.ylabel('Frequency') 26 | plt.show() 27 | 28 | # Estimates the probability of returns falling within specified bounds. 29 | def estimate_return_probability(returns, lower_bound, higher_bound): 30 | mean, std = np.mean(returns), np.std(returns) 31 | prob = round(norm(mean, std).cdf(higher_bound) - norm(mean, std).cdf(lower_bound), 4) 32 | return prob 33 | 34 | def main(): 35 | stock_ticker = 'AAPL' 36 | higher_bound, lower_bound = 0.3, 0.2 37 | num_of_years = 40 38 | 39 | # Calculate start and end dates 40 | end_date = dt.datetime.now() 41 | start_date = end_date - dt.timedelta(days=int(365.25 * num_of_years)) 42 | 43 | # Retrieve and process stock data 44 | df_returns = get_stock_returns(stock_ticker, start_date, end_date) 45 | plot_return_distribution(df_returns['Return'], stock_ticker) 46 | 47 | # Estimate probability 48 | prob = estimate_return_probability(df_returns['Return'], lower_bound, higher_bound) 49 | print(f'The probability of returns falling between {lower_bound} and {higher_bound} for {stock_ticker.upper()} is: {prob}') 50 | 51 | if __name__ == "__main__": 52 | main() -------------------------------------------------------------------------------- /stock_analysis/kelly_criterion.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import yfinance as yf 4 | import datetime as dt 5 | 6 | # Define stock symbol and time frame for analysis 7 | symbol = 'BAC' 8 | num_of_years = 1 9 | start_date = dt.date.today() - dt.timedelta(days=365 * num_of_years) 10 | end_date = dt.date.today() 11 | 12 | # Download stock data using yfinance package 13 | stock_data = yf.download(symbol, start=start_date, end=end_date) 14 | 15 | # Calculate daily returns and drop rows with missing data 16 | stock_data['Returns'] = stock_data['Adj Close'].pct_change() 17 | stock_data.dropna(inplace=True) 18 | 19 | # Display the first few rows of the data for verification 20 | print(stock_data.head()) 21 | 22 | # Calculate Kelly Criterion 23 | # Extract positive (wins) and negative (losses) returns 24 | wins = stock_data['Returns'][stock_data['Returns'] > 0] 25 | losses = stock_data['Returns'][stock_data['Returns'] <= 0] 26 | 27 | # Calculate win ratio and win-loss ratio 28 | win_ratio = len(wins) / len(stock_data['Returns']) 29 | win_loss_ratio = np.mean(wins) / np.abs(np.mean(losses)) 30 | 31 | # Apply Kelly Criterion formula 32 | kelly_criterion = win_ratio - ((1 - win_ratio) / win_loss_ratio) 33 | 34 | # Print the Kelly Criterion percentage 35 | print('Kelly Criterion: {:.3f}%'.format(kelly_criterion * 100)) -------------------------------------------------------------------------------- /stock_analysis/ma_backtesting.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import yfinance as yf 5 | import datetime as dt 6 | 7 | # Configure the stock symbol, moving average windows, initial capital, and date range 8 | symbol = 'MSFT' 9 | short_window = 20 10 | long_window = 50 11 | initial_capital = 10000 # Starting capital 12 | num_of_years = 3 13 | start_date = dt.date.today() - dt.timedelta(days=365 * num_of_years) 14 | end_date = dt.date.today() 15 | 16 | # Download stock data 17 | stock_data = yf.download(symbol, start=start_date, end=end_date) 18 | 19 | # Calculate short and long moving averages 20 | stock_data['Short_MA'] = stock_data['Adj Close'].rolling(window=short_window).mean() 21 | stock_data['Long_MA'] = stock_data['Adj Close'].rolling(window=long_window).mean() 22 | 23 | # Generate trading signals (1 = buy, 0 = hold/sell) 24 | stock_data['Signal'] = np.where(stock_data['Short_MA'] > stock_data['Long_MA'], 1, 0) 25 | stock_data['Positions'] = stock_data['Signal'].diff() 26 | 27 | # Calculate daily and cumulative portfolio returns 28 | stock_data['Daily P&L'] = stock_data['Adj Close'].diff() * stock_data['Signal'] 29 | stock_data['Total P&L'] = stock_data['Daily P&L'].cumsum() 30 | stock_data['Positions'] *= 100 # Position size for each trade 31 | 32 | # Construct a portfolio to keep track of holdings and cash 33 | portfolio = pd.DataFrame(index=stock_data.index) 34 | portfolio['Holdings'] = stock_data['Positions'] * stock_data['Adj Close'] 35 | portfolio['Cash'] = initial_capital - portfolio['Holdings'].cumsum() 36 | portfolio['Total'] = portfolio['Cash'] + stock_data['Positions'].cumsum() * stock_data['Adj Close'] 37 | portfolio['Returns'] = portfolio['Total'].pct_change() 38 | 39 | # Plotting the strategy results and stock prices 40 | fig = plt.figure(figsize=(14, 10)) 41 | ax1 = fig.add_subplot(2, 1, 1) 42 | stock_data[['Short_MA', 'Long_MA', 'Adj Close']].plot(ax=ax1, lw=2.) 43 | ax1.plot(stock_data.loc[stock_data['Positions'] == 1.0].index, stock_data['Short_MA'][stock_data['Positions'] == 1.0],'^', markersize=10, color='g', label='Buy Signal') 44 | ax1.plot(stock_data.loc[stock_data['Positions'] == -1.0].index, stock_data['Short_MA'][stock_data['Positions'] == -1.0],'v', markersize=10, color='r', label='Sell Signal') 45 | ax1.set_title(f'{symbol} Moving Average Crossover Strategy') 46 | ax1.set_ylabel('Price in $') 47 | ax1.grid() 48 | ax1.legend() 49 | 50 | # Plotting the portfolio value 51 | ax2 = fig.add_subplot(2, 1, 2) 52 | portfolio['Total'].plot(ax=ax2, lw=2.) 53 | ax2.set_ylabel('Portfolio Value in $') 54 | ax2.set_xlabel('Date') 55 | ax2.grid() 56 | plt.show() -------------------------------------------------------------------------------- /stock_analysis/ols_regression.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import numpy as np 3 | import pandas as pd 4 | from pandas_datareader.data import DataReader 5 | import matplotlib.pyplot as plt 6 | import statsmodels.api as sm 7 | from scipy import stats 8 | 9 | # Configure the stock symbol, start, and end dates for data 10 | stock = 'MSFT' 11 | start_date = datetime.datetime(2014, 12, 28) 12 | end_date = datetime.date.today() 13 | 14 | # Fetch stock and S&P 500 data 15 | stock_data = DataReader(stock, 'yahoo', start_date, end_date)['Close'] 16 | sp500_data = DataReader('^GSPC', 'yahoo', start_date, end_date)['Close'] 17 | 18 | # Combine data into a single DataFrame and calculate monthly returns 19 | combined_data = pd.concat([stock_data, sp500_data], axis=1) 20 | combined_data.columns = [stock, 'S&P500'] 21 | monthly_returns = combined_data.pct_change().dropna() 22 | 23 | # Define dependent and independent variables for regression 24 | X = monthly_returns['S&P500'] # Independent variable (S&P500 returns) 25 | y = monthly_returns[stock] # Dependent variable (Stock returns) 26 | 27 | # Ordinary Least Squares (OLS) Regression using statsmodels 28 | X_sm = sm.add_constant(X) # Adding a constant 29 | model = sm.OLS(y, X_sm) # Model definition 30 | results = model.fit() # Fit the model 31 | print(results.summary()) # Print the results summary 32 | 33 | # Linear Regression using scipy 34 | slope, intercept, r_value, p_value, std_err = stats.linregress(X, y) 35 | 36 | # Plotting stock and S&P 500 returns 37 | plt.figure(figsize=(14, 7)) 38 | plt.scatter(X, y, alpha=0.5, label='Daily Returns') 39 | plt.plot(X, intercept + slope * X, color='red', label='Regression Line') 40 | plt.title(f'Regression Analysis: {stock} vs S&P 500') 41 | plt.xlabel('S&P 500 Daily Returns') 42 | plt.ylabel(f'{stock} Daily Returns') 43 | plt.legend() 44 | plt.grid(True) 45 | plt.show() 46 | 47 | # Calculate beta and alpha 48 | beta = slope 49 | alpha = intercept 50 | print(f'alpha (intercept) = {alpha:.4f}') 51 | print(f'beta (slope) = {beta:.4f}') -------------------------------------------------------------------------------- /stock_analysis/performance_risk_analysis.py: -------------------------------------------------------------------------------- 1 | from pandas_datareader import DataReader 2 | import numpy as np 3 | import pandas as pd 4 | import datetime 5 | 6 | # Setting the stock and index symbols 7 | stock = 'MSFT' 8 | index = '^GSPC' 9 | 10 | # Defining time range for data 11 | start_date = datetime.datetime.now() - datetime.timedelta(days=1826) 12 | end_date = datetime.date.today() 13 | 14 | # Fetching data for the stock and S&P 500 index 15 | df_stock = DataReader(stock, 'yahoo', start_date, end_date) 16 | df_index = DataReader(index, 'yahoo', start_date, end_date) 17 | 18 | # Resampling the data to a monthly time series 19 | df_stock_monthly = df_stock['Adj Close'].resample('M').last() 20 | df_index_monthly = df_index['Adj Close'].resample('M').last() 21 | 22 | # Calculating monthly returns 23 | stock_returns = df_stock_monthly.pct_change().dropna() 24 | index_returns = df_index_monthly.pct_change().dropna() 25 | 26 | # Computing Beta, Alpha, and R-squared 27 | cov_matrix = np.cov(stock_returns, index_returns) 28 | beta = cov_matrix[0, 1] / cov_matrix[1, 1] 29 | alpha = np.mean(stock_returns) - beta * np.mean(index_returns) 30 | 31 | y_pred = alpha + beta * index_returns 32 | r_squared = 1 - np.sum((y_pred - stock_returns) ** 2) / np.sum((stock_returns - np.mean(stock_returns)) ** 2) 33 | 34 | # Calculating Volatility and Momentum 35 | volatility = np.std(stock_returns) * np.sqrt(12) # Annualized volatility 36 | momentum = np.prod(1 + stock_returns.tail(12)) - 1 # 1-year momentum 37 | 38 | # Printing the results 39 | print(f'Beta: {beta:.4f}') 40 | print(f'Alpha: {alpha:.4f} (annualized)') 41 | print(f'R-squared: {r_squared:.4f}') 42 | print(f'Volatility: {volatility:.4f}') 43 | print(f'1-Year Momentum: {momentum:.4f}') 44 | 45 | # Calculating the average volume over the last 60 days 46 | average_volume = df_stock['Volume'].tail(60).mean() 47 | print(f'Average Volume (last 60 days): {average_volume:.2f}') -------------------------------------------------------------------------------- /stock_analysis/risk_vs_returns.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import yfinance as yf 5 | import datetime as dt 6 | 7 | # Setting stock symbols and time range 8 | symbols = ['AAPL', 'MSFT', 'AMD', 'INTC', 'NVDA'] 9 | start = dt.date.today() - dt.timedelta(days=365*3) 10 | end = dt.date.today() 11 | 12 | # Downloading and processing stock data 13 | df = pd.DataFrame() 14 | for symbol in symbols: 15 | df[symbol] = yf.download(symbol, start=start, end=end)['Adj Close'] 16 | 17 | # Dropping rows with missing values 18 | df = df.dropna() 19 | 20 | # Calculating percentage change in stock prices 21 | rets = df.pct_change(periods=3) 22 | 23 | # Plotting scatter matrix 24 | scatter_matrix = pd.plotting.scatter_matrix(rets, diagonal='kde', figsize=(10, 10)) 25 | 26 | # Creating correlation matrix heatmap 27 | corr = rets.corr() 28 | plt.figure(figsize=(8, 6)) 29 | plt.imshow(corr, cmap='Blues', interpolation='none') 30 | plt.colorbar() 31 | plt.xticks(range(len(corr)), corr.columns) 32 | plt.yticks(range(len(corr)), corr.columns) 33 | plt.title("Correlation Matrix Heatmap") 34 | plt.show() 35 | 36 | # Plotting bar charts for risk and average returns 37 | plt.figure(figsize=(10, 4)) 38 | plt.bar(rets.columns, rets.std(), color='red', alpha=0.6, label='Risk (Std. Dev.)') 39 | plt.bar(rets.columns, rets.mean(), color='blue', alpha=0.6, label='Average Returns') 40 | plt.title("Risk and Average Returns") 41 | plt.xlabel("Stock Symbols") 42 | plt.ylabel("Value") 43 | plt.legend() 44 | plt.show() 45 | 46 | # Stacked bar chart for risk vs return 47 | plt.figure(figsize=(10, 4)) 48 | width = 0.35 49 | ind = np.arange(len(symbols)) 50 | plt.bar(ind, rets.mean(), width, color='blue', label='Average of Returns') 51 | plt.bar(ind, rets.std(), width, bottom=rets.mean(), color='red', label='Risk of Returns') 52 | plt.ylabel('Value') 53 | plt.xlabel('Stock Symbols') 54 | plt.title('Risk vs Average Returns') 55 | plt.xticks(ind, symbols) 56 | plt.legend() 57 | plt.show() 58 | 59 | # Scatter plot for expected returns vs risk 60 | plt.figure(figsize=(8, 6)) 61 | plt.scatter(rets.mean(), rets.std()) 62 | plt.xlabel('Expected Returns') 63 | plt.ylabel('Risk') 64 | for label, x, y in zip(rets.columns, rets.mean(), rets.std()): 65 | plt.annotate(label, xy=(x, y), xytext=(5, 5), textcoords='offset points') 66 | plt.title('Risk vs Expected Returns') 67 | plt.show() 68 | 69 | # Display table with risk vs expected returns 70 | risk_returns_table = pd.DataFrame({'Risk': rets.std(), 'Expected Returns': rets.mean()}) 71 | print("Table: Risk vs Expected Returns") 72 | print(risk_returns_table) -------------------------------------------------------------------------------- /stock_analysis/sma_histogram.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import matplotlib.ticker as mticker 6 | from pandas_datareader import data as pdr 7 | yf.pdr_override() 8 | 9 | # Setting parameters 10 | num_of_years = 40 11 | start = dt.datetime.now() - dt.timedelta(int(365.25 * num_of_years)) 12 | now = dt.date(2020, 10, 3) 13 | 14 | # Get user input for stock ticker 15 | stock = input("Enter the stock symbol: ") 16 | 17 | # Loop until user enters 'quit' 18 | while stock.lower() != "quit": 19 | # Fetch stock data 20 | df = pdr.get_data_yahoo(stock, start, now) 21 | 22 | # Calculate Simple Moving Average (SMA) 23 | sma = 50 24 | df['SMA' + str(sma)] = df['Adj Close'].rolling(window=sma).mean() 25 | 26 | # Calculate percentage change from SMA 27 | df['PC'] = ((df["Adj Close"] / df['SMA' + str(sma)]) - 1) * 100 28 | 29 | # Calculating statistics 30 | mean = df["PC"].mean() 31 | stdev = df["PC"].std() 32 | current = df["PC"].iloc[-1] 33 | yday = df["PC"].iloc[-2] 34 | 35 | # Displaying statistics 36 | print(f"Mean: {mean:.2f}, Standard Deviation: {stdev:.2f}, Current: {current:.2f}, Yesterday: {yday:.2f}") 37 | 38 | # Histogram settings 39 | bins = np.arange(-100, 100, 1) 40 | plt.figure(figsize=(15, 10)) 41 | plt.hist(df["PC"], bins=bins, alpha=0.5) 42 | plt.title(f"{stock} - % From {sma} SMA Histogram since {start.year}") 43 | plt.xlabel(f'Percent from {sma} SMA (bin size = 1)') 44 | plt.ylabel('Count') 45 | 46 | # Adding vertical lines for mean, std deviation, current and yesterday's percentage change 47 | for i in range(-3, 4): 48 | plt.axvline(x=mean + i * stdev, color='gray', linestyle='--', alpha=0.5 + abs(i)/6) 49 | plt.axvline(x=current, color='red', label='Today') 50 | plt.axvline(x=yday, color='blue', label='Yesterday') 51 | plt.legend() 52 | plt.show() 53 | 54 | # Next user input 55 | stock = input("Enter the stock symbol: ") -------------------------------------------------------------------------------- /stock_analysis/sp500_cot_sentiment_analysis.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import matplotlib.pyplot as plt 3 | import datetime 4 | import zipfile 5 | import urllib.request 6 | import shutil 7 | import os 8 | 9 | # Function to download and extract COT file 10 | def download_and_extract_cot_file(url, file_name): 11 | # Download and extract COT file 12 | with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file: 13 | shutil.copyfileobj(response, out_file) 14 | with zipfile.ZipFile(file_name) as zf: 15 | zf.extractall() 16 | 17 | # Download and process COT data for the last 5 years 18 | frames = [] 19 | this_year = datetime.datetime.now().year 20 | 21 | for year in range(this_year-5, this_year+1): 22 | url = f'https://www.cftc.gov/files/dea/history/fut_fin_xls_{year}.zip' 23 | download_and_extract_cot_file(url, f'{year}.zip') 24 | os.rename('FinFutYY.xls', f'{year}.xls') 25 | 26 | data = pd.read_excel(f'{year}.xls') 27 | data = data.set_index('Report_Date_as_MM_DD_YYYY') 28 | data.index = pd.to_datetime(data.index) 29 | data = data[data['Market_and_Exchange_Names'] == 'E-MINI S&P 500 - CHICAGO MERCANTILE EXCHANGE'] 30 | frames.append(data) 31 | 32 | # Concatenate yearly data frames 33 | df = pd.concat(frames) 34 | df.to_csv('COT_sp500_data.csv') 35 | 36 | # Read data for plotting 37 | df = pd.read_csv('COT_sp500_data.csv', index_col=0) 38 | df.index = pd.to_datetime(df.index) 39 | 40 | # Plotting 41 | plt.figure(figsize=(12, 6)) 42 | plt.plot(df.index, df['Pct_of_OI_Dealer_Long_All'], label='Dealer Long') 43 | plt.plot(df.index, df['Pct_of_OI_Lev_Money_Long_All'], label='Leveraged Long') 44 | plt.plot(df.index, df['Pct_of_OI_Dealer_Short_All'], label='Dealer Short') 45 | plt.plot(df.index, df['Pct_of_OI_Lev_Money_Short_All'], label='Leveraged Short') 46 | plt.xlabel('Date') 47 | plt.ylabel('Percentage') 48 | plt.title('Net Positions - Line Chart') 49 | plt.legend() 50 | plt.tight_layout() 51 | plt.show() 52 | 53 | # Box Plot 54 | plt.figure(figsize=(10, 6)) 55 | box_data = [df[col] for col in ['Pct_of_OI_Dealer_Long_All', 'Pct_of_OI_Dealer_Short_All', 'Pct_of_OI_Lev_Money_Long_All', 'Pct_of_OI_Lev_Money_Short_All']] 56 | plt.boxplot(box_data, labels=['Dealer Long', 'Dealer Short', 'Leveraged Money Long', 'Leveraged Money Short'], patch_artist=True) 57 | plt.title('Distribution of Open Interest by Category') 58 | plt.ylabel('Percentage') 59 | plt.grid(True) 60 | plt.show() -------------------------------------------------------------------------------- /stock_analysis/stock_pivot_resistance.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import pandas_datareader as pdr 4 | import matplotlib.pyplot as plt 5 | 6 | # Use yfinance to override pandas_datareader's default 7 | yf.pdr_override() 8 | 9 | # Function to fetch and plot stock data with pivot points 10 | def plot_stock_pivot_resistance(stock_symbol, start_date, end_date): 11 | # Fetch stock data 12 | df = pdr.get_data_yahoo(stock_symbol, start_date, end_date) 13 | 14 | # Plot high prices 15 | df["High"].plot(label="High") 16 | 17 | # Initialize variables to find and store pivot points 18 | pivots = [] 19 | dates = [] 20 | counter = 0 21 | last_pivot = 0 22 | window_size = 10 23 | window = [0] * window_size 24 | date_window = [0] * window_size 25 | 26 | # Identify pivot points 27 | for i, high_price in enumerate(df["High"]): 28 | window = window[1:] + [high_price] 29 | date_window = date_window[1:] + [df.index[i]] 30 | 31 | current_max = max(window) 32 | if current_max == last_pivot: 33 | counter += 1 34 | else: 35 | counter = 0 36 | 37 | if counter == 5: 38 | last_pivot = current_max 39 | last_date = date_window[window.index(last_pivot)] 40 | pivots.append(last_pivot) 41 | dates.append(last_date) 42 | 43 | # Plot resistance levels for each pivot point 44 | for i in range(len(pivots)): 45 | time_delta = dt.timedelta(days=30) 46 | plt.plot_date([dates[i], dates[i] + time_delta], 47 | [pivots[i], pivots[i]], 48 | linestyle="-", linewidth=2, marker=",") 49 | 50 | # Configure plot settings 51 | plt.title(stock_symbol.upper() + ' Resistance Points') 52 | plt.gcf().autofmt_xdate() 53 | plt.subplots_adjust(bottom=0.2) 54 | plt.show() 55 | 56 | # Main execution loop 57 | if __name__ == "__main__": 58 | start_date = dt.datetime(2019, 6, 1) 59 | end_date = dt.datetime.now() 60 | 61 | while True: 62 | stock_symbol = input("Enter a stock symbol (or type 'quit' to exit): ") 63 | if stock_symbol.lower() == "quit": 64 | break 65 | plot_stock_pivot_resistance(stock_symbol, start_date, end_date) -------------------------------------------------------------------------------- /stock_analysis/stock_profit_loss.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import matplotlib.pyplot as plt 4 | 5 | def calculate_stock_profit_loss(symbol, start_date, end_date, initial_investment): 6 | # Download stock data 7 | dataset = yf.download(symbol, start_date, end_date) 8 | 9 | # Calculate the number of shares and investment values 10 | shares = initial_investment / dataset['Adj Close'][0] 11 | purchase_price = dataset['Adj Close'][0] 12 | current_value = shares * dataset['Adj Close'][-1] 13 | 14 | # Calculate profit or loss and related metrics 15 | profit_or_loss = current_value - initial_investment 16 | percentage_gain_or_loss = (profit_or_loss / current_value) * 100 17 | percentage_returns = (current_value - initial_investment) / initial_investment * 100 18 | net_gains_or_losses = (dataset['Adj Close'][-1] - dataset['Adj Close'][0]) / dataset['Adj Close'][0] * 100 19 | total_return = ((current_value / initial_investment) - 1) * 100 20 | 21 | # Calculate profit and loss for each day 22 | dataset['PnL'] = shares * (dataset['Adj Close'].diff()) 23 | 24 | # Visualize the profit and loss 25 | plt.figure(figsize=(16,8)) 26 | plt.plot(dataset['PnL']) 27 | plt.title(f'Profit and Loss for {symbol} Each Day') 28 | plt.xlabel('Date') 29 | plt.ylabel('Profit/Loss') 30 | plt.show() 31 | 32 | # Display financial analysis 33 | print(f"Financial Analysis for {symbol}") 34 | print('-' * 50) 35 | print(f"Profit or Loss: ${profit_or_loss:.2f}") 36 | print(f"Percentage Gain or Loss: {percentage_gain_or_loss:.2f}%") 37 | print(f"Percentage of Returns: {percentage_returns:.2f}%") 38 | print(f"Net Gains or Losses: {net_gains_or_losses:.2f}%") 39 | print(f"Total Returns: {total_return:.2f}%") 40 | 41 | # Main execution 42 | if __name__ == "__main__": 43 | symbol = 'MSFT' 44 | start_date = dt.date.today() - dt.timedelta(days=365) 45 | end_date = dt.date.today() 46 | initial_investment = 5000 47 | 48 | calculate_stock_profit_loss(symbol, start_date, end_date, initial_investment) -------------------------------------------------------------------------------- /stock_analysis/stock_returns_statistical_analysis.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import numpy as np 4 | import scipy.stats as stats 5 | import matplotlib.pyplot as plt 6 | 7 | def analyze_stock_returns(symbol, start, end): 8 | # Download stock data 9 | df = yf.download(symbol, start, end) 10 | 11 | # Calculate daily returns 12 | returns = df['Adj Close'].pct_change().dropna() 13 | 14 | # Calculate and print various statistics 15 | print('Mean of returns:', np.mean(returns)) 16 | print('Median of returns:', np.median(returns)) 17 | print('Mode of returns:', stats.mode(returns)[0][0]) 18 | print('Arithmetic average of returns:', returns.mean()) 19 | print('Geometric mean of returns:', stats.gmean(returns)) 20 | print('Standard deviation of returns:', returns.std()) 21 | print('Harmonic mean of returns:', len(returns) / np.sum(1.0/returns)) 22 | print('Skewness:', stats.skew(returns)) 23 | print('Kurtosis:', stats.kurtosis(returns)) 24 | 25 | # Jarque-Bera test 26 | jarque_bera_results = stats.jarque_bera(returns) 27 | is_normal = jarque_bera_results[1] > 0.05 28 | print("Jarque-Bera p-value:", jarque_bera_results[1]) 29 | print('Are the returns normal?', is_normal) 30 | 31 | # Histogram of returns 32 | plt.hist(returns, bins=30) 33 | plt.title(f'Histogram of Returns for {symbol.upper()}') 34 | plt.show() 35 | 36 | # Main execution 37 | if __name__ == "__main__": 38 | symbol = 'AAPL' 39 | start_date = dt.date.today() - dt.timedelta(days=365*5) 40 | end_date = dt.date.today() 41 | 42 | analyze_stock_returns(symbol, start_date, end_date) -------------------------------------------------------------------------------- /stock_analysis/var_analysis.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import scipy.stats as stats 6 | 7 | def calculate_var(stock, start, end): 8 | # Download data from Yahoo Finance 9 | df = yf.download(stock, start, end) 10 | 11 | # Calculate daily returns 12 | returns = df['Adj Close'].pct_change().dropna() 13 | 14 | # VaR using historical bootstrap method 15 | plt.figure(figsize=(10, 5)) 16 | returns.hist(bins=40, density=True, histtype='stepfilled', alpha=0.5) 17 | plt.title("Histogram of stock daily returns") 18 | plt.show() 19 | 20 | # VaR using variance-covariance method 21 | tdf, tmean, tsigma = stats.t.fit(returns) 22 | support = np.linspace(returns.min(), returns.max(), 100) 23 | plt.figure(figsize=(10, 5)) 24 | plt.plot(support, stats.t.pdf(support, loc=tmean, scale=tsigma, df=tdf), "r-") 25 | plt.title("VaR using variance-covariance method") 26 | plt.show() 27 | 28 | # Calculate VaR using normal distribution at 95% confidence level 29 | mean, sigma = returns.mean(), returns.std() 30 | VaR = stats.norm.ppf(0.05, mean, sigma) 31 | print("VaR using normal distribution at 95% confidence level:", VaR) 32 | 33 | # Main execution 34 | if __name__ == "__main__": 35 | stock = "AMD" 36 | start = dt.date.today() - dt.timedelta(days=365*9) 37 | end = dt.date.today() 38 | calculate_var(stock, start, end) -------------------------------------------------------------------------------- /stock_analysis/view_stock_returns.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | import datetime as dt 3 | import matplotlib.pyplot as plt 4 | import pandas as pd 5 | import matplotlib.dates as mdates 6 | 7 | def view_stock_returns(symbol, num_years): 8 | # Fetch stock data for the given number of years 9 | start_date = dt.date.today() - dt.timedelta(days=365 * num_years) 10 | end_date = dt.date.today() 11 | dataset = yf.download(symbol, start_date, end_date) 12 | 13 | # Plot Adjusted Close Price over time 14 | plt.figure(figsize=(15, 10)) 15 | plt.plot(dataset['Adj Close'], label='Adj Close') 16 | plt.title(f'{symbol} Closing Price Chart') 17 | plt.xlabel('Date') 18 | plt.ylabel('Price') 19 | plt.grid(True) 20 | plt.legend() 21 | plt.show() 22 | 23 | # Monthly Returns Analysis 24 | monthly_dataset = dataset.asfreq('BM') 25 | monthly_dataset['Returns'] = dataset['Adj Close'].pct_change().dropna() 26 | monthly_dataset['Month_Name'] = monthly_dataset.index.strftime('%b-%Y') 27 | monthly_dataset['ReturnsPositive'] = monthly_dataset['Returns'] > 0 28 | colors = monthly_dataset['ReturnsPositive'].map({True: 'g', False: 'r'}) 29 | 30 | plt.figure(figsize=(15, 10)) 31 | monthly_dataset['Returns'].plot(kind='bar', color=colors) 32 | plt.xticks(monthly_dataset.index, monthly_dataset['Month_Name'], rotation=45) 33 | plt.title('Monthly Returns') 34 | plt.xlabel('Month') 35 | plt.ylabel('Returns') 36 | plt.show() 37 | 38 | # Yearly Returns Analysis 39 | yearly_dataset = dataset.asfreq('BY') 40 | yearly_dataset['Returns'] = dataset['Adj Close'].pct_change().dropna() 41 | yearly_dataset['ReturnsPositive'] = yearly_dataset['Returns'] > 0 42 | colors_year = yearly_dataset['ReturnsPositive'].map({True: 'g', False: 'r'}) 43 | 44 | plt.figure(figsize=(15, 10)) 45 | plt.bar(yearly_dataset.index.year, yearly_dataset['Returns'], color=colors_year) 46 | plt.title('Yearly Returns') 47 | plt.xlabel('Year') 48 | plt.ylabel('Returns') 49 | plt.show() 50 | 51 | # Example Usage 52 | symbol = 'AAPL' 53 | num_years = 5 54 | view_stock_returns(symbol, num_years) -------------------------------------------------------------------------------- /stock_data/autoscraper_finviz_data.py: -------------------------------------------------------------------------------- 1 | from autoscraper import AutoScraper 2 | import pandas as pd 3 | 4 | # Fetches financial data for a list of tickers from Finviz using AutoScraper. 5 | def fetch_finviz_data(tickers, scraper_rule_path): 6 | # Create an instance of AutoScraper 7 | scraper = AutoScraper() 8 | 9 | # Load scraper rules from the specified file path 10 | scraper.load(scraper_rule_path) 11 | 12 | # Iterate over the tickers and scrape data 13 | for ticker in tickers: 14 | url = f'https://finviz.com/quote.ashx?t={ticker}' 15 | result = scraper.get_result(url)[0] 16 | 17 | # Extract attributes and values 18 | index = result.index('Index') 19 | attributes, values = result[index:], result[:index] 20 | 21 | # Create a DataFrame and display data 22 | df = pd.DataFrame(zip(attributes, values), columns=['Attributes', 'Values']) 23 | print(f'\n{ticker} Data:') 24 | print(df.set_index('Attributes')) 25 | 26 | # Example usage 27 | tickers = ['SCHB', 'AMZN', 'AAPL', 'MSFT', 'TSLA', 'AMD', 'NFLX'] 28 | scraper_rule_path = '../finviz_table' 29 | fetch_finviz_data(tickers, scraper_rule_path) -------------------------------------------------------------------------------- /stock_data/dividend_history.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | import time 3 | import requests 4 | import pandas as pd 5 | from lxml import html 6 | 7 | # Function to convert datetime to string format for URL 8 | def format_date(date_datetime): 9 | date_mktime = time.mktime(date_datetime.timetuple()) 10 | return str(int(date_mktime)) 11 | 12 | # Function to construct URL for Yahoo Finance dividend history 13 | def subdomain(symbol, start, end): 14 | format_url = f"{symbol}/history?period1={start}&period2={end}" 15 | tail_url = "&interval=div%7Csplit&filter=div&frequency=1d" 16 | return format_url + tail_url 17 | 18 | # Function to define HTTP headers for request 19 | def header(subdomain): 20 | hdrs = {"authority": "finance.yahoo.com", "method": "GET", "path": subdomain, 21 | "scheme": "https", "accept": "text/html,application/xhtml+xml", 22 | "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", 23 | "cache-control": "no-cache", "cookie": "cookies", "dnt": "1", "pragma": "no-cache", 24 | "sec-fetch-mode": "navigate", "sec-fetch-site": "same-origin", "sec-fetch-user": "?1", 25 | "upgrade-insecure-requests": "1", "user-agent": "Mozilla/5.0"} 26 | return hdrs 27 | 28 | # Function to scrape dividend history page and return DataFrame 29 | def scrape_page(url, header): 30 | page = requests.get(url, headers=header) 31 | element_html = html.fromstring(page.content) 32 | table = element_html.xpath('//table')[0] 33 | table_tree = html.tostring(table, method='xml') 34 | df = pd.read_html(table_tree) 35 | return df[0] 36 | 37 | # Function to clean dividend data 38 | def clean_dividends(symbol, dividends): 39 | dividends = dividends.drop(len(dividends) - 1) 40 | dividends = dividends.set_index('Date')['Dividends'].str.replace(r'\Dividend', '').astype(float) 41 | dividends.name = symbol 42 | return dividends 43 | 44 | # Main script 45 | if __name__ == '__main__': 46 | symbol = input("Enter a ticker: ").upper() 47 | start = format_date(datetime.today() - timedelta(days=9125)) 48 | end = format_date(datetime.today()) 49 | 50 | sub = subdomain(symbol, start, end) 51 | hdrs = header(sub) 52 | 53 | base_url = "https://finance.yahoo.com/quote/" 54 | url = base_url + sub 55 | dividends_df = scrape_page(url, hdrs) 56 | dividends = clean_dividends(symbol, dividends_df) 57 | 58 | print(dividends) -------------------------------------------------------------------------------- /stock_data/fibonacci_retracement.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from pandas_datareader import DataReader 3 | import pandas as pd 4 | import datetime 5 | 6 | # Fetch stock data from Yahoo Finance 7 | def fetch_stock_data(ticker, start, end): 8 | return DataReader(ticker, 'yahoo', start, end) 9 | 10 | # Calculate Fibonacci retracement levels 11 | def fibonacci_levels(price_min, price_max): 12 | diff = price_max - price_min 13 | return { 14 | '0%': price_max, 15 | '23.6%': price_max - 0.236 * diff, 16 | '38.2%': price_max - 0.382 * diff, 17 | '61.8%': price_max - 0.618 * diff, 18 | '100%': price_min 19 | } 20 | 21 | # Plot the stock data and Fibonacci levels 22 | def plot_fibonacci_retracement(stock_data, fib_levels): 23 | fig, ax = plt.subplots() 24 | ax.plot(stock_data['Close'], color='black') 25 | 26 | for level, price in fib_levels.items(): 27 | ax.axhline(y=price, color='blue', linestyle='--', label=f'{level} level at {price:.2f}') 28 | 29 | plt.title(f'{stock_ticker} Fibonacci Retracement') 30 | plt.ylabel('Price') 31 | plt.xlabel('Date') 32 | plt.legend() 33 | plt.show() 34 | 35 | # Main program 36 | if __name__ == '__main__': 37 | stock_ticker = 'AAPL' 38 | start_date = datetime.datetime(2020, 1, 1) 39 | end_date = datetime.date.today() 40 | 41 | stock_data = fetch_stock_data(stock_ticker, start_date, end_date) 42 | price_min = stock_data['Close'].min() 43 | price_max = stock_data['Close'].max() 44 | fib_levels = fibonacci_levels(price_min, price_max) 45 | 46 | plot_fibonacci_retracement(stock_data, fib_levels) -------------------------------------------------------------------------------- /stock_data/finviz_insider_trades.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from bs4 import BeautifulSoup as soup 3 | from urllib.request import Request, urlopen 4 | 5 | # Set display options for pandas 6 | pd.set_option('display.max_colwidth', 60) 7 | pd.set_option('display.max_columns', None) 8 | pd.set_option('display.max_rows', None) 9 | 10 | # Function to fetch HTML content from URL 11 | def fetch_html(url): 12 | req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 13 | webpage = urlopen(req).read() 14 | return soup(webpage, "html.parser") 15 | 16 | # Function to extract insider trades table 17 | def extract_insider_trades(html_soup): 18 | trades = pd.read_html(str(html_soup), attrs={'class': 'styled-table-new is-rounded is-condensed mt-2 w-full'})[0] 19 | return trades 20 | 21 | # Process the insider trades data 22 | def process_insider_trades(trades): 23 | # Rename columns and sort by date 24 | trades.columns = ['Ticker', 'Owner', 'Relationship', 'Date', 'Transaction', 'Cost', '#Shares', 'Value ($)', '#Shares Total', 'SEC Form 4'] 25 | trades.sort_values('Date', ascending=False, inplace=True) 26 | 27 | # Set the date column as index and drop unnecessary rows 28 | trades.set_index('Date', inplace=True) 29 | 30 | return trades.head() 31 | 32 | # Main function to scrape insider trades 33 | def scrape_insider_trades(): 34 | try: 35 | url = "https://finviz.com/insidertrading.ashx" 36 | html_soup = fetch_html(url) 37 | trades = extract_insider_trades(html_soup) 38 | processed_trades = process_insider_trades(trades) 39 | return processed_trades 40 | except Exception as e: 41 | return e 42 | 43 | # Call the function and print the result 44 | print('\nInsider Trades:') 45 | print(scrape_insider_trades()) -------------------------------------------------------------------------------- /stock_data/finviz_news_scraper.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from bs4 import BeautifulSoup as soup 3 | from urllib.request import Request, urlopen 4 | from datetime import datetime 5 | 6 | # Set up scraper 7 | url = "https://finviz.com/news.ashx" 8 | req = Request(url, headers={"User-Agent": "Mozilla/5.0"}) 9 | webpage = urlopen(req).read() 10 | html_content = soup(webpage, "html.parser") 11 | 12 | # Function to scrape and process news from Finviz 13 | def scrape_news(html_content, news_index): 14 | try: 15 | # Extract news table from HTML content 16 | news_table = pd.read_html(str(html_content))[news_index] 17 | # Set column names and drop unnecessary columns 18 | news_table.columns = ["0", "DateTime", "Headlines"] 19 | news_table = news_table.drop(columns=['0']) 20 | news_table = news_table.set_index('DateTime') 21 | # Set 'Date' as the index column 22 | return news_table 23 | except Exception as e: 24 | # Return error message if scraping fails 25 | return pd.DataFrame({'Error': [str(e)]}) 26 | 27 | # Scrape and print general and blog news 28 | print("\nGeneral News:") 29 | print(scrape_news(html_content, 3)) 30 | 31 | print("\nBlog News:") 32 | print(scrape_news(html_content, 4)) -------------------------------------------------------------------------------- /stock_data/fundamental_ratios.py: -------------------------------------------------------------------------------- 1 | import FundamentalAnalysis as fa 2 | import pandas as pd 3 | from pandas_datareader import data as pdr 4 | import yfinance as yf 5 | from config import financial_model_prep 6 | 7 | # Set the Yahoo Finance API override 8 | yf.pdr_override() 9 | 10 | # Get API key from config 11 | api_key = financial_model_prep() 12 | 13 | # Define a list of stock tickers 14 | ticker_list = ['TMUSR', 'AAPL', 'MSFT', 'AMZN', 'FB', 'GOOGL', 'GOOG', 'INTC', 'NVDA', 'ADBE', 15 | 'PYPL', 'CSCO', 'NFLX', 'PEP', 'TSLA'] 16 | 17 | # Download and save financial data for each stock 18 | for ticker in ticker_list: 19 | # Get key metrics and financial ratios 20 | key_metrics = fa.key_metrics(ticker, api_key, period="annual") 21 | financial_ratios = fa.financial_ratios(ticker, api_key, period="annual") 22 | 23 | # Save data to Excel files 24 | key_metrics.to_excel(f'{ticker}_key_metrics.xlsx') 25 | financial_ratios.to_excel(f'{ticker}_financial_ratios.xlsx') 26 | 27 | # Download stock price data for a specified date range 28 | start_date = "2017-01-01" 29 | stock_prices = pdr.get_data_yahoo(ticker_list, start=start_date)['Close'] 30 | 31 | # Save stock prices data to an Excel file 32 | stock_prices.to_excel('stock_prices.xlsx') 33 | 34 | # Print the latest data for each category 35 | print('Key Metrics for last ticker: ') 36 | print(key_metrics) 37 | 38 | print('Financial Ratios for last ticker: ') 39 | print(financial_ratios) 40 | 41 | print('Price History for tickers since', start_date, ':') 42 | print(stock_prices) -------------------------------------------------------------------------------- /stock_data/high_dividend_yield.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import pandas as pd 3 | from config import financial_model_prep 4 | import sys 5 | import os 6 | parent_dir = os.path.dirname(os.getcwd()) 7 | sys.path.append(parent_dir) 8 | import tickers as ti 9 | 10 | # Create an instance of the financial model prep class for API access 11 | demo = financial_model_prep() 12 | 13 | # Read ticker symbols from a saved pickle file 14 | symbols = ti.tickers_sp500() 15 | 16 | # Initialize a dictionary to store dividend yield data for each company 17 | yield_dict = {} 18 | 19 | # Loop through each ticker symbol in the list 20 | for company in symbols: 21 | try: 22 | # Fetch company data from FinancialModelingPrep API using the ticker symbol 23 | companydata = requests.get(f'https://fmpcloud.io/api/v3/profile/{company}?apikey={demo}') 24 | companydata = companydata.json() # Convert response to JSON format 25 | 26 | # Extract relevant data for dividend calculation 27 | latest_Annual_Dividend = companydata[0]['lastDiv'] 28 | price = companydata[0]['price'] 29 | market_Capitalization = companydata[0]['mktCap'] 30 | name = companydata[0]['companyName'] 31 | exchange = companydata[0]['exchange'] 32 | 33 | # Calculate the dividend yield 34 | dividend_yield = latest_Annual_Dividend / price 35 | 36 | # Store the extracted data in the yield_dict dictionary 37 | yield_dict[company] = { 38 | 'dividend_yield': dividend_yield, 39 | 'latest_price': price, 40 | 'latest_dividend': latest_Annual_Dividend, 41 | 'market_cap': market_Capitalization / 1000000, # Convert market cap to millions 42 | 'company_name': name, 43 | 'exchange': exchange 44 | } 45 | 46 | except Exception as e: 47 | # Skip to the next ticker if there's an error with the current one 48 | print(f"Error processing {company}: {e}") 49 | continue 50 | 51 | # Convert the yield_dict dictionary to a pandas DataFrame 52 | yield_dataframe = pd.DataFrame.from_dict(yield_dict, orient='index') 53 | 54 | # Sort the DataFrame by dividend yield in descending order 55 | yield_dataframe = yield_dataframe.sort_values('dividend_yield', ascending=False) 56 | 57 | # Display the sorted DataFrame 58 | print(yield_dataframe) -------------------------------------------------------------------------------- /stock_data/historical_sp500_data.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.data as pdr 2 | import yfinance as yf 3 | import datetime as dt 4 | import sys 5 | import os 6 | parent_dir = os.path.dirname(os.getcwd()) 7 | sys.path.append(parent_dir) 8 | import tickers as ti # Import custom module to get S&P 500 tickers 9 | 10 | # Override the default pandas_datareader method to use Yahoo Finance as the data source 11 | yf.pdr_override() 12 | 13 | # Obtain a list of S&P 500 ticker symbols 14 | tickers = ti.tickers_sp500() 15 | 16 | # Replace any periods in ticker symbols with hyphens for Yahoo Finance compatibility 17 | tickers = [item.replace('.', '-') for item in tickers] 18 | 19 | # Define the number of years to look back for historical data 20 | num_of_years = 10 21 | 22 | # Calculate the start date based on the desired number of years of data 23 | start = dt.date.today() - dt.timedelta(days=int(365.25 * num_of_years)) 24 | 25 | # Loop through each ticker symbol to retrieve historical data 26 | for ticker in tickers: 27 | try: 28 | # Fetch historical data for the ticker from Yahoo Finance 29 | df = pdr.get_data_yahoo(ticker, start) 30 | 31 | # Define the file path to save the historical data in CSV format 32 | output_path = f'{ticker}.csv' 33 | df.to_csv(output_path) 34 | 35 | # Print a message indicating successful data retrieval and saving 36 | print(f'{ticker} historical data saved to {output_path}') 37 | 38 | except Exception as e: 39 | # Print an error message and skip to the next ticker if an error occurs 40 | print(f"Error fetching data for {ticker}: {e}") 41 | continue -------------------------------------------------------------------------------- /stock_data/pivots_calculator.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | import matplotlib.pyplot as plt 3 | import yfinance 4 | 5 | # Set display options for Pandas 6 | import pandas as pd 7 | pd.set_option('display.max_columns', None) 8 | 9 | # Prompt user for stock ticker input 10 | stock = input('Enter a ticker: ') 11 | 12 | # Fetch historical data for the specified stock using yfinance 13 | ticker = yfinance.Ticker(stock) 14 | df = ticker.history(interval="1d") 15 | 16 | # Extract data for the last trading day and remove unnecessary columns 17 | last_day = df.tail(1).copy().drop(columns=['Dividends', 'Stock Splits']) 18 | 19 | # Calculate pivot points and support/resistance levels 20 | # Pivot point formula: (High + Low + Close) / 3 21 | last_day['Pivot'] = (last_day['High'] + last_day['Low'] + last_day['Close']) / 3 22 | last_day['R1'] = 2 * last_day['Pivot'] - last_day['Low'] # Resistance 1 23 | last_day['S1'] = 2 * last_day['Pivot'] - last_day['High'] # Support 1 24 | last_day['R2'] = last_day['Pivot'] + (last_day['High'] - last_day['Low']) # Resistance 2 25 | last_day['S2'] = last_day['Pivot'] - (last_day['High'] - last_day['Low']) # Support 2 26 | last_day['R3'] = last_day['Pivot'] + 2 * (last_day['High'] - last_day['Low']) # Resistance 3 27 | last_day['S3'] = last_day['Pivot'] - 2 * (last_day['High'] - last_day['Low']) # Support 3 28 | 29 | # Display calculated pivot points and support/resistance levels for the last trading day 30 | print(last_day) 31 | 32 | # Fetch intraday data for the specified stock 33 | data = yfinance.download(tickers=stock, period="1d", interval="1m") 34 | 35 | # Extract 'Close' prices from the intraday data for plotting 36 | df = data['Close'] 37 | 38 | # Create and configure the plot with support and resistance lines 39 | fig, ax = plt.subplots() 40 | plt.rcParams['figure.figsize'] = (15, 10) 41 | plt.plot(df) 42 | plt.axhline(last_day['R1'].tolist()[0], color='b', label='Resistance 1') 43 | plt.axhline(last_day['S1'].tolist()[0], color='b', label='Support 1') 44 | plt.axhline(last_day['R2'].tolist()[0], color='green', label='Resistance 2') 45 | plt.axhline(last_day['S2'].tolist()[0], color='green', label='Support 2') 46 | plt.axhline(last_day['R3'].tolist()[0], color='r', label='Resistance 3') 47 | plt.axhline(last_day['S3'].tolist()[0], color='r', label='Support 3') 48 | plt.legend() 49 | plt.title(f'{stock.upper()} - {dt.date.today()}') 50 | plt.xlabel('Time') 51 | plt.ylabel('Price') 52 | 53 | # Display the final plot 54 | plt.show() -------------------------------------------------------------------------------- /stock_data/reddit_scraper.py: -------------------------------------------------------------------------------- 1 | import praw 2 | import pandas as pd 3 | 4 | # Import Reddit API credentials from config file 5 | from config import get_reddit 6 | my_client_id, my_client_secret, my_user_agent = get_reddit() 7 | 8 | # Initialize a PRAW Reddit instance with provided credentials 9 | reddit = praw.Reddit(client_id=my_client_id, client_secret=my_client_secret, user_agent=my_user_agent) 10 | 11 | # Define subreddit and number of articles to scrape 12 | subreddit_name = 'fatFIRE' 13 | num_of_articles = 5 14 | 15 | # Fetch posts from the specified subreddit 16 | posts = [] 17 | subreddit = reddit.subreddit(subreddit_name) 18 | for post in subreddit.new(limit=num_of_articles): 19 | # Append relevant post details to the list 20 | posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) 21 | 22 | # Convert the list of posts into a Pandas DataFrame 23 | # Columns: title, score, id, subreddit, url, num_comments, body (post content), created (timestamp) 24 | posts_df = pd.DataFrame(posts, columns=['title', 'score', 'id', 'subreddit', 'url', 'num_comments', 'body', 'created']) 25 | 26 | # Drop unnecessary columns from the DataFrame for simplicity 27 | posts_df = posts_df.drop(columns=['score', 'id', 'subreddit', 'created', 'url']) 28 | 29 | # Display the resulting DataFrame 30 | print(posts_df) 31 | 32 | # Optionally, print specific post details such as title and body of the last post 33 | print("Title of the last post:", posts_df['title'].tolist()[-1]) 34 | print("Body of the last post:", posts_df['body'].tolist()[-1]) -------------------------------------------------------------------------------- /stock_data/yf_intraday_data.py: -------------------------------------------------------------------------------- 1 | # Importing necessary libraries 2 | import yfinance as yf 3 | import matplotlib.pyplot as plt 4 | 5 | # Function to download intraday data for a given stock symbol 6 | def download_intraday_data(stock_symbol): 7 | data = yf.download(tickers=stock_symbol, period="1d", interval="1m") 8 | return data 9 | 10 | # Function to plot close prices of the stock 11 | def plot_close_prices(stock_data, stock_symbol): 12 | close_prices = stock_data['Close'] 13 | 14 | # Creating the plot 15 | fig, ax = plt.subplots() 16 | ax.plot(close_prices) 17 | ax.set_title(f'Price for {stock_symbol}') 18 | ax.set_xlabel('Time') 19 | ax.set_ylabel('Price') 20 | plt.show() 21 | 22 | # Main script execution 23 | if __name__ == "__main__": 24 | symbol = "NKE" # Define the stock symbol 25 | 26 | # Downloading the intraday data 27 | intraday_data = download_intraday_data(symbol) 28 | 29 | # Printing the last 5 rows of the data 30 | print(intraday_data.tail()) 31 | 32 | # Plotting the close prices 33 | plot_close_prices(intraday_data, symbol) 34 | -------------------------------------------------------------------------------- /technical_indicators/EMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 4) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 15 18 | df["EMA"] = ( 19 | df["Adj Close"].ewm(ignore_na=False, span=n, min_periods=n, adjust=True).mean() 20 | ) 21 | 22 | plt.figure(figsize=(14, 7)) 23 | plt.plot(df["Adj Close"]) 24 | plt.plot(df["EMA"]) 25 | plt.ylabel("Price") 26 | plt.xlabel("Date") 27 | plt.title("Stock Closing Price of " + str(n) + "-Day Exponential Moving Average") 28 | plt.legend(loc="best") 29 | plt.show() 30 | 31 | # ## Candlestick with EMA 32 | from matplotlib import dates as mdates 33 | 34 | dfc = df.copy() 35 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 36 | # dfc = dfc.dropna() 37 | dfc = dfc.reset_index() 38 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 39 | from mplfinance.original_flavor import candlestick_ohlc 40 | 41 | fig = plt.figure(figsize=(14, 7)) 42 | ax1 = plt.subplot(2, 1, 1) 43 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 44 | ax1.plot(df["EMA"], label="EMA") 45 | ax1.xaxis_date() 46 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 47 | ax1.grid(True, which="both") 48 | ax1.minorticks_on() 49 | ax1v = ax1.twinx() 50 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 51 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 52 | ax1v.axes.yaxis.set_ticklabels([]) 53 | ax1v.set_ylim(0, 3 * df.Volume.max()) 54 | ax1.set_title("Stock " + symbol + " Closing Price") 55 | ax1.legend(loc="best") 56 | ax1.set_ylabel("Price") 57 | ax1.set_xlabel("Date") 58 | plt.show() 59 | -------------------------------------------------------------------------------- /technical_indicators/EMA_volume.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 15 18 | df["EMAV"] = ( 19 | df["Volume"].ewm(ignore_na=False, span=n, min_periods=n, adjust=True).mean() 20 | ) 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title( 26 | "Stock " 27 | + symbol 28 | + " Closing Price of " 29 | + str(n) 30 | + "-Day Exponential Moving Average of Volume" 31 | ) 32 | ax1.set_ylabel("Price") 33 | ax1.legend(loc="best") 34 | 35 | ax2 = plt.subplot(2, 1, 2) 36 | ax2.plot(df["EMAV"]) 37 | ax2.grid() 38 | ax2.legend(loc="best") 39 | ax2.set_ylabel("EMAV") 40 | ax2.set_xlabel("Date") 41 | plt.show() 42 | 43 | # ## Candlestick with EMAV 44 | from matplotlib import dates as mdates 45 | 46 | dfc = df.copy() 47 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 48 | # dfc = dfc.dropna() 49 | dfc = dfc.reset_index() 50 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 51 | from mplfinance.original_flavor import candlestick_ohlc 52 | 53 | fig = plt.figure(figsize=(14, 7)) 54 | ax1 = plt.subplot(2, 1, 1) 55 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 56 | ax1.xaxis_date() 57 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 58 | ax1.grid(True, which="both") 59 | ax1.minorticks_on() 60 | ax1v = ax1.twinx() 61 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 62 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 63 | ax1v.axes.yaxis.set_ticklabels([]) 64 | ax1v.set_ylim(0, 3 * df.Volume.max()) 65 | ax1.set_title("Stock " + symbol + " Closing Price") 66 | ax1.set_ylabel("Price") 67 | 68 | ax2 = plt.subplot(2, 1, 2) 69 | ax2.plot(df["EMAV"], label="EMAV", color="g") 70 | ax2.grid() 71 | ax2.legend(loc="best") 72 | ax2.set_ylabel("EMAV") 73 | ax2.set_xlabel("Date") 74 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/EWMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 4) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 7 18 | df["EWMA"] = df["Adj Close"].ewm(ignore_na=False, min_periods=n - 1, span=n).mean() 19 | 20 | fig = plt.figure(figsize=(14, 7)) 21 | ax1 = plt.subplot(2, 1, 1) 22 | ax1.plot(df["Adj Close"]) 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | 26 | ax2 = plt.subplot(2, 1, 2) 27 | ax2.plot(df["EWMA"], label="Exponential Weighted Moving Average", color="red") 28 | # ax2.axhline(y=0, color='blue', linestyle='--') 29 | # ax2.axhline(y=0.5, color='darkblue') 30 | # ax2.axhline(y=-0.5, color='darkblue') 31 | ax2.grid() 32 | ax2.set_ylabel("Exponential Weighted Moving Average") 33 | ax2.set_xlabel("Date") 34 | ax2.legend(loc="best") 35 | plt.show() 36 | 37 | # ## Candlestick with Exponential Weighted Moving Average (EWMA) 38 | from matplotlib import dates as mdates 39 | 40 | dfc = df.copy() 41 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 42 | # dfc = dfc.dropna() 43 | dfc = dfc.reset_index() 44 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 45 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["EWMA"], label="Exponential Weighted Moving Average", color="red") 65 | # ax2.axhline(y=0, color='blue', linestyle='--') 66 | # ax2.axhline(y=0.5, color='darkblue') 67 | # ax2.axhline(y=-0.5, color='darkblue') 68 | ax2.grid() 69 | ax2.set_ylabel("Exponential Weighted Moving Average") 70 | ax2.set_xlabel("Date") 71 | ax2.legend(loc="best") 72 | plt.show() 73 | -------------------------------------------------------------------------------- /technical_indicators/MA_high_low.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["MA_High"] = df["High"].rolling(10).mean() 18 | df["MA_Low"] = df["Low"].rolling(10).mean() 19 | df = df.dropna() 20 | 21 | plt.figure(figsize=(16, 10)) 22 | plt.plot(df["Adj Close"]) 23 | plt.plot(df["MA_High"]) 24 | plt.plot(df["MA_Low"]) 25 | plt.title("Moving Average of High and Low for Stock") 26 | plt.legend(loc="best") 27 | plt.xlabel("Price") 28 | plt.ylabel("Date") 29 | plt.show() 30 | 31 | # # Candlestick with Moving Averages High and Low 32 | from matplotlib import dates as mdates 33 | 34 | df["VolumePositive"] = df["Open"] < df["Adj Close"] 35 | df = df.dropna() 36 | df = df.reset_index() 37 | df["Date"] = mdates.date2num(df["Date"].tolist()) 38 | 39 | from mplfinance.original_flavor import candlestick_ohlc 40 | 41 | fig = plt.figure(figsize=(20, 16)) 42 | ax1 = plt.subplot(2, 1, 1) 43 | candlestick_ohlc(ax1, df.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 44 | ax1.plot(df.Date, df["MA_High"], label="MA High") 45 | ax1.plot(df.Date, df["MA_Low"], label="MA Low") 46 | ax1.xaxis_date() 47 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 48 | # ax1.axhline(y=dfc['Adj Close'].mean(),color='r') 49 | ax1v = ax1.twinx() 50 | colors = df.VolumePositive.map({True: "g", False: "r"}) 51 | ax1v.bar(df.Date, df["Volume"], color=colors, alpha=0.4) 52 | ax1v.axes.yaxis.set_ticklabels([]) 53 | ax1v.set_ylim(0, 3 * df.Volume.max()) 54 | ax1.set_title("Stock " + symbol + " Closing Price") 55 | ax1.set_ylabel("Price") 56 | ax1.set_xlabel("Date") 57 | ax1.legend(loc="best") 58 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/PVI.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | returns = df["Adj Close"].pct_change() 18 | vol_increase = df["Volume"].shift(1) < df["Volume"] 19 | pvi = pd.Series(data=np.nan, index=df["Adj Close"].index, dtype="float64") 20 | 21 | pvi.iloc[0] = 1000 22 | for i in range(1, len(pvi)): 23 | if vol_increase.iloc[i]: 24 | pvi.iloc[i] = pvi.iloc[i - 1] * (1.0 + returns.iloc[i]) 25 | else: 26 | pvi.iloc[i] = pvi.iloc[i - 1] 27 | 28 | pvi = pvi.replace([np.inf, -np.inf], np.nan).fillna(1000) 29 | 30 | df["PVI"] = pd.Series(pvi) 31 | 32 | fig = plt.figure(figsize=(14, 7)) 33 | ax1 = plt.subplot(2, 1, 1) 34 | ax1.plot(df["Adj Close"]) 35 | ax1.set_title("Stock " + symbol + " Closing Price") 36 | ax1.set_ylabel("Price") 37 | ax1.legend(loc="best") 38 | 39 | ax2 = plt.subplot(2, 1, 2) 40 | ax2.plot(df["PVI"], label="Positive Volume Index", color="green") 41 | ax2.grid() 42 | ax2.legend(loc="best") 43 | ax2.set_ylabel("Positive Volume Index") 44 | ax2.set_xlabel("Date") 45 | plt.show() 46 | 47 | # ## Candlestick with Postive Volume Index 48 | from matplotlib import dates as mdates 49 | 50 | dfc = df.copy() 51 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 52 | # dfc = dfc.dropna() 53 | dfc = dfc.reset_index() 54 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 55 | from mplfinance.original_flavor import candlestick_ohlc 56 | 57 | fig = plt.figure(figsize=(14, 7)) 58 | ax1 = plt.subplot(2, 1, 1) 59 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 60 | ax1.xaxis_date() 61 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 62 | ax1.grid(True, which="both") 63 | ax1.minorticks_on() 64 | ax1v = ax1.twinx() 65 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 66 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 67 | ax1v.axes.yaxis.set_ticklabels([]) 68 | ax1v.set_ylim(0, 3 * df.Volume.max()) 69 | ax1.set_title("Stock " + symbol + " Closing Price") 70 | ax1.set_ylabel("Price") 71 | 72 | ax2 = plt.subplot(2, 1, 2) 73 | ax2.plot(df["PVI"], label="Positive Volume Index", color="green") 74 | ax2.grid() 75 | ax2.legend(loc="best") 76 | ax2.set_ylabel("Positive Volume Index") 77 | ax2.set_xlabel("Date") 78 | plt.show() 79 | -------------------------------------------------------------------------------- /technical_indicators/PVT.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["Momentum_1D"] = (df["Adj Close"] - df["Adj Close"].shift(1)).fillna(0) 18 | df["PVT"] = (df["Momentum_1D"] / df["Adj Close"].shift(1)) * df["Volume"] 19 | df["PVT"] = df["PVT"] - df["PVT"].shift(1) 20 | df["PVT"] = df["PVT"].fillna(0) 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title("Stock " + symbol + " Closing Price") 26 | ax1.set_ylabel("Price") 27 | 28 | ax2 = plt.subplot(2, 1, 2) 29 | ax2.plot(df["PVT"], label="Price Volume Trend") 30 | ax2.grid() 31 | ax2.legend(loc="best") 32 | ax2.set_ylabel("Price Volume Trend") 33 | ax2.set_xlabel("Date") 34 | plt.show() 35 | 36 | # ## Candlestick with Price Volume Trend (PVT) 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 44 | from mplfinance.original_flavor import candlestick_ohlc 45 | 46 | fig = plt.figure(figsize=(14, 7)) 47 | ax1 = plt.subplot(2, 1, 1) 48 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 49 | ax1.xaxis_date() 50 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 51 | ax1.grid(True, which="both") 52 | ax1.minorticks_on() 53 | ax1v = ax1.twinx() 54 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 55 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 56 | ax1v.axes.yaxis.set_ticklabels([]) 57 | ax1v.set_ylim(0, 3 * df.Volume.max()) 58 | ax1.set_title("Stock " + symbol + " Closing Price") 59 | ax1.set_ylabel("Price") 60 | 61 | ax2 = plt.subplot(2, 1, 2) 62 | ax2.plot(df["PVT"], label="Price Volume Trend") 63 | ax2.grid() 64 | ax2.legend(loc="best") 65 | ax2.set_ylabel("Price Volume Trend") 66 | ax2.set_xlabel("Date") 67 | plt.show() 68 | -------------------------------------------------------------------------------- /technical_indicators/ROC.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 12 18 | df["ROC"] = ( 19 | (df["Adj Close"] - df["Adj Close"].shift(n)) / df["Adj Close"].shift(n) 20 | ) * 100 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title("Stock " + symbol + " Closing Price") 26 | ax1.set_ylabel("Price") 27 | 28 | ax2 = plt.subplot(2, 1, 2) 29 | ax2.plot(df["ROC"], label="Rate of Change", color="black") 30 | ax2.axhline(y=0, color="blue", linestyle="--") 31 | ax2.axhline(y=10, color="red") 32 | ax2.axhline(y=-10, color="green") 33 | ax2.grid() 34 | ax2.set_ylabel("Rate of Change") 35 | ax2.set_xlabel("Date") 36 | ax2.legend(loc="best") 37 | plt.show() 38 | 39 | # ## Candlestick with (ROC) 40 | from matplotlib import dates as mdates 41 | 42 | dfc = df.copy() 43 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 44 | # dfc = dfc.dropna() 45 | dfc = dfc.reset_index() 46 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 47 | from mplfinance.original_flavor import candlestick_ohlc 48 | 49 | fig = plt.figure(figsize=(14, 7)) 50 | ax1 = plt.subplot(2, 1, 1) 51 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 52 | ax1.xaxis_date() 53 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 54 | ax1.grid(True, which="both") 55 | ax1.minorticks_on() 56 | ax1v = ax1.twinx() 57 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 58 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 59 | ax1v.axes.yaxis.set_ticklabels([]) 60 | ax1v.set_ylim(0, 3 * df.Volume.max()) 61 | ax1.set_title("Stock " + symbol + " Closing Price") 62 | ax1.set_ylabel("Price") 63 | 64 | ax2 = plt.subplot(2, 1, 2) 65 | ax2.plot(df["ROC"], label="Rate of Change", color="black") 66 | ax2.axhline(y=0, color="blue", linestyle="--") 67 | ax2.axhline(y=10, color="red") 68 | ax2.axhline(y=-10, color="green") 69 | ax2.grid() 70 | ax2.set_ylabel("Rate of Change") 71 | ax2.set_xlabel("Date") 72 | ax2.legend(loc="best") 73 | plt.show() 74 | -------------------------------------------------------------------------------- /technical_indicators/ROI.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["ROI"] = ( 18 | (df["Adj Close"] - df["Adj Close"].shift(1)) / df["Adj Close"].shift(1) * 100 19 | ) 20 | 21 | fig = plt.figure(figsize=(14, 7)) 22 | ax1 = plt.subplot(2, 1, 1) 23 | ax1.plot(df["Adj Close"]) 24 | ax1.set_title("Stock " + symbol + " Closing Price") 25 | ax1.set_ylabel("Price") 26 | 27 | ax2 = plt.subplot(2, 1, 2) 28 | ax2.plot(df["ROI"], label="Return on Investment", color="red") 29 | ax2.axhline(y=0, color="blue", linestyle="--") 30 | ax2.grid() 31 | ax2.set_ylabel("Return on Investmente") 32 | ax2.set_xlabel("Date") 33 | ax2.legend(loc="best") 34 | plt.show() 35 | 36 | # ## Candlestick with Return On Investment (ROI) 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 44 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 45 | 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["ROI"], label="Return on Investment", color="red") 65 | ax2.axhline(y=0, color="blue", linestyle="--") 66 | ax2.grid() 67 | ax2.set_ylabel("Return on Investmente") 68 | ax2.set_xlabel("Date") 69 | ax2.legend(loc="best") 70 | plt.show() 71 | -------------------------------------------------------------------------------- /technical_indicators/SMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 15 18 | df["SMA"] = df["Adj Close"].rolling(n).mean() 19 | 20 | plt.figure(figsize=(14, 7)) 21 | plt.plot(df["Adj Close"]) 22 | plt.plot(df["SMA"]) 23 | plt.ylabel("Price") 24 | plt.xlabel("Date") 25 | plt.title("Stock Closing Price of " + str(n) + "-Day Simple Moving Average") 26 | plt.legend(loc="best") 27 | plt.show() 28 | 29 | # ## Candlestick with SMA 30 | from matplotlib import dates as mdates 31 | 32 | dfc = df.copy() 33 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 34 | # dfc = dfc.dropna() 35 | dfc = dfc.reset_index() 36 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 37 | 38 | from mplfinance.original_flavor import candlestick_ohlc 39 | 40 | fig = plt.figure(figsize=(14, 7)) 41 | ax1 = plt.subplot(2, 1, 1) 42 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 43 | ax1.plot(df["SMA"], label="SMA") 44 | ax1.xaxis_date() 45 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 46 | ax1.grid(True, which="both") 47 | ax1.minorticks_on() 48 | ax1v = ax1.twinx() 49 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 50 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 51 | ax1v.axes.yaxis.set_ticklabels([]) 52 | ax1v.set_ylim(0, 3 * df.Volume.max()) 53 | ax1.set_title("Stock " + symbol + " Closing Price") 54 | ax1.legend(loc="best") 55 | ax1.set_ylabel("Price") 56 | ax1.set_xlabel("Date") 57 | plt.show() 58 | -------------------------------------------------------------------------------- /technical_indicators/TRIMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=180) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 7 18 | sma = df["Adj Close"].rolling(center=False, window=n, min_periods=n - 1).mean() 19 | df["TRIMA"] = sma.rolling(center=False, window=n, min_periods=n - 1).mean() 20 | 21 | fig = plt.figure(figsize=(14, 7)) 22 | ax1 = plt.subplot(2, 1, 1) 23 | ax1.plot(df["Adj Close"]) 24 | ax1.set_title("Stock " + symbol + " Closing Price") 25 | ax1.set_ylabel("Price") 26 | 27 | ax2 = plt.subplot(2, 1, 2) 28 | ax2.plot(df["TRIMA"], label="Triangular Moving Average", color="red") 29 | # ax2.axhline(y=0, color='blue', linestyle='--') 30 | ax2.grid() 31 | ax2.set_ylabel("Triangular Moving Average") 32 | ax2.set_xlabel("Date") 33 | ax2.legend(loc="best") 34 | plt.show() 35 | 36 | # ## Candlestick with Triangular Moving Average 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 44 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 45 | 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["TRIMA"], label="Triangular Moving Average", color="red") 65 | # ax2.axhline(y=0, color='blue', linestyle='--') 66 | ax2.grid() 67 | ax2.set_ylabel("Triangular Moving Average") 68 | ax2.set_xlabel("Date") 69 | ax2.legend(loc="best") 70 | plt.show() 71 | -------------------------------------------------------------------------------- /technical_indicators/TWAP.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=180) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | TP = (df[["Open", "High", "Low", "Adj Close"]].sum(axis=1)) / 4 18 | n = 10 19 | df["TWAP"] = TP.rolling(n).mean() 20 | 21 | fig = plt.figure(figsize=(14, 7)) 22 | ax1 = plt.subplot(2, 1, 1) 23 | ax1.plot(df["Adj Close"]) 24 | ax1.set_title("Stock " + symbol + " Closing Price") 25 | ax1.set_ylabel("Price") 26 | 27 | ax2 = plt.subplot(2, 1, 2) 28 | ax2.plot(df["TWAP"], label="Time Weighted Average Price", color="red") 29 | # ax2.axhline(y=0, color='blue', linestyle='--') 30 | # ax2.axhline(y=0.5, color='darkblue') 31 | # ax2.axhline(y=-0.5, color='darkblue') 32 | ax2.grid() 33 | ax2.set_ylabel("Time Weighted Average Price") 34 | ax2.set_xlabel("Date") 35 | ax2.legend(loc="best") 36 | plt.show() 37 | 38 | # ## Candlestick with Time Weighted Average Price (TWAP) 39 | from matplotlib import dates as mdates 40 | 41 | dfc = df.copy() 42 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 43 | # dfc = dfc.dropna() 44 | dfc = dfc.reset_index() 45 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 46 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 47 | from mplfinance.original_flavor import candlestick_ohlc 48 | 49 | fig = plt.figure(figsize=(14, 7)) 50 | ax1 = plt.subplot(2, 1, 1) 51 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 52 | ax1.xaxis_date() 53 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 54 | ax1.grid(True, which="both") 55 | ax1.minorticks_on() 56 | ax1v = ax1.twinx() 57 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 58 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 59 | ax1v.axes.yaxis.set_ticklabels([]) 60 | ax1v.set_ylim(0, 3 * df.Volume.max()) 61 | ax1.set_title("Stock " + symbol + " Closing Price") 62 | ax1.set_ylabel("Price") 63 | 64 | ax2 = plt.subplot(2, 1, 2) 65 | ax2.plot(df["TWAP"], label="Time Weighted Average Price", color="red") 66 | # ax2.axhline(y=0, color='blue', linestyle='--') 67 | # ax2.axhline(y=0.5, color='darkblue') 68 | # ax2.axhline(y=-0.5, color='darkblue') 69 | ax2.grid() 70 | ax2.set_ylabel("Time Weighted Average Price") 71 | ax2.set_xlabel("Date") 72 | ax2.legend(loc="best") 73 | plt.show() 74 | -------------------------------------------------------------------------------- /technical_indicators/VWAP.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | def VWAP(df): 18 | return (df["Adj Close"] * df["Volume"]).sum() / df["Volume"].sum() 19 | 20 | n = 14 21 | df["VWAP"] = pd.concat( 22 | [ 23 | (pd.Series(VWAP(df.iloc[i : i + n]), index=[df.index[i + n]])) 24 | for i in range(len(df) - n) 25 | ] 26 | ) 27 | df = df.dropna() 28 | 29 | plt.figure(figsize=(16, 10)) 30 | plt.plot(df["Adj Close"]) 31 | plt.plot(df["VWAP"]) 32 | plt.title("Volume Weighted Average Price for Stock") 33 | plt.legend(loc="best") 34 | plt.xlabel("Price") 35 | plt.ylabel("Date") 36 | plt.show() 37 | 38 | # ## Candlestick with VWAP 39 | from matplotlib import dates as mdates 40 | 41 | df["VolumePositive"] = df["Open"] < df["Adj Close"] 42 | df = df.dropna() 43 | df = df.reset_index() 44 | df["Date"] = mdates.date2num(df["Date"].tolist()) 45 | 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(16, 8)) 49 | ax1 = plt.subplot(111) 50 | candlestick_ohlc(ax1, df.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.plot(df.Date, df["VWAP"]) 52 | ax1.xaxis_date() 53 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 54 | # ax1.axhline(y=dfc['Adj Close'].mean(),color='r') 55 | ax1v = ax1.twinx() 56 | colors = df.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(df.Date, df["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | ax1.set_xlabel("Date") 63 | ax1.legend(loc="best") 64 | plt.show() 65 | -------------------------------------------------------------------------------- /technical_indicators/WMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | def WMA(data, n): 18 | 19 | ws = np.zeros(data.shape[0]) 20 | t_sum = sum(range(1, n + 1)) 21 | 22 | for i in range(n - 1, data.shape[0]): 23 | ws[i] = sum(data[i - n + 1 : i + 1] * np.linspace(1, n, n)) / t_sum 24 | 25 | return ws 26 | 27 | df["WMA"] = WMA(df["Adj Close"], 5) 28 | 29 | # Line Chart 30 | fig = plt.figure(figsize=(14, 7)) 31 | ax1 = plt.subplot(111) 32 | ax1.plot(df.index, df["Adj Close"]) 33 | ax1.plot(df.index[4:], df["WMA"][4:]) 34 | ax1v = ax1.twinx() 35 | ax1v.fill_between(df.index[0:], 0, df.Volume[0:], facecolor="#0079a3", alpha=0.4) 36 | ax1v.axes.yaxis.set_ticklabels([]) 37 | ax1v.set_ylim(0, 3 * df.Volume.max()) 38 | ax1.set_title("Stock " + symbol + " Closing Price") 39 | ax1.set_ylabel("Price") 40 | ax1.set_xlabel("Date") 41 | ax1.legend(loc="best") 42 | plt.show() 43 | 44 | # # Candlestick with WMA 45 | from matplotlib import dates as mdates 46 | 47 | dfc = df.copy() 48 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 49 | # dfc = dfc.dropna() 50 | dfc = dfc.reset_index() 51 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 52 | dfc = dfc.iloc[4:] 53 | 54 | from mplfinance.original_flavor import candlestick_ohlc 55 | 56 | fig = plt.figure(figsize=(14, 7)) 57 | ax1 = plt.subplot(2, 1, 1) 58 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 59 | ax1.plot(dfc.Date, dfc["WMA"], label="Weighted Moving Average") 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | ax1.xaxis_date() 63 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 64 | ax1.grid(True, which="both") 65 | ax1.minorticks_on() 66 | ax1v = ax1.twinx() 67 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 68 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 69 | ax1v.axes.yaxis.set_ticklabels([]) 70 | ax1v.set_ylim(0, 3 * dfc.Volume.max()) 71 | ax1.set_title("Stock " + symbol + " Closing Price") 72 | ax1.set_ylabel("Price") 73 | ax1.set_xlabel("Date") 74 | ax1.legend(loc="best") 75 | plt.show() 76 | -------------------------------------------------------------------------------- /technical_indicators/WSMA.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | def WSMA(df, column="Adj Close", n=14): 18 | ema = df[column].ewm(span=n, min_periods=n - 1).mean() 19 | K = 1 / n 20 | wsma = df[column] * K + ema * (1 - K) 21 | return wsma 22 | 23 | df["WSMA"] = WSMA(df, column="Adj Close", n=14) 24 | df = df.dropna() 25 | 26 | plt.figure(figsize=(16, 10)) 27 | plt.plot(df["Adj Close"]) 28 | plt.plot(df["WSMA"]) 29 | plt.title("Wilder's Smoothing Moving Average for Stock") 30 | plt.legend(loc="best") 31 | plt.xlabel("Price") 32 | plt.ylabel("Date") 33 | plt.show() 34 | 35 | # ## Candlestick with WSMA 36 | from matplotlib import dates as mdates 37 | 38 | df["VolumePositive"] = df["Open"] < df["Adj Close"] 39 | df = df.dropna() 40 | df = df.reset_index() 41 | df["Date"] = mdates.date2num(df["Date"].tolist()) 42 | 43 | from mplfinance.original_flavor import candlestick_ohlc 44 | 45 | fig = plt.figure(figsize=(16, 8)) 46 | ax1 = plt.subplot(111) 47 | candlestick_ohlc(ax1, df.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 48 | ax1.plot(df.Date, df["WSMA"]) 49 | ax1.xaxis_date() 50 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 51 | # ax1.axhline(y=dfc['Adj Close'].mean(),color='r') 52 | ax1v = ax1.twinx() 53 | colors = df.VolumePositive.map({True: "g", False: "r"}) 54 | ax1v.bar(df.Date, df["Volume"], color=colors, alpha=0.4) 55 | ax1v.axes.yaxis.set_ticklabels([]) 56 | ax1v.set_ylim(0, 3 * df.Volume.max()) 57 | ax1.set_title("Stock " + symbol + " Closing Price") 58 | ax1.set_ylabel("Price") 59 | ax1.set_xlabel("Date") 60 | ax1.legend(loc="best") 61 | plt.show() 62 | -------------------------------------------------------------------------------- /technical_indicators/Z_Score_Indicator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | from scipy.stats import zscore 18 | 19 | df["z_score"] = zscore(df["Adj Close"]) 20 | 21 | fig = plt.figure(figsize=(14, 7)) 22 | ax1 = plt.subplot(2, 1, 1) 23 | ax1.plot(df["Adj Close"]) 24 | ax1.set_title("Stock " + symbol + " Closing Price") 25 | ax1.set_ylabel("Price") 26 | ax1.legend(loc="best") 27 | 28 | ax2 = plt.subplot(2, 1, 2) 29 | ax2.plot(df["z_score"], label="Z-Score") 30 | ax2.axhline(y=1, color="black") 31 | ax2.grid() 32 | ax2.legend(loc="best") 33 | ax2.set_ylabel("Z-Score") 34 | ax2.set_xlabel("Date") 35 | plt.show() 36 | 37 | # ## Candlestick with Z-Score 38 | from matplotlib import dates as mdates 39 | 40 | dfc = df.copy() 41 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 42 | # dfc = dfc.dropna() 43 | dfc = dfc.reset_index() 44 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 45 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 46 | 47 | from mplfinance.original_flavor import candlestick_ohlc 48 | 49 | fig = plt.figure(figsize=(14, 7)) 50 | ax1 = plt.subplot(2, 1, 1) 51 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 52 | ax1.xaxis_date() 53 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 54 | ax1.grid(True, which="both") 55 | ax1.minorticks_on() 56 | ax1v = ax1.twinx() 57 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 58 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 59 | ax1v.axes.yaxis.set_ticklabels([]) 60 | ax1v.set_ylim(0, 3 * df.Volume.max()) 61 | ax1.set_title("Stock " + symbol + " Closing Price") 62 | ax1.set_ylabel("Price") 63 | 64 | ax2 = plt.subplot(2, 1, 2) 65 | ax2.plot(df["z_score"], label="Z-Score") 66 | ax2.axhline(y=1, color="black") 67 | ax2.grid() 68 | ax2.legend(loc="best") 69 | ax2.set_ylabel("Z-Score") 70 | ax2.set_xlabel("Date") 71 | plt.show() 72 | -------------------------------------------------------------------------------- /technical_indicators/absolute_price_oscillator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 4) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["HL"] = (df["High"] + df["Low"]) / 2 18 | df["HLC"] = (df["High"] + df["Low"] + df["Adj Close"]) / 3 19 | df["HLCC"] = (df["High"] + df["Low"] + df["Adj Close"] + df["Adj Close"]) / 4 20 | df["OHLC"] = (df["Open"] + df["High"] + df["Low"] + df["Adj Close"]) / 4 21 | 22 | df["Long_Cycle"] = df["Adj Close"].rolling(20).mean() 23 | df["Short_Cycle"] = df["Adj Close"].rolling(5).mean() 24 | df["APO"] = df["Long_Cycle"] - df["Short_Cycle"] 25 | 26 | fig = plt.figure(figsize=(14, 7)) 27 | ax1 = plt.subplot(2, 1, 1) 28 | ax1.plot(df["Adj Close"]) 29 | ax1.set_title("Stock " + symbol + " Closing Price") 30 | ax1.set_ylabel("Price") 31 | 32 | ax2 = plt.subplot(2, 1, 2) 33 | ax2.plot(df["APO"], label="Absolute Price Oscillator", color="green") 34 | ax2.grid() 35 | ax2.set_ylabel("Absolute Price Oscillator") 36 | ax2.set_xlabel("Date") 37 | ax2.legend(loc="best") 38 | plt.show() 39 | 40 | # ## Candlestick with Absolute Price Oscillator (APO) 41 | from matplotlib import dates as mdates 42 | 43 | dfc = df.copy() 44 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 45 | # dfc = dfc.dropna() 46 | dfc = dfc.reset_index() 47 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig = plt.figure(figsize=(14, 7)) 51 | ax1 = plt.subplot(2, 1, 1) 52 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 53 | ax1.xaxis_date() 54 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 55 | ax1.grid(True, which="both") 56 | ax1.minorticks_on() 57 | ax1v = ax1.twinx() 58 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 59 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 60 | ax1v.axes.yaxis.set_ticklabels([]) 61 | ax1v.set_ylim(0, 3 * df.Volume.max()) 62 | ax1.set_title("Stock " + symbol + " Closing Price") 63 | ax1.set_ylabel("Price") 64 | 65 | ax2 = plt.subplot(2, 1, 2) 66 | ax2.plot(df["APO"], label="Absolute Price Oscillator", color="green") 67 | ax2.grid() 68 | ax2.set_ylabel("Absolute Price Oscillator") 69 | ax2.set_xlabel("Date") 70 | ax2.legend(loc="best") 71 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/acceleration_bands.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 7 18 | UBB = df["High"] * (1 + 4 * (df["High"] - df["Low"]) / (df["High"] + df["Low"])) 19 | df["Upper_Band"] = UBB.rolling(n, center=False).mean() 20 | df["Middle_Band"] = df["Adj Close"].rolling(n).mean() 21 | LBB = df["Low"] * (1 - 4 * (df["High"] - df["Low"]) / (df["High"] + df["Low"])) 22 | df["Lower_Band"] = LBB.rolling(n, center=False).mean() 23 | 24 | plt.figure(figsize=(15, 7)) 25 | plt.plot(df["Adj Close"]) 26 | plt.plot(df["Upper_Band"]) 27 | plt.plot(df["Middle_Band"]) 28 | plt.plot(df["Lower_Band"]) 29 | plt.ylabel("Price") 30 | plt.xlabel("Date") 31 | plt.title("Stock Closing Price of " + str(n) + "-Day Acceleration Bands") 32 | plt.legend(loc="best") 33 | plt.show() 34 | 35 | from matplotlib import dates as mdates 36 | 37 | dfc = df.copy() 38 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 39 | # dfc = dfc.dropna() 40 | dfc = dfc.reset_index() 41 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 42 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 43 | from mplfinance.original_flavor import candlestick_ohlc 44 | 45 | fig = plt.figure(figsize=(15, 7)) 46 | ax1 = plt.subplot(2, 1, 1) 47 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 48 | ax1.plot(df["Upper_Band"], label="Upper Band") 49 | ax1.plot(df["Middle_Band"], label="Middle Band") 50 | ax1.plot(df["Lower_Band"], label="Lower Band") 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.legend(loc="best") 62 | ax1.set_ylabel("Price") 63 | ax1.set_xlabel("Date") 64 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/avg_true_range.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "NIO" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 14 18 | df["HL"] = df["High"] - df["Low"] 19 | df["HC"] = abs(df["High"] - df["Adj Close"].shift()) 20 | df["LC"] = abs(df["Low"] - df["Adj Close"].shift()) 21 | df["TR"] = df[["HL", "HC", "LC"]].max(axis=1) 22 | df["ATR"] = df["TR"].rolling(n).mean() 23 | df = df.drop(["HL", "HC", "LC", "TR"], axis=1) 24 | 25 | fig = plt.figure(figsize=(14, 7)) 26 | ax1 = plt.subplot(2, 1, 1) 27 | ax1.plot(df["Adj Close"]) 28 | ax1.set_title("Stock " + symbol + " Closing Price") 29 | ax1.set_ylabel("Price") 30 | ax1.legend(loc="best") 31 | 32 | ax2 = plt.subplot(2, 1, 2) 33 | ax2.plot(df["ATR"], label="ATR") 34 | ax2.axhline(y=1, color="black") 35 | ax2.grid() 36 | ax2.legend(loc="best") 37 | ax2.set_ylabel("Average True Range") 38 | ax2.set_xlabel("Date") 39 | plt.show() 40 | 41 | # ## Candlestick with ATR 42 | from matplotlib import dates as mdates 43 | 44 | dfc = df.copy() 45 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 46 | # dfc = dfc.dropna() 47 | dfc = dfc.reset_index() 48 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 49 | from mplfinance.original_flavor import candlestick_ohlc 50 | 51 | fig = plt.figure(figsize=(14, 7)) 52 | ax1 = plt.subplot(2, 1, 1) 53 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 54 | ax1.xaxis_date() 55 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 56 | ax1.grid(True, which="both") 57 | ax1.minorticks_on() 58 | ax1v = ax1.twinx() 59 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 60 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 61 | ax1v.axes.yaxis.set_ticklabels([]) 62 | ax1v.set_ylim(0, 3 * df.Volume.max()) 63 | ax1.set_title("Stock " + symbol + " Closing Price") 64 | ax1.set_ylabel("Price") 65 | 66 | ax2 = plt.subplot(2, 1, 2) 67 | ax2.plot(df["ATR"], label="ATR") 68 | ax2.axhline(y=1, color="black") 69 | ax2.grid() 70 | ax2.legend(loc="best") 71 | ax2.set_ylabel("Average True Range") 72 | ax2.set_xlabel("Date") 73 | plt.show() 74 | -------------------------------------------------------------------------------- /technical_indicators/beta_indicator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | market = "^GSPC" 12 | start = dt.date.today() - dt.timedelta(days=365 * 4) 13 | end = dt.date.today() 14 | 15 | # Read data 16 | df = yf.download(symbol, start, end) 17 | mk = yf.download(market, start, end) 18 | 19 | df["Returns"] = df["Adj Close"].pct_change().dropna() 20 | mk["Returns"] = mk["Adj Close"].pct_change().dropna() 21 | 22 | n = 5 23 | covar = df["Returns"].rolling(n).cov(mk["Returns"]) 24 | variance = mk["Returns"].rolling(n).var() 25 | df["Beta"] = covar / variance 26 | 27 | fig = plt.figure(figsize=(14, 7)) 28 | ax1 = plt.subplot(2, 1, 1) 29 | ax1.plot(df["Adj Close"]) 30 | ax1.set_title("Stock " + symbol + " Closing Price") 31 | ax1.set_ylabel("Price") 32 | 33 | ax2 = plt.subplot(2, 1, 2) 34 | ax2.plot(df["Beta"], label="Beta", color="red") 35 | # ax2.axhline(y=0, color='blue', linestyle='--') 36 | ax2.grid() 37 | ax2.set_ylabel("Beta") 38 | ax2.set_xlabel("Date") 39 | ax2.legend(loc="best") 40 | plt.show() 41 | 42 | # ## Candlestick with Beta 43 | from matplotlib import dates as mdates 44 | 45 | dfc = df.copy() 46 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 47 | # dfc = dfc.dropna() 48 | dfc = dfc.reset_index() 49 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 50 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 51 | from mplfinance.original_flavor import candlestick_ohlc 52 | 53 | fig = plt.figure(figsize=(14, 7)) 54 | ax1 = plt.subplot(2, 1, 1) 55 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 56 | ax1.xaxis_date() 57 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 58 | ax1.grid(True, which="both") 59 | ax1.minorticks_on() 60 | ax1v = ax1.twinx() 61 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 62 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 63 | ax1v.axes.yaxis.set_ticklabels([]) 64 | ax1v.set_ylim(0, 3 * df.Volume.max()) 65 | ax1.set_title("Stock " + symbol + " Closing Price") 66 | ax1.set_ylabel("Price") 67 | 68 | ax2 = plt.subplot(2, 1, 2) 69 | ax2.plot(df["Beta"], label="Beta", color="red") 70 | # ax2.axhline(y=0, color='blue', linestyle='--') 71 | ax2.grid() 72 | ax2.set_ylabel("Beta") 73 | ax2.set_xlabel("Date") 74 | ax2.legend(loc="best") 75 | plt.show() 76 | -------------------------------------------------------------------------------- /technical_indicators/candle_abs_returns.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["Absolute_Return"] = ( 18 | 100 * (df["Adj Close"] - df["Adj Close"].shift(1)) / df["Adj Close"].shift(1) 19 | ) 20 | fig = plt.figure(figsize=(14, 7)) 21 | ax1 = plt.subplot(2, 1, 1) 22 | ax1.plot(df["Adj Close"]) 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | 26 | ax2 = plt.subplot(2, 1, 2) 27 | ax2.plot(df["Absolute_Return"], label="Absolute Return", color="red") 28 | # ax2.axhline(y=0, color='blue', linestyle='--') 29 | # ax2.axhline(y=0.5, color='darkblue') 30 | # ax2.axhline(y=-0.5, color='darkblue') 31 | ax2.grid() 32 | ax2.set_ylabel("Absolute Return") 33 | ax2.set_xlabel("Date") 34 | ax2.legend(loc="best") 35 | plt.show() 36 | 37 | # ## Candlestick with Triple Exponential Weighted Moving Average 38 | from matplotlib import dates as mdates 39 | 40 | dfc = df.copy() 41 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 42 | # dfc = dfc.dropna() 43 | dfc = dfc.reset_index() 44 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 45 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["Absolute_Return"], label="Absolute Return", color="red") 65 | # ax2.axhline(y=0, color='blue', linestyle='--') 66 | # ax2.axhline(y=0.5, color='darkblue') 67 | # ax2.axhline(y=-0.5, color='darkblue') 68 | ax2.grid() 69 | ax2.set_ylabel("Absolute Return") 70 | ax2.set_xlabel("Date") 71 | ax2.legend(loc="best") 72 | plt.show() 73 | -------------------------------------------------------------------------------- /technical_indicators/central_pivot_range_cpr.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=180) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["Pivot"] = (df["High"] + df["Low"] + df["Adj Close"]) / 3.0 18 | df["BC"] = (df["High"] + df["Low"]) / 2.0 19 | df["TC"] = (df["Pivot"] - df["BC"]) + df["Pivot"] 20 | 21 | plt.figure(figsize=(14, 7)) 22 | plt.plot(df["Adj Close"]) 23 | plt.plot(df["TC"], label="Central Pivot Range") 24 | plt.plot(df["Pivot"], label="Central Pivot Range") 25 | plt.plot(df["BC"], label="Central Pivot Range") 26 | plt.title("Stock " + symbol + " Closing Price") 27 | plt.ylabel("Price") 28 | plt.legend(loc="best") 29 | plt.show() 30 | 31 | # ## Candlestick with Central Pivot Range (CPR) 32 | from matplotlib import dates as mdates 33 | 34 | dfc = df.copy() 35 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 36 | # dfc = dfc.dropna() 37 | dfc = dfc.reset_index() 38 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 39 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 40 | from mplfinance.original_flavor import candlestick_ohlc 41 | 42 | fig = plt.figure(figsize=(32, 25)) 43 | ax1 = plt.subplot(2, 1, 1) 44 | ax1.plot(df["Pivot"], label="Pivot") 45 | ax1.plot(df["BC"], label="BC") 46 | ax1.plot(df["TC"], label="TC") 47 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 48 | ax1.xaxis_date() 49 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 50 | ax1.grid(True, which="both") 51 | ax1.minorticks_on() 52 | ax1v = ax1.twinx() 53 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 54 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 55 | ax1v.axes.yaxis.set_ticklabels([]) 56 | ax1v.set_ylim(0, 3 * df.Volume.max()) 57 | ax1.set_title("Stock " + symbol + " Closing Price") 58 | ax1.set_ylabel("Price") 59 | ax1.legend(loc="best") 60 | plt.show() 61 | -------------------------------------------------------------------------------- /technical_indicators/commodity_channel_index.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 3) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 20 18 | df["TP"] = (df["High"] + df["Low"] + df["Adj Close"]) / 3 19 | df["SMA_TP"] = df["TP"].rolling(n).mean() 20 | df["SMA_STD"] = df["TP"].rolling(n).std() 21 | df["CCI"] = (df["TP"] - df["SMA_TP"]) / (0.015 * df["SMA_STD"]) 22 | df = df.drop(["TP", "SMA_TP", "SMA_STD"], axis=1) 23 | 24 | fig = plt.figure(figsize=(14, 7)) 25 | ax1 = plt.subplot(2, 1, 1) 26 | ax1.plot(df["Adj Close"]) 27 | ax1.set_title("Stock " + symbol + " Closing Price") 28 | ax1.set_ylabel("Price") 29 | 30 | ax2 = plt.subplot(2, 1, 2) 31 | ax2.plot(df["CCI"], label="Commodity Channel Index") 32 | ax2.axhline(y=100, color="red") 33 | ax2.axhline(y=-100, color="red") 34 | ax2.axhline(y=200, color="darkblue") 35 | ax2.axhline(y=-200, color="darkblue") 36 | ax2.grid() 37 | ax2.set_ylabel("CCI") 38 | ax2.set_xlabel("Date") 39 | plt.show() 40 | 41 | from matplotlib import dates as mdates 42 | 43 | dfc = df.copy() 44 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 45 | # dfc = dfc.dropna() 46 | dfc = dfc.reset_index() 47 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig = plt.figure(figsize=(14, 7)) 51 | ax1 = plt.subplot(2, 1, 1) 52 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 53 | ax1.xaxis_date() 54 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 55 | ax1.grid(True, which="both") 56 | ax1.minorticks_on() 57 | ax1v = ax1.twinx() 58 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 59 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 60 | ax1v.axes.yaxis.set_ticklabels([]) 61 | ax1v.set_ylim(0, 3 * df.Volume.max()) 62 | ax1.set_title("Stock " + symbol + " Closing Price") 63 | ax1.set_ylabel("Price") 64 | 65 | ax2 = plt.subplot(2, 1, 2) 66 | ax2.plot(df["CCI"], label="Commodity Channel Index") 67 | ax2.axhline(y=100, color="red") 68 | ax2.axhline(y=-100, color="red") 69 | ax2.axhline(y=200, color="darkblue") 70 | ax2.axhline(y=-200, color="darkblue") 71 | ax2.grid() 72 | ax2.set_ylabel("CCI") 73 | ax2.set_xlabel("Date") 74 | plt.show() 75 | -------------------------------------------------------------------------------- /technical_indicators/correlation_coeff.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol1 = "AAPL" 11 | symbol2 = "QQQ" 12 | start = dt.date.today() - dt.timedelta(days=365 * 2) 13 | end = dt.date.today() 14 | 15 | # Read data 16 | df1 = yf.download(symbol1, start, end) 17 | df2 = yf.download(symbol2, start, end) 18 | 19 | cc = df1["Adj Close"].corr(df2["Adj Close"]) 20 | 21 | df = pd.concat([df1["Adj Close"], df2["Adj Close"]], axis=1) 22 | df.columns = [symbol1, symbol2] 23 | 24 | n = 20 25 | df["Corr"] = df["AAPL"].rolling(n).corr(df["QQQ"]) 26 | 27 | fig = plt.figure(figsize=(14, 7)) 28 | ax1 = plt.subplot(2, 1, 1) 29 | ax1.plot(df1["Adj Close"]) 30 | ax1.set_title("Stock " + symbol1 + " Closing Price") 31 | ax1.set_ylabel("Price") 32 | ax1.legend(loc="best") 33 | 34 | ax2 = plt.subplot(2, 1, 2) 35 | ax2.plot(df["Corr"], label="Correlation Coefficient", color="black") 36 | ax2.grid() 37 | ax2.legend(loc="best") 38 | ax2.set_ylabel("Correlation Coefficient") 39 | ax2.set_xlabel("Date") 40 | plt.show() 41 | 42 | # ## Candlestick with Correlation Coefficient 43 | from matplotlib import dates as mdates 44 | 45 | dfc = df1.copy() 46 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 47 | # dfc = dfc.dropna() 48 | dfc = dfc.reset_index() 49 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 50 | from mplfinance.original_flavor import candlestick_ohlc 51 | 52 | fig = plt.figure(figsize=(14, 7)) 53 | ax1 = plt.subplot(2, 1, 1) 54 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 55 | ax1.xaxis_date() 56 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 57 | ax1.grid(True, which="both") 58 | ax1.minorticks_on() 59 | ax1v = ax1.twinx() 60 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 61 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 62 | ax1v.axes.yaxis.set_ticklabels([]) 63 | ax1v.set_ylim(0, 3 * df1.Volume.max()) 64 | ax1.set_title("Stock " + symbol1 + " Closing Price") 65 | ax1.set_ylabel("Price") 66 | 67 | ax2 = plt.subplot(2, 1, 2) 68 | ax2.plot(df["Corr"], label="Correlation Coefficient", color="black") 69 | ax2.grid() 70 | ax2.legend(loc="best") 71 | ax2.set_ylabel("Correlation Coefficient") 72 | ax2.set_xlabel("Date") 73 | plt.show() 74 | -------------------------------------------------------------------------------- /technical_indicators/covariance.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol1 = "AAPL" 11 | symbol2 = "QQQ" 12 | start = dt.date.today() - dt.timedelta(days=365 * 2) 13 | end = dt.date.today() 14 | 15 | # Read data 16 | df1 = yf.download(symbol1, start, end) 17 | df2 = yf.download(symbol2, start, end) 18 | 19 | c = df1["Adj Close"].cov(df2["Adj Close"]) 20 | 21 | df = pd.concat([df1["Adj Close"], df2["Adj Close"]], axis=1) 22 | df.columns = [symbol1, symbol2] 23 | 24 | n = 14 25 | df["Cov"] = df["AAPL"].rolling(n).cov(df["QQQ"]) 26 | 27 | fig = plt.figure(figsize=(14, 7)) 28 | ax1 = plt.subplot(2, 1, 1) 29 | ax1.plot(df1["Adj Close"]) 30 | ax1.set_title("Stock " + symbol1 + " Closing Price") 31 | ax1.set_ylabel("Price") 32 | ax1.legend(loc="best") 33 | 34 | ax2 = plt.subplot(2, 1, 2) 35 | ax2.plot(df["Cov"], label="Covariance", color="black") 36 | ax2.grid() 37 | ax2.legend(loc="best") 38 | ax2.set_ylabel("Covariance") 39 | ax2.set_xlabel("Date") 40 | plt.show() 41 | 42 | # ## Candlestick with Covariance 43 | from matplotlib import dates as mdates 44 | 45 | dfc = df1.copy() 46 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 47 | # dfc = dfc.dropna() 48 | dfc = dfc.reset_index() 49 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 50 | from mplfinance.original_flavor import candlestick_ohlc 51 | 52 | fig = plt.figure(figsize=(14, 7)) 53 | ax1 = plt.subplot(2, 1, 1) 54 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 55 | ax1.xaxis_date() 56 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 57 | ax1.grid(True, which="both") 58 | ax1.minorticks_on() 59 | ax1v = ax1.twinx() 60 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 61 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 62 | ax1v.axes.yaxis.set_ticklabels([]) 63 | ax1v.set_ylim(0, 3 * df1.Volume.max()) 64 | ax1.set_title("Stock " + symbol1 + " Closing Price") 65 | ax1.set_ylabel("Price") 66 | 67 | ax2 = plt.subplot(2, 1, 2) 68 | ax2.plot(df["Cov"], label="Covariance", color="black") 69 | ax2.grid() 70 | ax2.legend(loc="best") 71 | ax2.set_ylabel("Covariance") 72 | ax2.set_xlabel("Date") 73 | plt.show() 74 | -------------------------------------------------------------------------------- /technical_indicators/detrended_price_oscillator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 15 18 | df["DPO"] = ( 19 | df["Adj Close"].shift(int((0.5 * n) + 1)) - df["Adj Close"].rolling(n).mean() 20 | ) 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title("Stock " + symbol + " Closing Price") 26 | ax1.set_ylabel("Price") 27 | ax1.legend(loc="best") 28 | 29 | ax2 = plt.subplot(2, 1, 2) 30 | ax2.plot(df["DPO"], label="DPO") 31 | ax2.axhline(y=0, color="red") 32 | ax2.grid() 33 | ax2.legend() 34 | ax2.set_ylabel("DPO") 35 | ax2.set_xlabel("Date") 36 | plt.show() 37 | 38 | # ## Candlestick with DPO 39 | from matplotlib import dates as mdates 40 | 41 | dfc = df.copy() 42 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 43 | # dfc = dfc.dropna() 44 | dfc = dfc.reset_index() 45 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["DPO"], label="DPO") 65 | ax2.axhline(y=0, color="red") 66 | ax2.grid() 67 | ax2.set_ylabel("DPO") 68 | ax2.set_xlabel("Date") 69 | ax2.legend(loc="best") 70 | plt.show() 71 | -------------------------------------------------------------------------------- /technical_indicators/donchain_channel.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["Upper_Channel_Line"] = pd.Series.rolling(df["High"], window=20).max() 18 | df["Lower_Channel_Line"] = pd.Series.rolling(df["Low"], window=20).min() 19 | df["Middle_Channel_Line"] = (df["Upper_Channel_Line"] + df["Lower_Channel_Line"]) / 2 20 | df = df.dropna() 21 | 22 | plt.figure(figsize=(16, 10)) 23 | plt.plot(df["Adj Close"]) 24 | plt.fill_between( 25 | df.index, 26 | df["Lower_Channel_Line"], 27 | df["Upper_Channel_Line"], 28 | color="lightblue", 29 | alpha=0.4, 30 | ) 31 | plt.plot(df["Upper_Channel_Line"], c="darkred", linestyle="-", drawstyle="steps") 32 | plt.plot(df["Lower_Channel_Line"], c="forestgreen", linestyle="-", drawstyle="steps") 33 | plt.plot(df["Middle_Channel_Line"], c="blue", linestyle="-") 34 | plt.title("Dochain Channel for Stock") 35 | plt.legend(loc="best") 36 | plt.xlabel("Price") 37 | plt.ylabel("Date") 38 | plt.show() 39 | 40 | # ## Candlestick with Donchain Channel 41 | from matplotlib import dates as mdates 42 | 43 | dfc = df.copy() 44 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 45 | # dfc = dfc.dropna() 46 | dfc = dfc.reset_index() 47 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig, ax1 = plt.subplots(figsize=(20, 12)) 51 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 52 | # colors = ['red', 'green', 'blue'] 53 | # labels = ['Upper Channel Line', 'Lower Channel Line', 'Middle Channel Line'] 54 | for i in dfc[["Upper_Channel_Line", "Lower_Channel_Line", "Middle_Channel_Line"]]: 55 | ax1.plot(dfc["Date"], dfc[i]) 56 | ax1.xaxis_date() 57 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 58 | ax1.grid(True, which="both") 59 | ax1.minorticks_on() 60 | ax1v = ax1.twinx() 61 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 62 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 63 | ax1v.axes.yaxis.set_ticklabels([]) 64 | ax1v.set_ylim(0, 3 * df.Volume.max()) 65 | ax1.set_title("Stock " + symbol + " Closing Price") 66 | ax1.set_ylabel("Price") 67 | ax1.set_xlabel("Date") 68 | ax1.legend(loc="best") 69 | plt.show() 70 | -------------------------------------------------------------------------------- /technical_indicators/double_exp_moving_avg.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | import sys 9 | import os 10 | parent_dir = os.path.dirname(os.getcwd()) 11 | sys.path.append(parent_dir) 12 | import ta_functions as ta 13 | 14 | # input 15 | symbol = "AAPL" 16 | start = dt.date.today() - dt.timedelta(days=365 * 2) 17 | end = dt.date.today() 18 | 19 | # Read data 20 | df = yf.download(symbol, start, end) 21 | 22 | df["EMA"] = ta.EMA(df["Adj Close"], timeperiod=5) 23 | df["EMA_S"] = ta.EMA(df["EMA"], timeperiod=5) 24 | df["DEMA"] = (2 * df["EMA"]) - df["EMA_S"] 25 | 26 | # Line Chart 27 | fig = plt.figure(figsize=(16, 8)) 28 | ax1 = plt.subplot(111) 29 | ax1.plot(df.index, df["Adj Close"]) 30 | ax1.plot(df.index, df["DEMA"]) 31 | ax1.axhline(y=df["Adj Close"].mean(), color="r") 32 | ax1.grid() 33 | # ax1.grid(True, which='both') 34 | # ax1.grid(which='minor', linestyle='-', linewidth='0.5', color='black') 35 | # ax1.grid(which='major', linestyle='-', linewidth='0.5', color='red') 36 | # ax1.minorticks_on() 37 | ax1.legend(loc="best") 38 | ax1v = ax1.twinx() 39 | ax1v.fill_between(df.index[0:], 0, df.Volume[0:], facecolor="#0079a3", alpha=0.4) 40 | ax1v.axes.yaxis.set_ticklabels([]) 41 | ax1v.set_ylim(0, 3 * df.Volume.max()) 42 | ax1.set_title("Stock " + symbol + " Closing Price") 43 | ax1.set_ylabel("Price") 44 | plt.show() 45 | 46 | # ## Candlestick with DEMA 47 | from matplotlib import dates as mdates 48 | 49 | dfc = df.copy() 50 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 51 | dfc = dfc.dropna() 52 | dfc = dfc.reset_index() 53 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 54 | from mplfinance.original_flavor import candlestick_ohlc 55 | 56 | fig = plt.figure(figsize=(16, 8)) 57 | ax1 = plt.subplot(111) 58 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 59 | ax1.plot(df.index, df["DEMA"]) 60 | ax1.xaxis_date() 61 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 62 | ax1.grid(True, which="both") 63 | ax1.minorticks_on() 64 | ax1v = ax1.twinx() 65 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 66 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 67 | ax1v.axes.yaxis.set_ticklabels([]) 68 | ax1v.set_ylim(0, 3 * df.Volume.max()) 69 | ax1.set_title("Stock " + symbol + " Closing Price") 70 | ax1.set_ylabel("Price") 71 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/dynamic_momentum_index.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["sd"] = df["Adj Close"].rolling(5).std() 18 | df["asd"] = df["sd"].rolling(10).mean() 19 | df["DMI"] = 14 / (df["sd"] / df["asd"]) 20 | df = df.drop(["sd", "asd"], axis=1) 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title("Stock " + symbol + " Closing Price") 26 | ax1.set_ylabel("Price") 27 | 28 | ax2 = plt.subplot(2, 1, 2) 29 | ax2.plot(df["DMI"], label="Dynamic Momentum Index") 30 | ax2.grid() 31 | ax2.legend(loc="best") 32 | ax2.set_ylabel("Dynamic Momentum Index") 33 | ax2.set_xlabel("Date") 34 | plt.show() 35 | 36 | # ## Candlestick with Dynamic Momentum Index 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 44 | from mplfinance.original_flavor import candlestick_ohlc 45 | 46 | fig = plt.figure(figsize=(14, 7)) 47 | ax1 = plt.subplot(2, 1, 1) 48 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 49 | ax1.xaxis_date() 50 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 51 | ax1.grid(True, which="both") 52 | ax1.minorticks_on() 53 | ax1v = ax1.twinx() 54 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 55 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 56 | ax1v.axes.yaxis.set_ticklabels([]) 57 | ax1v.set_ylim(0, 3 * df.Volume.max()) 58 | ax1.set_title("Stock " + symbol + " Closing Price") 59 | ax1.set_ylabel("Price") 60 | 61 | ax2 = plt.subplot(2, 1, 2) 62 | ax2.plot(df["DMI"], label="Dynamic Momentum Index") 63 | ax2.grid() 64 | ax2.legend(loc="best") 65 | ax2.set_ylabel("Dynamic Momentum Index") 66 | ax2.set_xlabel("Date") 67 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/geometric_return_indicator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | from scipy.stats import gmean 18 | 19 | n = 10 20 | df["Geometric_Return"] = pd.Series(df["Adj Close"]).rolling(n).apply(gmean) 21 | 22 | fig = plt.figure(figsize=(14, 7)) 23 | ax1 = plt.subplot(2, 1, 1) 24 | ax1.plot(df["Adj Close"]) 25 | ax1.set_title("Stock " + symbol + " Closing Price") 26 | ax1.set_ylabel("Price") 27 | 28 | ax2 = plt.subplot(2, 1, 2) 29 | ax2.plot(df["Geometric_Return"], label="Geometric Return", color="red") 30 | # ax2.axhline(y=0, color='blue', linestyle='--') 31 | # ax2.axhline(y=0.5, color='darkblue') 32 | # ax2.axhline(y=-0.5, color='darkblue') 33 | ax2.grid() 34 | ax2.set_ylabel("Geometric Return") 35 | ax2.set_xlabel("Date") 36 | ax2.legend(loc="best") 37 | plt.show() 38 | 39 | # ## Candlestick with Triple Exponential Weighted Moving Average 40 | from matplotlib import dates as mdates 41 | 42 | dfc = df.copy() 43 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 44 | # dfc = dfc.dropna() 45 | dfc = dfc.reset_index() 46 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 47 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig = plt.figure(figsize=(14, 7)) 51 | ax1 = plt.subplot(2, 1, 1) 52 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 53 | ax1.xaxis_date() 54 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 55 | ax1.grid(True, which="both") 56 | ax1.minorticks_on() 57 | ax1v = ax1.twinx() 58 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 59 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 60 | ax1v.axes.yaxis.set_ticklabels([]) 61 | ax1v.set_ylim(0, 3 * df.Volume.max()) 62 | ax1.set_title("Stock " + symbol + " Closing Price") 63 | ax1.set_ylabel("Price") 64 | 65 | ax2 = plt.subplot(2, 1, 2) 66 | ax2.plot(df["Geometric_Return"], label="Geometric Return", color="red") 67 | # ax2.axhline(y=0, color='blue', linestyle='--') 68 | # ax2.axhline(y=0.5, color='darkblue') 69 | # ax2.axhline(y=-0.5, color='darkblue') 70 | ax2.grid() 71 | ax2.set_ylabel("Geometric Return") 72 | ax2.set_xlabel("Date") 73 | ax2.legend(loc="best") 74 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/high_minus_low.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start=start, end=end) 16 | 17 | df["H-L"] = df["High"] - df["Low"] 18 | 19 | fig = plt.figure(figsize=(14, 7)) 20 | ax1 = plt.subplot(2, 1, 1) 21 | ax1.plot(df["Adj Close"]) 22 | ax1.set_title("Stock " + symbol + " Closing Price") 23 | ax1.set_ylabel("Price") 24 | 25 | ax2 = plt.subplot(2, 1, 2) 26 | ax2.plot(df.index, df["H-L"], label="High Minus Low", color="green") 27 | ax2.grid() 28 | ax2.set_ylabel("High Minus Low") 29 | ax2.set_xlabel("Date") 30 | ax2.legend(loc="best") 31 | plt.show() 32 | 33 | # ## Candlestick with High Minus Low 34 | from matplotlib import dates as mdates 35 | 36 | dfc = df.copy() 37 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 38 | # dfc = dfc.dropna() 39 | dfc = dfc.reset_index() 40 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 41 | from mplfinance.original_flavor import candlestick_ohlc 42 | 43 | fig = plt.figure(figsize=(14, 7)) 44 | ax1 = plt.subplot(2, 1, 1) 45 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 46 | ax1.xaxis_date() 47 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 48 | ax1.grid(True, which="both") 49 | ax1.minorticks_on() 50 | ax1v = ax1.twinx() 51 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 52 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 53 | ax1v.axes.yaxis.set_ticklabels([]) 54 | ax1v.set_ylim(0, 3 * df.Volume.max()) 55 | ax1.set_title("Stock " + symbol + " Closing Price") 56 | ax1.set_ylabel("Price") 57 | 58 | ax2 = plt.subplot(2, 1, 2) 59 | ax2.plot(df.index, df["H-L"], label="High Minus Low", color="green") 60 | ax2.grid() 61 | ax2.set_ylabel("High Minus Low") 62 | ax2.set_xlabel("Date") 63 | ax2.legend(loc="best") 64 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/hull_moving_average.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import math 6 | import yfinance as yf 7 | import datetime as dt 8 | yf.pdr_override() 9 | import sys 10 | import os 11 | parent_dir = os.path.dirname(os.getcwd()) 12 | sys.path.append(parent_dir) 13 | import ta_functions as ta 14 | 15 | # input 16 | symbol = "AAPL" 17 | start = dt.date.today() - dt.timedelta(days=365 * 2) 18 | end = dt.date.today() 19 | 20 | # Read data 21 | df = yf.download(symbol, start, end) 22 | 23 | n = 30 24 | df["WMA_1"] = ta.WMA(df["Adj Close"], timeperiod=n / 2) * 2 25 | df["WMA_2"] = df["WMA_1"] - ta.WMA(df["Adj Close"], timeperiod=n) 26 | df["HMA"] = ta.WMA(df["WMA_2"], timeperiod=math.sqrt(n)) 27 | df = df.drop(["WMA_1", "WMA_2"], axis=1) 28 | 29 | fig = plt.figure(figsize=(14, 7)) 30 | ax1 = plt.subplot(2, 1, 1) 31 | ax1.plot(df["Adj Close"]) 32 | ax1.set_title("Stock " + symbol + " Closing Price") 33 | ax1.set_ylabel("Price") 34 | 35 | ax2 = plt.subplot(2, 1, 2) 36 | ax2.plot(df["HMA"], label="Hull Moving Average", color="red") 37 | # ax2.axhline(y=0, color='blue', linestyle='--') 38 | ax2.grid() 39 | ax2.set_ylabel("Hull Moving Average") 40 | ax2.set_xlabel("Date") 41 | ax2.legend(loc="best") 42 | plt.show() 43 | 44 | # ## Candlestick with Hull Moving Average 45 | from matplotlib import dates as mdates 46 | 47 | dfc = df.copy() 48 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 49 | # dfc = dfc.dropna() 50 | dfc = dfc.reset_index() 51 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 52 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 53 | from mplfinance.original_flavor import candlestick_ohlc 54 | 55 | fig = plt.figure(figsize=(14, 7)) 56 | ax1 = plt.subplot(2, 1, 1) 57 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 58 | ax1.xaxis_date() 59 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 60 | ax1.grid(True, which="both") 61 | ax1.minorticks_on() 62 | ax1v = ax1.twinx() 63 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 64 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 65 | ax1v.axes.yaxis.set_ticklabels([]) 66 | ax1v.set_ylim(0, 3 * df.Volume.max()) 67 | ax1.set_title("Stock " + symbol + " Closing Price") 68 | ax1.set_ylabel("Price") 69 | 70 | ax2 = plt.subplot(2, 1, 2) 71 | ax2.plot(df["HMA"], label="Hull Moving Average", color="red") 72 | # ax2.axhline(y=0, color='blue', linestyle='--') 73 | ax2.grid() 74 | ax2.set_ylabel("Hull Moving Average") 75 | ax2.set_xlabel("Date") 76 | ax2.legend(loc="best") 77 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/keltners_channels.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | import sys 9 | import os 10 | parent_dir = os.path.dirname(os.getcwd()) 11 | sys.path.append(parent_dir) 12 | import ta_functions as ta 13 | 14 | # input 15 | symbol = "AAPL" 16 | start = dt.date.today() - dt.timedelta(days=365 * 2) 17 | end = dt.date.today() 18 | 19 | # Read data 20 | df = yf.download(symbol, start, end) 21 | 22 | n = 20 23 | df["EMA"] = ta.EMA(df["Adj Close"], timeperiod=20) 24 | df["ATR"] = ta.ATR(df["High"], df["Low"], df["Adj Close"], timeperiod=10) 25 | df["Upper Line"] = df["EMA"] + 2 * df["ATR"] 26 | df["Lower Line"] = df["EMA"] - 2 * df["ATR"] 27 | del df["ATR"] 28 | 29 | plt.figure(figsize=(14, 7)) 30 | plt.plot(df["Adj Close"]) 31 | plt.plot(df["EMA"], label="Middle Line", linestyle="--") 32 | plt.plot(df["Upper Line"], color="g") 33 | plt.plot(df["Lower Line"], color="r") 34 | plt.ylabel("Price") 35 | plt.xlabel("Date") 36 | plt.title(symbol + " Closing Price of Keltners Channels") 37 | plt.legend(loc="best") 38 | plt.show() 39 | 40 | # ## Candlestick with Keltners Channels 41 | from matplotlib import dates as mdates 42 | 43 | dfc = df.copy() 44 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 45 | # dfc = dfc.dropna() 46 | dfc = dfc.reset_index() 47 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig = plt.figure(figsize=(14, 7)) 51 | ax1 = plt.subplot(2, 1, 1) 52 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 53 | ax1.plot(df["EMA"], label="Middle Line", linestyle="--") 54 | ax1.plot(df["Upper Line"], color="g") 55 | ax1.plot(df["Lower Line"], color="r") 56 | ax1.xaxis_date() 57 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 58 | ax1.grid(True, which="both") 59 | ax1.minorticks_on() 60 | ax1v = ax1.twinx() 61 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 62 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 63 | ax1v.axes.yaxis.set_ticklabels([]) 64 | ax1v.set_ylim(0, 3 * df.Volume.max()) 65 | ax1.set_title("Stock " + symbol + " Closing Price") 66 | ax1.legend(loc="best") 67 | ax1.set_ylabel("Price") 68 | ax1.set_xlabel("Date") 69 | plt.show() 70 | -------------------------------------------------------------------------------- /technical_indicators/linear_weighted_moving_average.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | def linear_weight_moving_average(close, n): 18 | lwma = [np.nan] * n 19 | for i in range(n, len(close)): 20 | lwma.append( 21 | (close[i - n : i] * (np.arange(n) + 1)).sum() / (np.arange(n + 1).sum()) 22 | ) 23 | return lwma 24 | 25 | df["LWMA"] = linear_weight_moving_average(df["Adj Close"], 5) 26 | 27 | fig = plt.figure(figsize=(14, 7)) 28 | ax1 = plt.subplot(2, 1, 1) 29 | ax1.plot(df["Adj Close"]) 30 | ax1.set_title("Stock " + symbol + " Closing Price") 31 | ax1.set_ylabel("Price") 32 | 33 | ax2 = plt.subplot(2, 1, 2) 34 | ax2.plot(df["LWMA"], label="Linearly Weighted Moving Average", color="red") 35 | # ax2.axhline(y=0, color='blue', linestyle='--') 36 | # ax2.axhline(y=0.5, color='darkblue') 37 | # ax2.axhline(y=-0.5, color='darkblue') 38 | ax2.grid() 39 | ax2.set_ylabel("Linearly Weighted Moving Average") 40 | ax2.set_xlabel("Date") 41 | ax2.legend(loc="best") 42 | plt.show() 43 | 44 | # ## Candlestick with Linearly Weighted Moving Average 45 | from matplotlib import dates as mdates 46 | 47 | dfc = df.copy() 48 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 49 | # dfc = dfc.dropna() 50 | dfc = dfc.reset_index() 51 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 52 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 53 | from mplfinance.original_flavor import candlestick_ohlc 54 | 55 | fig = plt.figure(figsize=(14, 7)) 56 | ax1 = plt.subplot(2, 1, 1) 57 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 58 | ax1.xaxis_date() 59 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 60 | ax1.grid(True, which="both") 61 | ax1.minorticks_on() 62 | ax1v = ax1.twinx() 63 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 64 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 65 | ax1v.axes.yaxis.set_ticklabels([]) 66 | ax1v.set_ylim(0, 3 * df.Volume.max()) 67 | ax1.set_title("Stock " + symbol + " Closing Price") 68 | ax1.set_ylabel("Price") 69 | 70 | ax2 = plt.subplot(2, 1, 2) 71 | ax2.plot(df["LWMA"], label="Linearly Weighted Moving Average", color="red") 72 | ax2.grid() 73 | ax2.set_ylabel("Linearly Weighted Moving Average") 74 | ax2.set_xlabel("Date") 75 | ax2.legend(loc="best") 76 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/momentum.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=180) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 14 18 | df["Momentum"] = df["Adj Close"] - df["Adj Close"].shift(n) 19 | 20 | fig = plt.figure(figsize=(14, 7)) 21 | ax1 = plt.subplot(2, 1, 1) 22 | ax1.plot(df["Adj Close"]) 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | 26 | ax2 = plt.subplot(2, 1, 2) 27 | ax2.plot(df["Momentum"], label="Momentum", color="black") 28 | # ax2.axhline(y=0, color='blue', linestyle='--') 29 | # ax2.axhline(y=10, color='red') 30 | # ax2.axhline(y=-10, color='green') 31 | ax2.grid() 32 | ax2.set_ylabel("Momentum") 33 | ax2.set_xlabel("Date") 34 | ax2.legend(loc="best") 35 | plt.show() 36 | 37 | # ## Candlestick with Momentum 38 | from matplotlib import dates as mdates 39 | 40 | dfc = df.copy() 41 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 42 | # dfc = dfc.dropna() 43 | dfc = dfc.reset_index() 44 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 45 | from mplfinance.original_flavor import candlestick_ohlc 46 | 47 | fig = plt.figure(figsize=(14, 7)) 48 | ax1 = plt.subplot(2, 1, 1) 49 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 50 | ax1.xaxis_date() 51 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 52 | ax1.grid(True, which="both") 53 | ax1.minorticks_on() 54 | ax1v = ax1.twinx() 55 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 56 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 57 | ax1v.axes.yaxis.set_ticklabels([]) 58 | ax1v.set_ylim(0, 3 * df.Volume.max()) 59 | ax1.set_title("Stock " + symbol + " Closing Price") 60 | ax1.set_ylabel("Price") 61 | 62 | ax2 = plt.subplot(2, 1, 2) 63 | ax2.plot(df["Momentum"], label="Momentum", color="black") 64 | ax2.grid() 65 | ax2.set_ylabel("Momentum") 66 | ax2.set_xlabel("Date") 67 | ax2.legend(loc="best") 68 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/moving_average_envelopes.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | import sys 9 | import os 10 | parent_dir = os.path.dirname(os.getcwd()) 11 | sys.path.append(parent_dir) 12 | import ta_functions as ta 13 | 14 | # input 15 | symbol = "AAPL" 16 | start = dt.date.today() - dt.timedelta(days=180) 17 | end = dt.date.today() 18 | 19 | # Read data 20 | df = yf.download(symbol, start, end) 21 | 22 | df["20SMA"] = ta.SMA(df["Adj Close"], timeperiod=20) 23 | df["Upper_Envelope"] = df["20SMA"] + (df["20SMA"] * 0.025) 24 | df["Lower_Envelope"] = df["20SMA"] - (df["20SMA"] * 0.025) 25 | 26 | # Line Chart 27 | plt.figure(figsize=(14, 7)) 28 | plt.plot(df["Adj Close"]) 29 | plt.plot(df["Upper_Envelope"], color="blue") 30 | plt.plot(df["Lower_Envelope"], color="red") 31 | plt.plot( 32 | df["Adj Close"].rolling(20).mean(), 33 | color="orange", 34 | label="Average Price", 35 | linestyle="--", 36 | ) 37 | plt.title("Stock of Moving Average Envelopes") 38 | plt.ylabel("Price") 39 | plt.xlabel("Date") 40 | plt.legend(loc="best") 41 | plt.show() 42 | 43 | # ## Candlestick with MAE 44 | from matplotlib import dates as mdates 45 | 46 | dfc = df.copy() 47 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 48 | # dfc = dfc.dropna() 49 | dfc = dfc.reset_index() 50 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 51 | from mplfinance.original_flavor import candlestick_ohlc 52 | 53 | fig = plt.figure(figsize=(14, 7)) 54 | ax1 = plt.subplot(111) 55 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 56 | ax1.plot(df["Upper_Envelope"], color="blue") 57 | ax1.plot(df["Lower_Envelope"], color="red") 58 | ax1.plot(df["Adj Close"].rolling(20).mean(), color="orange") 59 | ax1.xaxis_date() 60 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 61 | ax1.grid(True, which="both") 62 | ax1.minorticks_on() 63 | ax1v = ax1.twinx() 64 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 65 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 66 | ax1v.axes.yaxis.set_ticklabels([]) 67 | ax1v.set_ylim(0, 3 * df.Volume.max()) 68 | ax1.set_title("Stock " + symbol + " Closing Price") 69 | ax1.legend(loc="best") 70 | ax1.set_ylabel("Price") 71 | ax1.set_xlabel("Date") 72 | plt.show() 73 | -------------------------------------------------------------------------------- /technical_indicators/moving_average_high_low.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | n = 14 # number of periods 15 | df["MA_High"] = df["High"].rolling(n).mean() 16 | df["MA_Low"] = df["Low"].rolling(n).mean() 17 | 18 | fig = plt.figure(figsize=(14, 7)) 19 | ax1 = plt.subplot(2, 1, 1) 20 | ax1.plot(df["Adj Close"]) 21 | ax1.plot(df["MA_High"], label="Moving Average of High") 22 | ax1.plot(df["MA_Low"], label="Moving Average of Low") 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | ax1.legend(loc="best") 26 | 27 | ax2 = plt.subplot(2, 1, 2) 28 | ax2.plot(df["MA_High"], label="Moving Average of High") 29 | ax2.plot(df["MA_Low"], label="Moving Average of Low") 30 | ax2.grid() 31 | ax2.legend(loc="best") 32 | ax2.set_ylabel("Moving Average of High and Low") 33 | ax2.set_xlabel("Date") 34 | plt.show() 35 | 36 | # ## Candlestick with Moving Averages of the High and Low 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 44 | from mplfinance.original_flavor import candlestick_ohlc 45 | 46 | fig = plt.figure(figsize=(14, 7)) 47 | ax1 = plt.subplot(2, 1, 1) 48 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 49 | ax1.plot(df["MA_High"], label="Moving Average of High") 50 | ax1.plot(df["MA_Low"], label="Moving Average of Low") 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | ax1.legend(loc="best") 63 | 64 | ax2 = plt.subplot(2, 1, 2) 65 | ax2.plot(df["MA_High"], label="Moving Average of High") 66 | ax2.plot(df["MA_Low"], label="Moving Average of Low") 67 | ax2.grid() 68 | ax2.legend(loc="best") 69 | ax2.set_ylabel("Moving Average of High and Low") 70 | ax2.set_xlabel("Date") 71 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/moving_avg_env.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import sys 7 | import os 8 | parent_dir = os.path.dirname(os.getcwd()) 9 | sys.path.append(parent_dir) 10 | import ta_functions as ta 11 | 12 | yf.pdr_override() 13 | 14 | # input 15 | symbol = "AAPL" 16 | start = dt.date.today() - dt.timedelta(days=365 * 4) 17 | end = dt.date.today() 18 | 19 | # Read data 20 | df = yf.download(symbol, start, end) 21 | 22 | df["20SMA"] = ta.SMA(df["Adj Close"], timeperiod=20) 23 | df["Upper_Envelope"] = df["20SMA"] + (df["20SMA"] * 0.025) 24 | df["Lower_Envelope"] = df["20SMA"] - (df["20SMA"] * 0.025) 25 | 26 | # Line Chart 27 | plt.figure(figsize=(14, 7)) 28 | plt.plot(df["Adj Close"]) 29 | plt.plot(df["Upper_Envelope"], color="blue") 30 | plt.plot(df["Lower_Envelope"], color="red") 31 | plt.plot( 32 | df["Adj Close"].rolling(20).mean(), 33 | color="orange", 34 | label="Average Price", 35 | linestyle="--", 36 | ) 37 | plt.title("Stock of Moving Average Envelopes") 38 | plt.ylabel("Price") 39 | plt.xlabel("Date") 40 | plt.legend(loc="best") 41 | plt.show() 42 | 43 | # ## Candlestick with MAE 44 | from matplotlib import dates as mdates 45 | 46 | dfc = df.copy() 47 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 48 | # dfc = dfc.dropna() 49 | dfc = dfc.reset_index() 50 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 51 | from mplfinance.original_flavor import candlestick_ohlc 52 | 53 | fig = plt.figure(figsize=(14, 7)) 54 | ax1 = plt.subplot(111) 55 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 56 | ax1.plot(df["Upper_Envelope"], color="blue") 57 | ax1.plot(df["Lower_Envelope"], color="red") 58 | ax1.plot(df["Adj Close"].rolling(20).mean(), color="orange") 59 | ax1.xaxis_date() 60 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 61 | ax1.grid(True, which="both") 62 | ax1.minorticks_on() 63 | ax1v = ax1.twinx() 64 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 65 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 66 | ax1v.axes.yaxis.set_ticklabels([]) 67 | ax1v.set_ylim(0, 3 * df.Volume.max()) 68 | ax1.set_title("Stock " + symbol + " Closing Price") 69 | ax1.legend(loc="best") 70 | ax1.set_ylabel("Price") 71 | ax1.set_xlabel("Date") 72 | plt.show() 73 | -------------------------------------------------------------------------------- /technical_indicators/price_relative.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol1 = "AAPL" 11 | symbol2 = "^GSPC" 12 | start = dt.date.today() - dt.timedelta(days=365) 13 | end = dt.date.today() 14 | 15 | # Read data 16 | df1 = yf.download(symbol1, start, end) 17 | df2 = yf.download(symbol2, start, end) 18 | df = pd.concat([df1["Adj Close"], df2["Adj Close"]], axis=1) 19 | 20 | # Rename columns 21 | df.columns = [symbol1, symbol2] 22 | 23 | df["Price Relative"] = df["AAPL"] / df["^GSPC"] 24 | df["Percentage Change in Price Relative"] = ( 25 | (df["Price Relative"] - df["Price Relative"].shift()) / df["Price Relative"].shift() 26 | ) * 100 27 | 28 | fig = plt.figure(figsize=(14, 7)) 29 | ax1 = plt.subplot(2, 1, 1) 30 | ax1.plot(df1["Adj Close"]) 31 | ax1.set_title("Stock " + symbol1 + " Closing Price") 32 | ax1.set_ylabel("Price") 33 | ax1.legend(loc="best") 34 | 35 | ax2 = plt.subplot(2, 1, 2) 36 | ax2.plot( 37 | df["Percentage Change in Price Relative"], label="Price Relative", color="black" 38 | ) 39 | ax2.grid() 40 | ax2.legend(loc="best") 41 | ax2.set_ylabel("Price Relative") 42 | ax2.set_xlabel("Date") 43 | plt.show() 44 | 45 | # ## Candlestick with Price Relative 46 | from matplotlib import dates as mdates 47 | 48 | dfc = df1.copy() 49 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 50 | # dfc = dfc.dropna() 51 | dfc = dfc.reset_index() 52 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 53 | from mplfinance.original_flavor import candlestick_ohlc 54 | 55 | fig = plt.figure(figsize=(14, 7)) 56 | ax1 = plt.subplot(2, 1, 1) 57 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 58 | ax1.xaxis_date() 59 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 60 | ax1.grid(True, which="both") 61 | ax1.minorticks_on() 62 | ax1v = ax1.twinx() 63 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 64 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 65 | ax1v.axes.yaxis.set_ticklabels([]) 66 | ax1v.set_ylim(0, 3 * df1.Volume.max()) 67 | ax1.set_title("Stock " + symbol1 + " Closing Price") 68 | ax1.set_ylabel("Price") 69 | 70 | ax2 = plt.subplot(2, 1, 2) 71 | ax2.plot( 72 | df["Percentage Change in Price Relative"], label="Price Relative", color="black" 73 | ) 74 | ax2.grid() 75 | ax2.legend(loc="best") 76 | ax2.set_ylabel("Price Relative") 77 | ax2.set_xlabel("Date") 78 | plt.show() 79 | -------------------------------------------------------------------------------- /technical_indicators/realised_volatility.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import math 6 | import yfinance as yf 7 | import datetime as dt 8 | yf.pdr_override() 9 | 10 | # input 11 | symbol = "AAPL" 12 | start = dt.date.today() - dt.timedelta(days=365) 13 | end = dt.date.today() 14 | 15 | # Read data 16 | df = yf.download(symbol, start, end) 17 | 18 | n = 20 19 | rets = df["Adj Close"].pct_change().dropna() 20 | std = rets.rolling(n).std() 21 | 22 | historical_vol_annually = std * math.sqrt(252) 23 | df["RV"] = 100 * historical_vol_annually 24 | 25 | fig = plt.figure(figsize=(14, 7)) 26 | ax1 = plt.subplot(2, 1, 1) 27 | ax1.plot(df["Adj Close"]) 28 | ax1.set_title("Stock " + symbol + " Closing Price") 29 | ax1.set_ylabel("Price") 30 | 31 | ax2 = plt.subplot(2, 1, 2) 32 | ax2.plot(df["RV"], label="Realised Volatility") 33 | ax2.axhline(y=df["RV"].mean(), color="red") 34 | ax2.grid() 35 | ax2.set_ylabel("Realised Volatility") 36 | ax2.set_xlabel("Date") 37 | plt.show() 38 | 39 | # ## Candlestick with Historical Volatility 40 | from matplotlib import dates as mdates 41 | 42 | dfc = df.copy() 43 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 44 | # dfc = dfc.dropna() 45 | dfc = dfc.reset_index() 46 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 47 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 48 | from mplfinance.original_flavor import candlestick_ohlc 49 | 50 | fig = plt.figure(figsize=(14, 7)) 51 | ax1 = plt.subplot(2, 1, 1) 52 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 53 | ax1.xaxis_date() 54 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 55 | ax1.grid(True, which="both") 56 | ax1.minorticks_on() 57 | ax1v = ax1.twinx() 58 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 59 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 60 | ax1v.axes.yaxis.set_ticklabels([]) 61 | ax1v.set_ylim(0, 3 * df.Volume.max()) 62 | ax1.set_title("Stock " + symbol + " Closing Price") 63 | ax1.set_ylabel("Price") 64 | 65 | ax2 = plt.subplot(2, 1, 2) 66 | ax2.plot(df["RV"], label="Realised Volatility") 67 | ax2.axhline(y=df["RV"].mean(), color="red") 68 | ax2.grid() 69 | ax2.set_ylabel("Realised Volatility") 70 | ax2.set_xlabel("Date") 71 | plt.show() -------------------------------------------------------------------------------- /technical_indicators/smoothed_moving_average.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 7 18 | df["SMMA"] = pd.Series(df["Adj Close"].ewm(alpha=1 / float(n)).mean()) 19 | 20 | fig = plt.figure(figsize=(14, 7)) 21 | ax1 = plt.subplot(2, 1, 1) 22 | ax1.plot(df["Adj Close"]) 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | 26 | ax2 = plt.subplot(2, 1, 2) 27 | ax2.plot(df["SMMA"], label="Smoothed Moving Average", color="red") 28 | # ax2.axhline(y=0, color='blue', linestyle='--') 29 | ax2.grid() 30 | ax2.set_ylabel("Smoothed Moving Average") 31 | ax2.set_xlabel("Date") 32 | ax2.legend(loc="best") 33 | plt.show() 34 | 35 | # ## Candlestick with Smoothed Moving Average 36 | from matplotlib import dates as mdates 37 | 38 | dfc = df.copy() 39 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 40 | # dfc = dfc.dropna() 41 | dfc = dfc.reset_index() 42 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 43 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 44 | 45 | from mplfinance.original_flavor import candlestick_ohlc 46 | 47 | fig = plt.figure(figsize=(14, 7)) 48 | ax1 = plt.subplot(2, 1, 1) 49 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 50 | ax1.xaxis_date() 51 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 52 | ax1.grid(True, which="both") 53 | ax1.minorticks_on() 54 | ax1v = ax1.twinx() 55 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 56 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 57 | ax1v.axes.yaxis.set_ticklabels([]) 58 | ax1v.set_ylim(0, 3 * df.Volume.max()) 59 | ax1.set_title("Stock " + symbol + " Closing Price") 60 | ax1.set_ylabel("Price") 61 | 62 | ax2 = plt.subplot(2, 1, 2) 63 | ax2.plot(df["SMMA"], label="Smoothed Moving Average", color="red") 64 | # ax2.axhline(y=0, color='blue', linestyle='--') 65 | ax2.grid() 66 | ax2.set_ylabel("Smoothed Moving Average") 67 | ax2.set_xlabel("Date") 68 | ax2.legend(loc="best") 69 | plt.show() 70 | -------------------------------------------------------------------------------- /technical_indicators/standard_deviation_volatility.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365 * 2) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | df["STD"] = df["Adj Close"].rolling(10).std() 18 | 19 | fig = plt.figure(figsize=(14, 7)) 20 | ax1 = plt.subplot(2, 1, 1) 21 | ax1.plot(df["Adj Close"]) 22 | ax1.set_title("Stock " + symbol + " Closing Price") 23 | ax1.set_ylabel("Price") 24 | 25 | ax2 = plt.subplot(2, 1, 2) 26 | ax2.plot(df["STD"], label="Standard Deviation Volatility") 27 | ax2.axhline(y=df["STD"].mean(), color="red") 28 | ax2.grid() 29 | ax2.set_ylabel("Standard Deviation Volatility") 30 | ax2.set_xlabel("Date") 31 | plt.show() 32 | 33 | # ## Candlestick with Standard Deviation Volatility 34 | from matplotlib import dates as mdates 35 | 36 | dfc = df.copy() 37 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 38 | # dfc = dfc.dropna() 39 | dfc = dfc.reset_index() 40 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 41 | 42 | from mplfinance.original_flavor import candlestick_ohlc 43 | 44 | fig = plt.figure(figsize=(14, 7)) 45 | ax1 = plt.subplot(2, 1, 1) 46 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 47 | ax1.xaxis_date() 48 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 49 | ax1.grid(True, which="both") 50 | ax1.minorticks_on() 51 | ax1v = ax1.twinx() 52 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 53 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 54 | ax1v.axes.yaxis.set_ticklabels([]) 55 | ax1v.set_ylim(0, 3 * df.Volume.max()) 56 | ax1.set_title("Stock " + symbol + " Closing Price") 57 | ax1.set_ylabel("Price") 58 | 59 | ax2 = plt.subplot(2, 1, 2) 60 | ax2.plot(df["STD"], label="Standard Deviation Volatility") 61 | ax2.axhline(y=df["STD"].mean(), color="red") 62 | ax2.grid() 63 | ax2.set_ylabel("Standard Deviation Volatility") 64 | ax2.set_xlabel("Date") 65 | plt.show() 66 | -------------------------------------------------------------------------------- /technical_indicators/variance_indicator.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | 9 | # input 10 | symbol = "AAPL" 11 | start = dt.date.today() - dt.timedelta(days=365) 12 | end = dt.date.today() 13 | 14 | # Read data 15 | df = yf.download(symbol, start, end) 16 | 17 | n = 14 18 | df["Variance"] = df["Adj Close"].rolling(n).var() 19 | 20 | fig = plt.figure(figsize=(14, 7)) 21 | ax1 = plt.subplot(2, 1, 1) 22 | ax1.plot(df["Adj Close"]) 23 | ax1.set_title("Stock " + symbol + " Closing Price") 24 | ax1.set_ylabel("Price") 25 | ax1.legend(loc="best") 26 | 27 | ax2 = plt.subplot(2, 1, 2) 28 | ax2.plot(df["Variance"], label="Variance") 29 | ax2.axhline(y=1, color="black") 30 | ax2.grid() 31 | ax2.legend(loc="best") 32 | ax2.set_ylabel("Variance") 33 | ax2.set_xlabel("Date") 34 | plt.show() 35 | 36 | # ## Candlestick with Variance 37 | from matplotlib import dates as mdates 38 | 39 | dfc = df.copy() 40 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 41 | # dfc = dfc.dropna() 42 | dfc = dfc.reset_index() 43 | dfc["Date"] = pd.to_datetime(dfc["Date"]) 44 | dfc["Date"] = dfc["Date"].apply(mdates.date2num) 45 | 46 | from mplfinance.original_flavor import candlestick_ohlc 47 | 48 | fig = plt.figure(figsize=(14, 7)) 49 | ax1 = plt.subplot(2, 1, 1) 50 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 51 | ax1.xaxis_date() 52 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 53 | ax1.grid(True, which="both") 54 | ax1.minorticks_on() 55 | ax1v = ax1.twinx() 56 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 57 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 58 | ax1v.axes.yaxis.set_ticklabels([]) 59 | ax1v.set_ylim(0, 3 * df.Volume.max()) 60 | ax1.set_title("Stock " + symbol + " Closing Price") 61 | ax1.set_ylabel("Price") 62 | 63 | ax2 = plt.subplot(2, 1, 2) 64 | ax2.plot(df["Variance"], label="Variance") 65 | ax2.axhline(y=1, color="black") 66 | ax2.grid() 67 | ax2.legend(loc="best") 68 | ax2.set_ylabel("Variance") 69 | ax2.set_xlabel("Date") 70 | plt.show() 71 | -------------------------------------------------------------------------------- /technical_indicators/volume_weighted_moving_average.py: -------------------------------------------------------------------------------- 1 | # Import dependencies 2 | import numpy as np 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import yfinance as yf 6 | import datetime as dt 7 | yf.pdr_override() 8 | import sys 9 | import os 10 | parent_dir = os.path.dirname(os.getcwd()) 11 | sys.path.append(parent_dir) 12 | import ta_functions as ta 13 | 14 | # input 15 | symbol = "AAPL" 16 | start = dt.date.today() - dt.timedelta(days=365) 17 | end = dt.date.today() 18 | 19 | # Read data 20 | df = yf.download(symbol, start, end) 21 | 22 | df["SMA"] = ta.SMA(df["Adj Close"], timeperiod=3) 23 | df["VWMA"] = ( 24 | (df["Adj Close"] * df["Volume"]) 25 | + (df["Adj Close"].shift(1) * df["Volume"].shift(1)) 26 | + (df["Adj Close"].shift(2) * df["Volume"].shift(2)) 27 | ) / (df["Volume"].rolling(3).sum()) 28 | 29 | def VWMA(close, volume, n): 30 | cv = pd.Series(close.shift(n) * volume.shift(n)) 31 | tv = volume.rolling(n).sum() 32 | vwma = cv / tv 33 | return vwma 34 | 35 | VWMA(df["Adj Close"], df["Volume"], 3) 36 | 37 | plt.figure(figsize=(14, 7)) 38 | plt.plot(df["Adj Close"]) 39 | plt.plot(df["VWMA"], label="Volume Weighted Moving Average") 40 | plt.plot(df["SMA"], label="Simple Moving Average") 41 | plt.legend(loc="best") 42 | plt.title("Stock of Midpoint Method") 43 | plt.xlabel("Date") 44 | plt.ylabel("Price") 45 | plt.show() 46 | 47 | # ## Candlestick with VWMA 48 | from matplotlib import dates as mdates 49 | 50 | dfc = df.copy() 51 | dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"] 52 | # dfc = dfc.dropna() 53 | dfc = dfc.reset_index() 54 | dfc["Date"] = mdates.date2num(dfc["Date"].tolist()) 55 | 56 | from mplfinance.original_flavor import candlestick_ohlc 57 | 58 | fig = plt.figure(figsize=(14, 7)) 59 | ax1 = plt.subplot(2, 1, 1) 60 | candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0) 61 | ax1.plot(df["VWMA"], label="Volume Weighted Moving Average") 62 | ax1.plot(df["SMA"], label="Simple Moving Average") 63 | ax1.set_title("Stock " + symbol + " Closing Price") 64 | ax1.set_ylabel("Price") 65 | ax1.xaxis_date() 66 | ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y")) 67 | ax1.grid(True, which="both") 68 | ax1.minorticks_on() 69 | ax1v = ax1.twinx() 70 | colors = dfc.VolumePositive.map({True: "g", False: "r"}) 71 | ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4) 72 | ax1v.axes.yaxis.set_ticklabels([]) 73 | ax1v.set_ylim(0, 3 * df.Volume.max()) 74 | ax1.set_title("Stock " + symbol + " Closing Price") 75 | ax1.set_ylabel("Price") 76 | ax1.legend(loc="best") 77 | plt.show() 78 | -------------------------------------------------------------------------------- /tickers.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import requests 3 | 4 | def tickers_sp500(): 5 | url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies' 6 | html = requests.get(url).text 7 | df = pd.read_html(html, header=0)[0] 8 | tickers = df['Symbol'].tolist() 9 | return tickers 10 | 11 | def tickers_nasdaq(): 12 | url = 'http://www.nasdaqtrader.com/dynamic/symdir/nasdaqlisted.txt' 13 | data = requests.get(url).text 14 | # The data is '|' separated and last two lines are not needed 15 | lines = data.split('\n') 16 | # Convert to DataFrame 17 | df = pd.DataFrame([sub.split("|") for sub in lines[1:-2]], columns=lines[0].split("|")) 18 | return df['Symbol'].tolist() 19 | 20 | def tickers_nyse(): 21 | url = 'http://www.nasdaqtrader.com/dynamic/symdir/otherlisted.txt' 22 | data = requests.get(url).text 23 | # The data is '|' separated and the last two lines are not needed 24 | lines = data.split('\n') 25 | # Convert to DataFrame 26 | df = pd.DataFrame([sub.split("|") for sub in lines[1:-2]], columns=lines[0].split("|")) 27 | # Filter out only NYSE symbols 28 | nyse_df = df[df['Exchange'] == 'N'] 29 | return nyse_df['ACT Symbol'].tolist() 30 | 31 | def tickers_dow(): 32 | url = 'https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average' 33 | html = requests.get(url).text 34 | df = pd.read_html(html, header=0, attrs = {'id': 'constituents'})[0] 35 | tickers = df['Symbol'].tolist() 36 | return tickers 37 | 38 | def tickers_amex(): 39 | url = 'http://www.nasdaqtrader.com/dynamic/symdir/otherlisted.txt' 40 | data = requests.get(url).text 41 | # The data is '|' separated and the last two lines are not needed 42 | lines = data.split('\n') 43 | # Convert to DataFrame 44 | df = pd.DataFrame([sub.split("|") for sub in lines[1:-2]], columns=lines[0].split("|")) 45 | # Filter out only AMEX symbols 46 | amex_df = df[df['Exchange'] == 'A'] 47 | return amex_df['ACT Symbol'].tolist() --------------------------------------------------------------------------------