Skip to content

Instantly share code, notes, and snippets.

@mcohen01
Created January 23, 2018 16:56
Show Gist options
  • Save mcohen01/8a04ab1d9ab96b571320b84775e7f95b to your computer and use it in GitHub Desktop.
Save mcohen01/8a04ab1d9ab96b571320b84775e7f95b to your computer and use it in GitHub Desktop.
from collections import Counter, defaultdict
from pandas import DataFrame, Series
import json
import seaborn
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter, MaxNLocator
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
fontsize = 14
fig = plt.figure(figsize=(12,8))
fig.suptitle('Revenue Growth', fontsize=fontsize)
quarters = [18, 20, 24, 28, 33, 38, 44, 51, 59, 65, 72, 82, 87, 96, 101]
guidance = 105
projected = 112
labels = [
'2014Q2', '2014Q3', '2015Q1', '2015Q3',
'2016Q1', '2016Q3', '2017Q1', '2017Q3',
'2018Q1', '2018Q3', '2019Q1', '2019Q3'
]
periods = len(quarters) + 3
active_quarters = len(quarters) - 4
growth = (Series(quarters) / Series(quarters).shift(4) - 1) * 100
def plot_growth():
return growth.plot(kind='line',
label='Actual',
alpha=.8,
fontsize=fontsize,
xlim=[0, periods],
ylim=[20, 100])
def plot_trend_line():
X = np.arange(active_quarters).reshape(-1, 1)
y = growth.dropna().values
model = LinearRegression()
model.fit(X, y)
nans = growth.values.tolist()[0:4]
x = nans + list(range(4, periods + 6))
X_test = [x for x in range(0, periods + 2)]
X_test = np.array(X_test).reshape(-1, 1)
y_test = model.predict(X_test).tolist()
y = nans + y_test
plt.plot(x, y,
alpha=.4,
label='Trend',
color='purple')
def plot_next_quarter(value, title, color):
most_recent_revenue = growth.values.tolist()[-1]
indices = growth.index.tolist()
nans = growth.values.tolist()[0:4]
nas = np.repeat(nans[0], len(indices)).tolist()
projection = (value / quarters[-4] - 1) * 100
gx = indices + [indices[-1], indices[-1] + 1]
gy = nas + [most_recent_revenue, projection]
plt.plot(gx, gy, label=title, alpha=.4, color=color)
ax = plot_growth()
plot_trend_line()
plot_next_quarter(guidance, 'Guidance', '#fc0000')
plot_next_quarter(projected, 'Projected', '#3b9626')
## aesthetics
plt.xticks(rotation=45, fontsize=fontsize)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x,y: labels[int(y)]))
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_ylabel('Year Over Year (Percent)', fontsize=fontsize)
plt.legend(prop={'size': fontsize})
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment