Last active
March 24, 2021 16:01
-
-
Save hhsm95/a6ac3f853cf218c6ba0aa5b1430c209a to your computer and use it in GitHub Desktop.
Check anual increment of stocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yfinance as yf | |
import pandas as pd | |
def calculate(symbol: str) -> dict: | |
stocks = yf.Ticker(symbol) | |
data = stocks.history(period="5y") | |
data = data[["Close"]] | |
data.reset_index(inplace=True) | |
data['month'] = data["Date"].dt.month | |
data['year'] = data["Date"].dt.year | |
data.rename(columns = {'Close' : 'Price', 'day' : 'Day', 'month' : 'Month', 'year' : 'Year'}, inplace = True) | |
data.drop(columns=["Date"], inplace=True) | |
data = data[data["Year"] != 2021] | |
per_year = data.groupby('Year')['Price'].agg(lambda x: x.pct_change().mean() * 365) | |
per_month = data.groupby('Month')['Price'].agg(lambda x: x.pct_change().mean() * (365 / 12)) | |
per_year_month = data.groupby(['Year', 'Month'])['Price'].agg(lambda x: x.pct_change().mean() * (365 / 12)) | |
per_year_avg = per_year.mean() | |
per_month_avg = per_month.mean() | |
per_year_month_avg = per_year_month.mean() | |
per_year["avg"] = per_year_avg | |
per_month["avg"] = per_month_avg | |
per_year_month["avg"] = per_year_month_avg | |
return { | |
"per_year": per_year, "per_month": per_month, "per_year_month": per_year_month, | |
} | |
def main(): | |
symbols = [ | |
"COST", | |
] | |
results = {} | |
for symbol in symbols: | |
data = calculate(symbol) | |
print(symbol) | |
results[symbol] = data | |
tables = ["per_year", "per_month", "per_year_month"] | |
for row in tables: | |
data = {} | |
for symbol in symbols: | |
data[symbol] = results[symbol][row] | |
print(data) | |
df = pd.DataFrame(data) | |
df = df.transpose() | |
df.to_csv(f"stocks_{row}.csv") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment