Merge pull request #240 from raihankhan-rk/raihan

fixed #235
This commit is contained in:
Bartick Maiti 2022-10-09 13:01:11 +05:30 committed by GitHub
commit 9d1b637e71
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 182 additions and 0 deletions

View File

@ -0,0 +1,95 @@
from flask import Flask, render_template, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, LoginManager, login_user, login_required, current_user, logout_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import ValidationError, InputRequired, Length
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'YOUR_SECRET_KEY'
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
class RegistrationForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Password"})
submit = SubmitField("Register")
def validate_username(self, username):
existing_user_username = User.query.filter_by(username=username.data).first()
if existing_user_username:
raise ValidationError("That username already exists! Try a different one.")
class LoginForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Password"})
submit = SubmitField("Login")
@app.route('/')
def home():
return render_template('home.html')
@app.route('/dashboard', methods=["GET", "POST"])
@login_required
def dashboard():
return render_template('dashboard.html')
@app.route('/logout', methods=["GET", "POST"])
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/login', methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for('dashboard'))
else:
flash("Incorrect Password! Please Try again")
else:
flash("This email is not registered. Try Signing Up!")
return render_template('login.html', form=form)
@app.route('/register', methods=["GET", "POST"])
def register():
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data)
new_user = User(username=form.username.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run(debug=True)

View File

@ -0,0 +1,87 @@
import requests
import smtplib
from email.message import EmailMessage
MY_EMAIL = ""
MY_PASSWORD = ""
recipients = []
em = EmailMessage()
em['From'] = MY_EMAIL
STOCK_LIST = {"TSLA": "Tesla Inc.",
"AAPL": "Apple Inc.",
"FB": "Meta Platforms, Inc.",
"GOOG": "Alphabet Inc.",
"NFLX": "Netflix, Inc",
}
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
STOCK_API_KEY = ""
NEWS_API_KEY = ""
message = "\n"
for key in STOCK_LIST:
stock_params = {
"function": "TIME_SERIES_DAILY",
"symbol": key,
"apikey": STOCK_API_KEY,
}
COMPANY_NAME = STOCK_LIST[key]
response = requests.get(STOCK_ENDPOINT, params=stock_params)
data = response.json()["Time Series (Daily)"]
data_list = [value for (key, value) in data.items()]
yesterday_data = data_list[0]
yesterday_closing_price = yesterday_data["4. close"]
day_before_yesterday_data = data_list[1]
day_before_yesterday_closing_price = day_before_yesterday_data["4. close"]
difference = (float(yesterday_closing_price) - float(day_before_yesterday_closing_price))
if difference > 0:
notation = "🔺"
updown = "up"
else:
notation = "🔻"
updown = "down"
difference = abs(float(yesterday_closing_price) - float(day_before_yesterday_closing_price))
diff_percent = round(((difference / float(yesterday_closing_price)) * 100), 2)
if diff_percent > 0.05:
news_params = {
"apiKey": NEWS_API_KEY,
"qInTitle": COMPANY_NAME,
}
news_response = requests.get(NEWS_ENDPOINT, params=news_params)
articles = news_response.json()["articles"]
article = articles[0]
message = message + f"{COMPANY_NAME}({key}): {notation}{diff_percent}%\nHeadlines: {article['title']}. \nBrief: {article['description']}\n\n"
print(message)
with smtplib.SMTP("smtp.gmail.com", port=587) as server:
server.starttls()
server.login(user=MY_EMAIL, password=MY_PASSWORD)
em["Subject"] = "Your daily watchlist 📈"
for recipient in recipients:
em.set_content(message)
em['To'] = recipient
server.send_message(em)
del em["To"]
"""
TSLA: 🔺2%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?.
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
or
"TSLA: 🔻5%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?.
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
"""