Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
QuantConnect
GitHub Repository: QuantConnect/Research
Path: blob/master/Documentation/Python/Stock-Picking-With-Fundamental-Data.ipynb
629 views
Kernel: Python 3

QuantConnect Logo


Stock Picking With Fundamental Data

An example of selecting stocks in a sector based on their relative PE ratios.

First we import the matplotlib library to assist with plotting.

import matplotlib.pyplot as plt

We create our QuantBook object.

qb = QuantBook()

Next, we create a list of symbol objects for several large airline companies.

tickers = [ "ALK", # Alaska Air Group, Inc. "AAL", # American Airlines Group, Inc. "DAL", # Delta Air Lines, Inc. "LUV", # Southwest Airlines Company "UAL", # United Air Lines "ALGT", # Allegiant Travel Company "SKYW" # SkyWest, Inc. ] symbols = [qb.AddEquity(ticker, Resolution.Daily).Symbol for ticker in tickers]

We get the PE ratios of the symbols throughout 2014.

pe_ratios = qb.GetFundamental(symbols, "ValuationRatios.PERatio", datetime(2014, 1, 1), datetime(2015, 1, 1)) pe_ratios

Now we plot the PE ratios across time.

pe_ratios.plot(figsize=(16, 8), title="PE Ratio Over Time") plt.xlabel("Time") plt.ylabel("PE Ratio") plt.show()

We want to select the symbols with the highest and lowest average PE ratios. First, we call mean() on the DataFrame and then sort the values with sort_values().

sorted_by_mean_pe = pe_ratios.mean().sort_values() sorted_by_mean_pe

We select the symbols with the highest and lowest average PE ratios by selecting the first and last element in the series index.

highest_avg_pe = qb.Symbol(sorted_by_mean_pe.index[-1]) lowest_avg_pe = qb.Symbol(sorted_by_mean_pe.index[0])

We now gather the historical closing prices for the securities we found to have the highest and lowest PE ratios.

history = qb.History([highest_avg_pe, lowest_avg_pe], datetime(2009, 1, 1), datetime(2015, 1, 1), Resolution.Daily).close.unstack(level=0) history

Lastly, we plot the returns generated by investing in these securities from 2009 to 2015.

returns_over_time = ((history.pct_change()[1:] + 1).cumprod() - 1) returns_over_time.plot(figsize=(16, 8), title="Returns Over Time") plt.ylabel("Return") plt.show()