Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multistock Dashboard #6

Draft
wants to merge 1 commit into
base: inclass
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions test/alpha_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,23 @@ def test_fetch_stocks_daily():
df = alpha.fetch_stocks_daily(symbol="OOPS")
assert isinstance(df, DataFrame)
assert df.empty



def test_fetch_multistock_daily():
alpha = AlphavantageService()

# with valid symbol, returns the data:
result = alpha.fetch_multistock_daily(symbols=["IBM", "NFLX"])
assert isinstance(result, dict)
assert list(result.keys()) == ["IBM", "NFLX"]

data = result["IBM"]
assert isinstance(data, list)
assert len(data) >= 100
assert list(data[0].keys()) == ['timestamp', 'open', 'high', 'low', 'close', 'adjusted_close', 'volume', 'dividend_amount', 'split_coefficient']

data = result["NFLX"]
assert isinstance(data, list)
assert len(data) >= 100
assert list(data[0].keys()) == ['timestamp', 'open', 'high', 'low', 'close', 'adjusted_close', 'volume', 'dividend_amount', 'split_coefficient']
23 changes: 22 additions & 1 deletion web_app/routes/dashboard_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def stocks_dashboard():
return redirect("/stocks/form")



@dashboard_routes.route("/unemployment/dashboard")
def unemployment_dashboard():
print("UNEMPLOYMENT DASHBOARD...")
Expand All @@ -58,3 +57,25 @@ def unemployment_dashboard():
print("ERROR", err)
#flash("OOPS", "warning")
return redirect("/")





# can hit this with: "/multistock/dashboard?symbols=NFLX&symbols=GOOGL&symbols=MSFT"
@dashboard_routes.route("/multistock/dashboard", methods=["GET"])
def multistock_dashboard():
print("MULTI-STOCK DASHBOARD...")

# consider reading these symbols from a datastore, or asking for multiple inputs
symbols = request.args.getlist("symbols") or ["NFLX", "GOOGL", "MSFT"]
print(symbols)

try:
alpha = AlphavantageService()
data = alpha.fetch_multistock_daily(symbols=symbols)
return render_template("multistock_dashboard.html", symbols=symbols, data=data)
except Exception as err:
print("ERROR", err)
#flash("OOPS", "warning")
return redirect("/")
11 changes: 10 additions & 1 deletion web_app/services/alpha.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from dotenv import load_dotenv
from pandas import read_csv, DataFrame


load_dotenv()

ALPHAVANTAGE_API_KEY = os.getenv("ALPHAVANTAGE_API_KEY", default="demo")
Expand Down Expand Up @@ -44,6 +43,16 @@ def fetch_stocks_daily(self, symbol="MSFT"):
else:
return df

def fetch_multistock_daily(self, symbols:list):
results = {}
for symbol in symbols:
request_url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={symbol}&apikey={self.api_key}&datatype=csv"
df = read_csv(request_url)
results[symbol] = df.to_dict("records")
# TODO: consider implementing some kind of validation or re-attempt in case one or more requests goes bad
return results #> {"MSFT": [], "GOOGL": [], "NFLX": []}


def fetch_unemployment(self):
"""
Fetches unemployment data.
Expand Down
46 changes: 46 additions & 0 deletions web_app/templates/multistock_dashboard.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{% extends "bootstrap_5_layout.html" %}
{% set active_page = "stocks_dashboard" %}

{% block content %}

<h2>Multistock Dashboard</h2>

<p>Selected Stocks: <span id="display-symbol">{{ symbols }}</span></p>

<div id="dataviz-container"></div>


<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type="text/javascript">

// processing the specific JSON response data returned by the router:
var responseData = JSON.parse('{{data | tojson}}')
console.log(responseData) //> {"MSFT": [], "GOOGL": [], "NFLX": []}

var symbols = Object.keys(responseData)
console.log(symbols)

// charting the data (see https://plotly.com/javascript/line-charts/):
var title = "Daily Closing Prices (Multistock)"
var layout = {title: title, height: 500}
var chartData = []

symbols.forEach(symbol => {
console.log(symbol)
var symbolData = responseData[symbol]

var dates = [] //> an array of date keys, for the chart ["2020-01-27", "2020-01-24", "2020-01-23", etc.]
var closingPrices = [] //> an array of price objects
symbolData.forEach(row => {
dates.push(row["timestamp"])
closingPrices.push(row["adjusted_close"])
});

chartData.push({x: dates, y: closingPrices, mode: "lines+markers", name: symbol})
})

Plotly.newPlot("dataviz-container", chartData, layout, {responsive: true})

</script>

{% endblock %}