Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from newsapi import NewsApiClient
|
| 5 |
+
from transformers import pipeline
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow import keras
|
| 8 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 9 |
+
import numpy as np
|
| 10 |
+
from datetime import datetime, timedelta
|
| 11 |
+
import alpaca_trade_api as tradeapi
|
| 12 |
+
import logging
|
| 13 |
+
|
| 14 |
+
# Set up logging
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
# Load environment variables with fallback
|
| 19 |
+
NEWSAPI_KEY = os.getenv('NEWSAPI_KEY', 'your_newsapi_key')
|
| 20 |
+
ALPACA_API_KEY = os.getenv('ALPACA_API_KEY', 'your_alpaca_api_key')
|
| 21 |
+
ALPACA_SECRET_KEY = os.getenv('ALPACA_SECRET_KEY', 'your_alpaca_secret_key')
|
| 22 |
+
APCA_API_KEY_ID = os.getenv('APCA_API_KEY_ID', ALPACA_API_KEY)
|
| 23 |
+
APCA_API_SECRET_KEY = os.getenv('APCA_API_SECRET_KEY', ALPACA_SECRET_KEY)
|
| 24 |
+
|
| 25 |
+
# Check if all necessary keys are available
|
| 26 |
+
if not all([NEWSAPI_KEY, APCA_API_KEY_ID, APCA_API_SECRET_KEY]):
|
| 27 |
+
raise ValueError("Ensure all API keys and secret keys are set as environment variables.")
|
| 28 |
+
|
| 29 |
+
# Initialize NewsAPI client
|
| 30 |
+
newsapi = NewsApiClient(api_key=NEWSAPI_KEY)
|
| 31 |
+
|
| 32 |
+
# Initialize Alpaca Trade API client
|
| 33 |
+
alpaca_api = tradeapi.REST(APCA_API_KEY_ID, APCA_API_SECRET_KEY, base_url='https://paper-api.alpaca.markets')
|
| 34 |
+
|
| 35 |
+
def collect_market_data(ticker):
|
| 36 |
+
data = yf.download(ticker, start=(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'), end=datetime.now().strftime('%Y-%m-%d'))
|
| 37 |
+
data.to_csv(f'{ticker}_market_data.csv')
|
| 38 |
+
logger.info(f'Market data for {ticker} collected successfully.')
|
| 39 |
+
|
| 40 |
+
def collect_news_data(query, from_date, to_date):
|
| 41 |
+
all_articles = newsapi.get_everything(q=query, from_param=from_date, to=to_date, language='en', sort_by='relevancy')
|
| 42 |
+
if all_articles['status'] == 'ok':
|
| 43 |
+
articles_df = pd.DataFrame(all_articles['articles'])
|
| 44 |
+
articles_df.to_csv('news_data.csv')
|
| 45 |
+
logger.info(f'News data for {query} collected successfully.')
|
| 46 |
+
else:
|
| 47 |
+
logger.error(f'Error collecting news data: {all_articles["message"]}')
|
| 48 |
+
|
| 49 |
+
def perform_sentiment_analysis():
|
| 50 |
+
sentiment_pipeline = pipeline("sentiment-analysis")
|
| 51 |
+
try:
|
| 52 |
+
news_data = pd.read_csv('news_data.csv')
|
| 53 |
+
news_data['sentiment'] = news_data['description'].apply(lambda x: sentiment_pipeline(x)[0]['label'] if pd.notna(x) else 'NEUTRAL')
|
| 54 |
+
news_data.to_csv('sentiment_data.csv', index=False)
|
| 55 |
+
logger.info('Sentiment analysis performed successfully.')
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.error(f'Error performing sentiment analysis: {e}')
|
| 58 |
+
|
| 59 |
+
def train_price_prediction_model(ticker):
|
| 60 |
+
data = pd.read_csv(f'{ticker}_market_data.csv')
|
| 61 |
+
data = data[['Date', 'Close']].set_index('Date')
|
| 62 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 63 |
+
scaled_data = scaler.fit_transform(data)
|
| 64 |
+
|
| 65 |
+
X = []
|
| 66 |
+
y = []
|
| 67 |
+
|
| 68 |
+
for i in range(60, len(scaled_data)):
|
| 69 |
+
X.append(scaled_data[i-60:i, 0])
|
| 70 |
+
y.append(scaled_data[i, 0])
|
| 71 |
+
|
| 72 |
+
X = np.array(X)
|
| 73 |
+
y = np.array(y)
|
| 74 |
+
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
|
| 75 |
+
|
| 76 |
+
model = keras.Sequential([
|
| 77 |
+
keras.layers.LSTM(50, return_sequences=True, input_shape=(X.shape[1], 1)),
|
| 78 |
+
keras.layers.LSTM(50, return_sequences=False),
|
| 79 |
+
keras.layers.Dense(25),
|
| 80 |
+
keras.layers.Dense(1)
|
| 81 |
+
])
|
| 82 |
+
|
| 83 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 84 |
+
model.fit(X, y, batch_size=1, epochs=1)
|
| 85 |
+
|
| 86 |
+
model.save(f'{ticker}_price_prediction_model.h5')
|
| 87 |
+
logger.info('Price prediction model trained successfully.')
|
| 88 |
+
|
| 89 |
+
def make_trade_decision(ticker):
|
| 90 |
+
model = keras.models.load_model(f'{ticker}_price_prediction_model.h5')
|
| 91 |
+
data = pd.read_csv(f'{ticker}_market_data.csv')
|
| 92 |
+
last_60_days = data['Close'].tail(60).values
|
| 93 |
+
last_60_days_scaled = MinMaxScaler(feature_range=(0, 1)).fit_transform(last_60_days.reshape(-1, 1))
|
| 94 |
+
|
| 95 |
+
X_test = []
|
| 96 |
+
X_test.append(last_60_days_scaled)
|
| 97 |
+
X_test = np.array(X_test)
|
| 98 |
+
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
|
| 99 |
+
|
| 100 |
+
predicted_price = model.predict(X_test)
|
| 101 |
+
predicted_price = MinMaxScaler(feature_range=(0, 1)).inverse_transform(predicted_price)
|
| 102 |
+
|
| 103 |
+
current_price = yf.download(ticker, period='1d')['Close'].values[0]
|
| 104 |
+
|
| 105 |
+
if predicted_price > current_price:
|
| 106 |
+
alpaca_api.submit_order(
|
| 107 |
+
symbol=ticker,
|
| 108 |
+
qty=1,
|
| 109 |
+
side='buy',
|
| 110 |
+
type='market',
|
| 111 |
+
time_in_force='gtc'
|
| 112 |
+
)
|
| 113 |
+
logger.info(f'Bought 1 share of {ticker}')
|
| 114 |
+
else:
|
| 115 |
+
alpaca_api.submit_order(
|
| 116 |
+
symbol=ticker,
|
| 117 |
+
qty=1,
|
| 118 |
+
side='sell',
|
| 119 |
+
type='market',
|
| 120 |
+
time_in_force='gtc'
|
| 121 |
+
)
|
| 122 |
+
logger.info(f'Sold 1 share of {ticker}')
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
TICKER = 'AAPL'
|
| 126 |
+
QUERY = 'Apple Inc'
|
| 127 |
+
FROM_DATE = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
|
| 128 |
+
TO_DATE = datetime.now().strftime('%Y-%m-%d')
|
| 129 |
+
|
| 130 |
+
collect_market_data(TICKER)
|
| 131 |
+
collect_news_data(QUERY, FROM_DATE, TO_DATE)
|
| 132 |
+
perform_sentiment_analysis()
|
| 133 |
+
train_price_prediction_model(TICKER)
|
| 134 |
+
make_trade_decision(TICKER)
|