Skip to content

๐Ÿ’ช๐Ÿ“ˆ Powerfolio! is a stock screener and portfolio analysis. Backtest buy-and-hold vs. trading on RSI. Build a portfolio using efficient frontier and map hierarchical clustering results.

illyanyc/powerfolio

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Creators:


Table of Contents


About

What is Powerfolio!?

Powerfolio! is screener, portfolio builder and analyzer for S&P 500 securities. Powerfolio! implements fundamental analysis, technical analysis and traditional portfolio analysis methods such as Sharpe Ratio and Efficient Frontier in order to allow you to select the best power-folio for your financial needs.



Theory

Fundamental Analysis

P/E - Price to Earnings Ratio

The price-to-earnings ratio (P/E ratio) is a method used to value a company by comparing the share price to the Earnings per Share (EPS). The price-to-earnings ratio is used a multiplier for company earnings. High P/E ratio means that the stock value is high compared to corporate earnings, and that the company may be overvalues, and vis-versa.


EPS - Earnings per Share

Earnings per share (EPS) is generally calculated by dividing company's profit by the outstanding shares of its common stock. EPS is a general way for a company to report it's profitability adjusted to it's marker capitalization. It is one of the general ways to evaluate corporate earnings.


Dividend

A dividend is the distribution of a company's earnings to its shareholders. Dividends are paid directly to shareholders of the company on periodic basis and the amount is determined by the board of directors.

Technical Analysis

RSI - Relative Strength Index

Relative Strength Index, better known as RSI is a technical indicator used to determine is a particular security is overbought or oversold. It measures the magnitude of price change of the asset; and is an oscillator that moves between 0 and 100. RSI was developed by J. Welles Wilder Jr. in 1978.


RSI indicator, indicates that a stock is overbought then the indicator crosses above 70%, and oversold when the indicator drops below 30%. Additionally, a trader may want to enter a position when RSI crosses above 30%, indicating bullish reversal, and exit a position when RSI drops below 70%, indicating bearish reversal.


MACD

Moving average convergence divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages of a securityโ€™s price. The MACD is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA.


