forked from dataman-git/codes_for_articles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock.py
110 lines (69 loc) · 2.45 KB
/
stock.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
87
88
89
90
91
92
93
94
95
96
97
98
99
# !pip install streamlit
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf # https://pypi.org/project/yfinance/
from ta.volatility import BollingerBands
from ta.trend import MACD
from ta.momentum import RSIIndicator
##################
# Set up sidebar #
##################
# Add in location to select image.
option = st.sidebar.selectbox('Select one symbol', ( 'AAPL', 'MSFT',"SPY",'WMT'))
import datetime
today = datetime.date.today()
before = today - datetime.timedelta(days=700)
start_date = st.sidebar.date_input('Start date', before)
end_date = st.sidebar.date_input('End date', today)
if start_date < end_date:
st.sidebar.success('Start date: `%s`\n\nEnd date:`%s`' % (start_date, end_date))
else:
st.sidebar.error('Error: End date must fall after start date.')
##############
# Stock data #
##############
# https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html#momentum-indicators
df = yf.download(option,start= start_date,end= end_date, progress=False)
indicator_bb = BollingerBands(df['Close'])
bb = df
bb['bb_h'] = indicator_bb.bollinger_hband()
bb['bb_l'] = indicator_bb.bollinger_lband()
bb = bb[['Close','bb_h','bb_l']]
macd = MACD(df['Close']).macd()
rsi = RSIIndicator(df['Close']).rsi()
###################
# Set up main app #
###################
st.write('Stock Bollinger Bands')
st.line_chart(bb)
progress_bar = st.progress(0)
# https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py
st.write('Stock Moving Average Convergence Divergence (MACD)')
st.area_chart(macd)
st.write('Stock RSI ')
st.line_chart(rsi)
st.write('Recent data ')
st.dataframe(df.tail(10))
################
# Download csv #
################
import base64
from io import BytesIO
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
processed_data = output.getvalue()
return processed_data
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
val = to_excel(df)
b64 = base64.b64encode(val) # val looks like b'...'
return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="download.xlsx">Download excel file</a>' # decode b'abc' => abc
st.markdown(get_table_download_link(df), unsafe_allow_html=True)