我一直在努力插入一个图形/图表到html.我已经尝试了一个基本的matplotlib图表(测试图1)使用mpld 3将图转换为html.我也尝试创建一个图形与mplfinance(测试图2).所有我已经尝试到目前为止都没有成功,现在几天.
第一个图表,我想使,我试图拉数据为每个股票代码到一个图表,对应于正确的股票代码的ticker_page.html
。然后,我试图使它更简单,因此(测试图1)
我在想我的问题是如何正确地链接@app.route。我不想要一个.png或静态的东西,因为以后当我更好地理解连接时,我会使图形与可能的超链接,滚动功能等交互。
关于到目前为止如何设置应用程序的背景信息,有一个/News
页面。在新闻页面上有一个列表中的名称。当您单击其中一个名称时,它会将您带到/ticker
页面,该页面正确显示ticker_page.html
,而不是我试图插入的图表。
APP.PY:
from flask import Flask, render_template, request
from datetime import datetime
from itertools import groupby
import pipeline
import mpld3
import matplotlib.pyplot as plt
import pandas_datareader
import mplfinance as mpf
app = Flask(__name__)
# Read in the data from the CSV file
CSV_data = 'path'
with open(CSV_data, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
articles = [row for row in reader]
# Get the list of unique tickers from the data
tickers = sorted(set(article['Ticker'] for article in articles))
def format_date(date_str):
try:
# Check if date string is in "DD-Mon-YY" format
date_obj = datetime.strptime(date_str, "%d-%b-%y")
except ValueError:
# Check if date string is in "MM/DD/YYYY" format
date_obj = datetime.strptime(date_str, "%m/%d/%Y")
return date_obj.date().strftime("%m-%d-%Y")
def sort_articles(articles):
try:
return sorted(articles, key=lambda x: datetime.strptime(x["Date"], "%m-%d-%Y"), reverse=True)
except (KeyError, ValueError):
print("Houston, we have a problem")
return articles
@app.route('/')
def index():
# Your logic for the home page here
# For example, you can set up a welcome message
welcome_message = "Welcome!"
return render_template('index.html', welcome_message=welcome_message)
@app.route('/news')
def urls():
selected_tickers = request.args.getlist('ticker')
# Filter the articles based on the selected tickers
filtered_articles = [article for article in articles if not selected_tickers or article['Ticker'] in selected_tickers]
# Generate a dictionary to map each ticker to its date, title, and link
ticker_articles = {}
for article in filtered_articles:
ticker = article['Ticker']
if ticker not in ticker_articles:
ticker_articles[ticker] = []
ticker_articles[ticker].append((article['Date'], article['Title'], article['Link']))
# Render the 'urls.html' template with the necessary data
return render_template('urls.html', tickers=tickers, filtered_articles=filtered_articles, ticker_articles=ticker_articles)
#TEST FIG 1
@app.route('/graph/<string:ticker>/')
def graph(ticker):
fig, ax = plt.subplots(ticker)
# Add some data to the plot
ax.plot([1, 2, 3], [4, 5, 6])
# Convert the Matplotlib figure to HTML
html_graph = mpld3.fig_to_html(fig)
return render_template('ticker_page.html', html_graph=html_graph)
#TEST FIG 2
@app.route('/pricegraph/<string:ticker>/')
def generate_price_chart(ticker):
"""Generates a price chart for the given ticker."""
# Get the historical price data for the ticker
df = mpf.DataReader(ticker, period="1d")
# Create a Matplotlib figure
fig = mpf.figure(figsize=(10, 6))
# Add the price chart to the figure
mpf.plot(df, type="candle", style="yahoo", fig=fig, ax=fig.add_subplot(111))
# Convert the Matplotlib figure to HTML
html = mpf.fig_to_html(fig)
return html
@app.route('/ticker/<string:ticker>/')
def ticker_page(ticker):
# Sample data for demonstration purposes
ticker_data = {
'ticker': ticker,
'date': '2023-07-19',
'article_name': 'Sample Article for ' + ticker,
'article_url': 'https://example.com/' + ticker,
#'chart': html_graph
}
# Render the 'ticker_page.html' template with the ticker data
return render_template('ticker_page.html', ticker_data=ticker_data)#, html_graph=html_graph)#, html=html_pipeline)
if __name__ == '__main__':
app.run(debug=True)
TICKER_PAGE.HTML
{% extends 'base.html' %}
{% block content %}
<title>{{ ticker_data.ticker }} Page - TITLE</title>
<head>
</head>
<body>
<div></div>
<div id="data"><h1>{{ ticker_data.ticker }}</h1>
<p>Date: {{ ticker_data.date }}</p>
</div>
<div id="pipeline">
<h2>Pipeline Chart</h2>
<div>
{{html_graph}}
</div>
<div>
<script>
// Get the price chart HTML
var html = "{{ html }}";
// Render the price chart
document.getElementById("pricegraph").innerHTML = html;
</script> </div>
</div>
<div id="news">
<h2>Press Releases</h2>
<p>Sample Article URL:
<a href="{{ ticker_data.article_url }}" target="_blank">{{ ticker_data.article_name }}</a>
</p>
<p>Sample Article: {{ ticker_data.article_name }}</p>
</div>
</div>
</body>
{% endblock %}
我一直在努力插入一个图形/图表到html.我已经尝试了一个基本的matplotlib图表(测试图1)使用mpld 3将图转换为html.我也尝试创建一个图形与mplfinance(测试图2).所有我已经尝试到目前为止都没有成功,现在几天.
我在想我的问题是如何正确地链接@app.route。我不想要一个.png或静态的东西,因为以后当我更好地理解连接时,我会使图形与可能的超链接,滚动功能等交互。
关于到目前为止如何设置应用程序的背景信息,有一个/News
页面。在新闻页面上有一个列表中的名称。当您单击其中一个名称时,它会将您带到/ticker
页面,该页面正确显示ticker_page.html
,而不是我试图插入的图表。
APP.PY:
from flask import Flask, render_template, request
from datetime import datetime
from itertools import groupby
import pipeline
import mpld3
import matplotlib.pyplot as plt
import pandas_datareader
import mplfinance as mpf
app = Flask(__name__)
# Read in the data from the CSV file
CSV_data = 'path'
with open(CSV_data, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
articles = [row for row in reader]
# Get the list of unique tickers from the data
tickers = sorted(set(article['Ticker'] for article in articles))
def format_date(date_str):
try:
# Check if date string is in "DD-Mon-YY" format
date_obj = datetime.strptime(date_str, "%d-%b-%y")
except ValueError:
# Check if date string is in "MM/DD/YYYY" format
date_obj = datetime.strptime(date_str, "%m/%d/%Y")
return date_obj.date().strftime("%m-%d-%Y")
def sort_articles(articles):
try:
return sorted(articles, key=lambda x: datetime.strptime(x["Date"], "%m-%d-%Y"), reverse=True)
except (KeyError, ValueError):
print("Houston, we have a problem")
return articles
@app.route('/')
def index():
# Your logic for the home page here
# For example, you can set up a welcome message
welcome_message = "Welcome!"
return render_template('index.html', welcome_message=welcome_message)
@app.route('/news')
def urls():
selected_tickers = request.args.getlist('ticker')
# Filter the articles based on the selected tickers
filtered_articles = [article for article in articles if not selected_tickers or article['Ticker'] in selected_tickers]
# Generate a dictionary to map each ticker to its date, title, and link
ticker_articles = {}
for article in filtered_articles:
ticker = article['Ticker']
if ticker not in ticker_articles:
ticker_articles[ticker] = []
ticker_articles[ticker].append((article['Date'], article['Title'], article['Link']))
# Render the 'urls.html' template with the necessary data
return render_template('urls.html', tickers=tickers, filtered_articles=filtered_articles, ticker_articles=ticker_articles)
#TEST FIG 1
@app.route('/graph/<string:ticker>/')
def graph(ticker):
fig, ax = plt.subplots(ticker)
# Add some data to the plot
ax.plot([1, 2, 3], [4, 5, 6])
# Convert the Matplotlib figure to HTML
html_graph = mpld3.fig_to_html(fig)
return render_template('ticker_page.html', html_graph=html_graph)
#TEST FIG 2
@app.route('/pricegraph/<string:ticker>/')
def generate_price_chart(ticker):
"""Generates a price chart for the given ticker."""
# Get the historical price data for the ticker
df = mpf.DataReader(ticker, period="1d")
# Create a Matplotlib figure
fig = mpf.figure(figsize=(10, 6))
# Add the price chart to the figure
mpf.plot(df, type="candle", style="yahoo", fig=fig, ax=fig.add_subplot(111))
# Convert the Matplotlib figure to HTML
html = mpf.fig_to_html(fig)
return html
@app.route('/ticker/<string:ticker>/')
def ticker_page(ticker):
# Sample data for demonstration purposes
ticker_data = {
'ticker': ticker,
'date': '2023-07-19',
'article_name': 'Sample Article for ' + ticker,
'article_url': 'https://example.com/' + ticker,
#'chart': html_graph
}
# Render the 'ticker_page.html' template with the ticker data
return render_template('ticker_page.html', ticker_data=ticker_data)#, html_graph=html_graph)#, html=html_pipeline)
if __name__ == '__main__':
app.run(debug=True)
TICKER_PAGE.HTML
{% extends 'base.html' %}
{% block content %}
<title>{{ ticker_data.ticker }} Page - TITLE</title>
<head>
</head>
<body>
<div></div>
<div id="data"><h1>{{ ticker_data.ticker }}</h1>
<p>Date: {{ ticker_data.date }}</p>
</div>
<div id="pipeline">
<h2>Pipeline Chart</h2>
<div>
{{html_graph}}
</div>
<div>
<script>
// Get the price chart HTML
var html = "{{ html }}";
// Render the price chart
document.getElementById("pricegraph").innerHTML = html;
</script> </div>
</div>
<div id="news">
<h2>Press Releases</h2>
<p>Sample Article URL:
<a href="{{ ticker_data.article_url }}" target="_blank">{{ ticker_data.article_name }}</a>
</p>
<p>Sample Article: {{ ticker_data.article_name }}</p>
</div>
</div>
</body>
{% endblock %}
1条答案
按热度按时间dkqlctbz1#
我知道了一部分我在做什么,但足以回答这个问题的基础。我不应该使用
matplotlib
。我应该使用chart.js
。我还不知道如何从app.py
调用,但现在我发现我可以直接将图表插入HTML。chart.js文档链接:https://www.chartjs.org/docs/latest/
ticker_page.html