Exponential moving average is a moving average that places a greater weight to most recent data points and less to the older data points. In finance, EMA reacts more significantly to recent price changes than a [simple moving average (SMA)](, which applies an equal weight to all observations in the period. In statistics, a moving average (MA), also known as simple moving average (SMA) in finance, is a calculation used to analyze data points by creating a series of averages of different subsets of the full data set.


MACD is used by traders to indicate bullish and bearish reversals when the EMA trendlines cross.



Traditional Analysis

Sharpe Ratio

Sharpe Ratio allows user understand the return of an investment compared to the risk of the investment. Sharpe Ratio is the average return earned above the risk-free rate compared to volitility of the investment. Volatility is a measure of the price fluctuations of an asset or portfolio. The Sharpe ratio was developed by Nobel laureate William F. Sharpe in 1966.


where:

  • Rp = return of portfolio
  • Rf = risk-free rate
  • ฯƒp = standard deviation of the portfolioโ€™s excess return

Subtracting the risk-free rate from the retuns allows the user to isolate the profits from the cost of money. The risk-free rate of return usually identified by the 10-year U.S. Government Bond Yield, although in some instances risk-free rate may be identified as passive returns from investment in an index such as S&P 500, as that kind of investment may be considered the true cost of money.

Greater Sharpe Ratio is accosiated with a greater rist-adjusted return.

Efficient Frontier

The Efficient Frontier is the collection of portfolios optimized for the highest expected return normalized to a specified level of risk. Portfolios that lie below the efficient frontier are sub-optimal because they do not provide enough return for the level of risk. Portfolios that cluster to the right of the efficient frontier are sub-optimal because they have a higher level of risk for the defined rate of return.

The plot was taken from TheWealthyFinn.com:


Harry Markowitz has introduced the Efficient Frontier in 1952 and made it the cornerstone of modern portfolio theory (MPT).


Hierarchical Clustering

Hierarchial Rist Clustering utilizes hierarchial risk parity ...

The plot was taken from QuantPedia.com:




Installation

Anaconda

Anaconda is a package manager, an environment manager, a Python/R data science distribution, and a collection of over open-source packages.

Installation

Anaconda Installation


Jupyter

Powerfolio! is contained within a Jupyter Notebook. Project Jupyter exists to develop open-source software, open-standards, and services for interactive computing across dozens of programming languages. [Jupyter Project Overview]

Installation

pip install jupyterlab

pandas

pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. [Pandas Overview]

Installation

conda install pandas

NumPy

The fundamental package for scientific computing with Python [Numpy Overview]

Installation

conda install numpy

Scipy

SciPy is a Python-based ecosystem of open-source software for mathematics, science, and engineering. [Scipy Overview]

Installation

python -m pip install --user scipy ipython sympy nose

matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. [matplotlib Overview]

Installation

conda install matplotlib

Panel

A high-level app and dashboarding solution for Python [Holoviz Panel Overview]

Installation

conda install -c pyviz panel

Plotly

Interactive charts and maps for Python, R, and JavaScript. [Plotly Overview]

Installation

Plotly must be installed inside the environment where it is meant to be used.

conda install -c plotly plotly

ipywidgets and Jupyter Lab extensions must be added prior to Plotly's use

conda install "notebook>=5.3" "ipywidgets>=7.5"
jupyter labextension install jupyterlab-plotly@4.14.3
jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4.14.3

hvPlot

A high-level plotting API for the PyData ecosystem built on HoloViews. [hvPLot Overview]

Installation

conda install -c pyviz hvplot

For Jupyter Notebook support:

jupyter labextension install @pyviz/jupyterlab_pyviz

Seaborn

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. [Seaborn Overview]

Installation

conda install seaborn

Matplotlib

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. [Matplotlib Overview]

Installation

conda install matplotlib

APIs

Alpaca Trade API

Alpaca is a technology company headquartered in Silicon Valley that builds commission-free stock trading API (Brokerage services are provided by Alpaca Securities LLC, member FINRA/SIPC) [Alpaca Trade API Overview].

A user API key is required.


Installation

pip install alpaca-trade-api

Quandl

The premier source for financial, economic and alternative datasets, serving investment professionals. Nasdaqโ€™s Quandl platform is used by analysts from the worldโ€™s top hedge funds, asset managers and investment banks. [Quandl API Overview].

A user API key is required.


Installation

conda install -c anaconda quandl

FinnHub

Real-Time RESTful APIs and Websocket for Stocks, Currencies, and Crypto. [FinnHub API Overview]

A user API key is required.

Installation

pip install finnhub-python


Using the Dashboard

Data Connections

Data connections in the Powerfolio! Dashboard are provided by Alpaca, Quandl, and Finnhub.

  • The securities for analysis are presented in a .csv file store locally.
  • Alpaca Trade API provides marker High, Low, Open, Close and Volume data. An API key is required. The API calls are performed live.
  • Quandl API provides risk-free-rate data for Sharpe Ratio calculation
  • FinnHub provides fundamental data. The data is stored locally in a .csv sheet and needs to be updated periodically.

Securities tickers

Securities tickers are stored locally and can be replaced on demand. The column with tickers within the .csv file must be named "Symbol"

The data from the default .csv contains S&P 500 tickers in the following format:

Symbol Security GICS Sector GICS Sub-Industry Headquarters Location Date first added CIK Founded
11 A Agilent Technologies Health Care Health Care Equipment Santa Clara, California 6/5/2000 1090872 1999
28 AAL American Airlines Group Industrials Airlines Fort Worth, Texas 3/23/2015 6201 1934
8 AAP Advance Auto Parts Consumer Discretionary Automotive Retail Raleigh, North Carolina 7/9/2015 1158449 1932
45 AAPL Apple Inc. Information Technology Technology Hardware, Storage & Peripherals Cupertino, California 11/30/1982 320193 1977
2 ABBV AbbVie Inc. Health Care Pharmaceuticals North Chicago, Illinois 12/31/2012 1551152 2013 (1888)

API keys

The user needs to store the API keys locally and reference them in the dashboard.ipynb before running the application. In order to reference the API keys enter the filepath of your .env file in code cell 3 of the notebook:

In order to properly load API keys using dotenv library the key names in the file must be:

API Key Type .env variable
Alpaca Trade API key ALPACA_API_KEY
Alpaca Trade API secret key ALPACA_SECRET_KEY
FinnHub API key FINNHUB_API_KEY

FinnHub Data Refresh

FinnHub data is stored locally in a .csv and can be refreshed on the Welcome page of the Dashboard:


FinnHub generated fundamental data is stored in a fundamental_data.csv file, the path of which can be changed on-demand:



Computational Methods

Fundamental and Technical Portfolio Builder

Fundamental/Technical Portfolio Builder tab contains the tools necessary to build a model portfolio, or shall we say, Powerfolio!

Fundamental model portfolio builder scans securities provided in the locally stored .csv file and returns securities that fit the user input criteria.

The selection criteria for the model portfolio are:

Start date

End date

P/E range

EPS range

Dividend range

Pressing the Apply selection button refreshes the Filtered Stocks Dataframe and plots the model fundamental portfolio. Filtered Stocks Dataframe is sortable and interactive.

Pressing Refresh button clears the Filtered Stocks Dataframe.


Fundamental Portfolio Screener/Builder GUI:


The model fundamental portfolio is displayed on the right side of the Dashboard. Fundamental Portfolio Screener/Builder result:


RSI Trader

Powerfolio! utilizes Relative Strength Index (RSI) in order to build a model-based portfolio. The strategy is based solely on โ€œcrossoversโ€ signals derived from the RSI values. The strategy will buy/close a position while crossing upward the oversold level and will trigger a sell/close signal while crossing the overbought signal downward. Generally an RSI value of 30 is considered oversold and RSI value of 70 is considered overbought. However the user can select different values for the oversold/overbought levels. Typically RSI is used while scanning divergences but we havenโ€™t explored this path yet.

RSI Trader GUI allows user to enter the lower and upper RSI bounds as well as the number of days for the moving average.

The selection criteria for the model portfolio are:

Min

Max

RSI Lenght


RSI Builder GUI:


The resulting plot shows the RSI Trader simulated portfolio in addition to model fundamental portfolio. This allows the user to compare the portfolios on one plot. The RSI Trader GUI allows user to change input selection and generate additional portfolios in order to best compare different trade entry and exit points.

RSI Builder result:


Technical Analysis Viewer

Technical Analysis tab contains a tool that allows the user to view technical indicators for each of the securities in the Fundamental/Technical Portfolio that was generated on the previous tab.

It provides the user with:

RSI

Price

Volume

MACD

The user can select the tickers for the securities within their portfolio in the drop-down menu on the top left side of the screen and pressing the View Technical Indicators button.

Technical Analysis GUI and result:


Efficient Frontier Results

Efficient Frontier tab allows user to model an efficient portfolio and compare it to the Fundamental Model Portfolio that the user hasa generated previously.

Efficient Frontier GUI and results:

Hierarchical Clustering Results

...

Hierarchical Clustering result:




About

๐Ÿ’ช๐Ÿ“ˆ Powerfolio! is a stock screener and portfolio analysis. Backtest buy-and-hold vs. trading on RSI. Build a portfolio using efficient frontier and map hierarchical clustering results.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •