Skip to content

Instantly share code, notes, and snippets.

@marcosan93
Created September 23, 2021 18:17
Show Gist options
  • Select an option

  • Save marcosan93/65b7e5d8b89fc257ab94c793fd9c042c to your computer and use it in GitHub Desktop.

Select an option

Save marcosan93/65b7e5d8b89fc257ab94c793fd9c042c to your computer and use it in GitHub Desktop.
def getData(ticker, window, ma_period):
"""
Grabs price data from a given ticker. Retrieves prices based on the given time window; from now
to N days ago. Sets the moving average period for prediction. Returns a preprocessed DF
formatted for FB Prophet.
"""
# Time periods
now = datetime.now()
# How far back to retrieve tweets
ago = now - timedelta(days=window)
# Designating the Ticker
crypto = yf.Ticker(ticker)
# Getting price history
df = crypto.history(start=ago.strftime("%Y-%m-%d"), end=now.strftime("%Y-%m-%d"), interval="1d")
# Handling missing data from yahoo finance
df = df.reindex(
[df.index.min()+pd.offsets.Day(i) for i in range(df.shape[0])],
fill_value=None
).fillna(method='ffill')
# Getting the N Day Moving Average and rounding the values
df['MA'] = df[['Open']].rolling(window=ma_period).mean().apply(lambda x: round(x, 2))
# Dropping the NaNs
df.dropna(inplace=True)
# Formatted for FB Prophet
df = df.reset_index().rename(columns={"Date": "ds", "MA": "y"})
return df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment