-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
86 lines (75 loc) · 2.99 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Python modules
csv: Perform operations such as extracting strings from a CSV file downloaded with stooq's API
datetime: Get a date for getting stock prices with stooq API
os: Get env file and delete csv and image files
join, dirname: Get env file
pandas: Read and sort data in a CSV file
mplfinance: Generate a chart image of stock price
pandas_datareader.stooq: API client for stooq
dotenv: Get environment variants
dateutil.relativedelta: Calculate the period of time for the stock price to be acquired
Internal module
slack: Notification Class to configure the settings for the Slack API
"""
import csv
import datetime
import os
from os.path import join, dirname
import pandas as pd
import mplfinance as mpf
import pandas_datareader.stooq as stooq
from dotenv import load_dotenv
from dateutil.relativedelta import relativedelta
from notifiers import slack
from message import message
def generate_stock_chart_image():
"""
Generate a six-month stock chart image with mplfinance
"""
dataframe = pd.read_csv(f"/tmp/{str(today)}.csv", index_col=0, parse_dates=True)
# The return value `Date` from stooq is sorted by asc, so change it to desc for plot
dataframe = dataframe.sort_values('Date')
mpf.plot(dataframe, type='candle', figratio=(12,4),
volume=True, mav=(5, 25), style='yahoo',
savefig=f"/tmp/{str(today)}.png")
def generate_csv_with_datareader():
"""
Generate a csv file of OHLCV with date with stooq API
"""
start_date = today - relativedelta(months=3)
stooq_reader = stooq.StooqDailyReader(stock_code, start=start_date, end=today)
stooq_reader.read().to_csv(f"/tmp/{str(today)}.csv")
# pylint: disable=W0613
# When main() is executed in CloudFunction, (event,context) are automatically specified as arguments
# https://cloud.google.com/functions/docs/writing/background?hl=ja#function_parameters
def main(event, context):
"""
The main function that will be executed when this Python file is executed
"""
generate_csv_with_datareader()
generate_stock_chart_image()
with open(f"/tmp/{str(today)}.csv", 'r', encoding="utf-8") as file:
# Skip header row
reader = csv.reader(file)
header = next(reader)
for i, row in enumerate(csv.DictReader(file, header)):
# The most recent data to Slack notification
if i == 0:
ohlcv = row
elif i == 1:
# Previous day's data for compareing the most recent data
prev_ohlcv = row
# Send to Slack notifiaction
text = message.Message(today, ohlcv, prev_ohlcv).content
slack.Slack(today, text).post()
# Load env variants
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
stock_code = os.environ.get("STOCK_CODE")
# Get today's date for getting the stock price and csv&image filename
today = datetime.date.today()
# tmp directory is present by default on Cloud Functions, so guard it
if not os.path.isdir('/tmp'):
os.mkdir('/tmp')
FILENAME = '%s.csv' % str(today)