156 lines
6.9 KiB
Python
156 lines
6.9 KiB
Python
from datetime import date, datetime
|
|
import streamlit as st
|
|
import yfinance as yf
|
|
import plotly.express as px
|
|
from webpages import code_editor as ce
|
|
|
|
def pythonx_finance():
|
|
|
|
st.title("Lesson 3: Collecting Stock Data Through API")
|
|
st.header(":one: What is API")
|
|
st.markdown(
|
|
"""
|
|
API stands for **Application Programming Interface**. It is a set of protocols, routines, and tools for building software and applications. An API defines the way by which an external client can request services and access data from an operating system, library, or application. It provides a communication interface for two or more systems to exchange data and interact with each other. APIs are commonly used to enable developers to create new applications and services that integrate with existing systems or to extract data from websites and services for use in other applications.
|
|
""")
|
|
st.image("./images/lesson3-api.png")
|
|
|
|
st.header(":two: Using yfinance Library(Package) to Extract Stock Data")
|
|
st.markdown("""
|
|
[yfinance](https://github.com/ranaroussi/yfinance) is a Python library that allows you to easily download and analyze financial data from Yahoo Finance.
|
|
|
|
It provides a convenient way to access stock market data and perform various operations with it such as
|
|
- retrieving historical data
|
|
- getting real-time data
|
|
- obtaining financial ratios and metrics, and more.
|
|
|
|
It provides a simple and efficient way to work with stock data in Python, without the need to manually scrape data from websites or manually download data from financial sources.
|
|
""")
|
|
|
|
st.header(":three: Application Demo")
|
|
# print text formatted by HTML
|
|
|
|
# Display a styled title in HTML format
|
|
st.markdown(
|
|
"<h1 style='text-align:center; color:red;'> Sample Stock Price App. </h1>",
|
|
unsafe_allow_html=True)
|
|
st.write("Reference: [yfinance Package](https://aroussi.com/post/python-yahoo-finance)")
|
|
# Brief description of the app's purpose
|
|
st.subheader('Build an online application for tracing stock price history')
|
|
|
|
# Display a subheading in Markdown
|
|
st.header("Check Stock History")
|
|
|
|
# Define a list of popular stock symbols
|
|
stock_list = ['MSFT', 'AAPL', 'AMZN', 'GOOGL']
|
|
|
|
# Create a dropdown menu for selecting a stock
|
|
stock_name = st.selectbox('Select a stock to check', options=stock_list)
|
|
|
|
# Input for selecting the start date of stock data, default is January 1, 2024
|
|
start_date = st.date_input('Start Date', datetime(2024, 1, 1))
|
|
# Input for selecting the end date of stock data, default is today
|
|
end_date = st.date_input("End Date")
|
|
|
|
# Store today's date for validation
|
|
today = date.today()
|
|
|
|
# Action to retrieve stock data when the 'Submit' button is clicked
|
|
if st.button('Submit'):
|
|
# Check if selected dates are valid (not in the future)
|
|
if (start_date > today) or (end_date > today) or (start_date > end_date):
|
|
st.warning("Please select a valid date period.")
|
|
else:
|
|
# Get data for the selected stock
|
|
stock = yf.Ticker(stock_name)
|
|
# Retrieve historical data between selected dates
|
|
stock_history = stock.history(start=start_date, end=end_date)
|
|
st.write("**Raw Data of Stock Price**")
|
|
# Display raw data of stock price
|
|
st.dataframe(stock_history)
|
|
# Plot stock price data (Open, High, Low, Close) using Plotly
|
|
fig = px.line(stock_history,
|
|
# use the index of the stock_history data as x-axis.
|
|
x=stock_history.index,
|
|
# plot data of columns ['Open', 'High', 'Low', 'Close']
|
|
y=['Open', 'High', 'Low', 'Close'],
|
|
title=stock_name + " Stock Price",
|
|
labels={
|
|
"value": "Stock Price ($)",
|
|
"variable": "Price Type"
|
|
})
|
|
# Display the generated plot in the app
|
|
st.write(fig)
|
|
# Display a success message upon completion
|
|
st.success('Done')
|
|
|
|
|
|
|
|
source_code = """
|
|
|
|
from datetime import date, datetime
|
|
import streamlit as st
|
|
import yfinance as yf
|
|
import plotly.express as px
|
|
|
|
|
|
# Display a styled title in HTML format
|
|
st.markdown(
|
|
"<h1 style='text-align:center; color:red;'> Sample Stock Price App. </h1>",
|
|
unsafe_allow_html=True)
|
|
st.write("Reference: [yfinance Package](https://aroussi.com/post/python-yahoo-finance)")
|
|
# Brief description of the app's purpose
|
|
st.subheader('Build an online application for tracing stock price history')
|
|
|
|
# Display a subheading in Markdown
|
|
st.header("Check Stock History")
|
|
|
|
# Define a list of popular stock symbols
|
|
stock_list = ['MSFT', 'AAPL', 'AMZN', 'GOOGL']
|
|
|
|
# Create a dropdown menu for selecting a stock
|
|
stock_name = st.selectbox('Select a stock to check', options=stock_list)
|
|
|
|
# Input for selecting the start date of stock data, default is January 1, 2024
|
|
start_date = st.date_input('Start Date', datetime(2024, 1, 1))
|
|
# Input for selecting the end date of stock data, default is today
|
|
end_date = st.date_input("End Date")
|
|
|
|
# Store today's date for validation
|
|
today = date.today()
|
|
|
|
# Action to retrieve stock data when the 'Submit' button is clicked
|
|
if st.button('Submit'):
|
|
# Check if selected dates are valid (not in the future)
|
|
if (start_date > today) or (end_date > today) or (start_date > end_date):
|
|
st.warning("Please select a valid date period.")
|
|
else:
|
|
# Get data for the selected stock
|
|
stock = yf.Ticker(stock_name)
|
|
# Retrieve historical data between selected dates
|
|
stock_history = stock.history(start=start_date, end=end_date)
|
|
st.write("**Raw Data of Stock Price**")
|
|
# Display raw data of stock price
|
|
st.dataframe(stock_history)
|
|
# Plot stock price data (Open, High, Low, Close) using Plotly
|
|
fig = px.line(stock_history,
|
|
# use the index of the stock_history data as x-axis.
|
|
x=stock_history.index,
|
|
# plot data of columns ['Open', 'High', 'Low', 'Close']
|
|
y=['Open', 'High', 'Low', 'Close'],
|
|
title=stock_name + " Stock Price",
|
|
labels={
|
|
"value": "Stock Price ($)",
|
|
"variable": "Price Type"
|
|
})
|
|
# Display the generated plot in the app
|
|
st.write(fig)
|
|
# Display a success message upon completion
|
|
st.success('Done')
|
|
|
|
|
|
|
|
"""
|
|
st.divider()
|
|
st.subheader("**Source Code of the Sample App.**")
|
|
|
|
st.code(source_code, line_numbers=True) |