Spaces:
Runtime error
Runtime error
Ken Sang Tang commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,26 +1,97 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
# Function to
|
| 13 |
-
def
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
# Set up Gradio interface
|
| 24 |
-
gr.Interface(fn=generate_response, inputs="text", outputs="text").launch()
|
| 25 |
|
| 26 |
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification
|
| 4 |
+
from alpaca_trade_api.rest import REST, TimeFrame
|
| 5 |
+
import yfinance as yf
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas_ta as ta
|
| 8 |
import torch
|
| 9 |
|
| 10 |
+
# Configuration
|
| 11 |
+
ALPACA_API_KEY = 'AKRII2NASCQ4UYYNMUBJ'
|
| 12 |
+
ALPACA_SECRET_KEY = 'amTJvuxDsojAZFVU3wEt6IZPBN9L5VvhfbwR28fj'
|
| 13 |
+
ALPACA_BASE_URL = 'https://paper-api.alpaca.markets'
|
| 14 |
+
MODEL_NAME = "databricks/dolly-v2-3b"
|
| 15 |
+
FINBERT_MODEL_NAME = "yiyanghkust/finbert-tone"
|
| 16 |
+
SYMBOL = '^KLSE' # KLCI index symbol
|
| 17 |
+
START_DATE = '2020-01-01'
|
| 18 |
+
END_DATE = '2023-12-31'
|
| 19 |
+
|
| 20 |
+
# Initialize Alpaca API
|
| 21 |
+
api = REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL)
|
| 22 |
+
|
| 23 |
+
# Load Models
|
| 24 |
+
dolly_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 25 |
+
dolly_model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
|
| 26 |
+
finbert_tokenizer = AutoTokenizer.from_pretrained(FINBERT_MODEL_NAME)
|
| 27 |
+
finbert_model = AutoModelForSequenceClassification.from_pretrained(FINBERT_MODEL_NAME)
|
| 28 |
+
|
| 29 |
+
# Step 1: Fetch KLCI Data
|
| 30 |
+
def fetch_stock_data(symbol, start_date, end_date):
|
| 31 |
+
print("Fetching stock data...")
|
| 32 |
+
data = yf.download(symbol, start=start_date, end=end_date)
|
| 33 |
+
data = add_technical_indicators(data)
|
| 34 |
+
return data
|
| 35 |
+
|
| 36 |
+
# Step 2: Add Technical Indicators
|
| 37 |
+
def add_technical_indicators(data):
|
| 38 |
+
print("Adding technical indicators...")
|
| 39 |
+
data['RSI'] = ta.rsi(data['Close'], length=14)
|
| 40 |
+
data['MACD'] = ta.macd(data['Close'], fast=12, slow=26)['MACD_12_26_9']
|
| 41 |
+
bbands = ta.bbands(data['Close'])
|
| 42 |
+
data['BB_upper'], data['BB_middle'], data['BB_lower'] = bbands['BBU_20_2.0'], bbands['BBM_20_2.0'], bbands['BBL_20_2.0']
|
| 43 |
+
return data
|
| 44 |
+
|
| 45 |
+
# Step 3: Analyze Sentiment using FinBERT
|
| 46 |
+
def analyze_sentiment(text):
|
| 47 |
+
print("Analyzing sentiment...")
|
| 48 |
+
inputs = finbert_tokenizer(text, return_tensors="pt")
|
| 49 |
+
outputs = finbert_model(**inputs)
|
| 50 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 51 |
+
sentiment = torch.argmax(predictions).item()
|
| 52 |
+
return ["Negative", "Neutral", "Positive"][sentiment]
|
| 53 |
|
| 54 |
+
# Step 4: Generate Dolly Prediction
|
| 55 |
+
def generate_prediction(prompt):
|
| 56 |
+
print("Generating prediction...")
|
| 57 |
+
inputs = dolly_tokenizer(prompt, return_tensors="pt")
|
| 58 |
+
outputs = dolly_model.generate(**inputs, max_length=100)
|
| 59 |
+
return dolly_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 60 |
|
| 61 |
+
# Step 5: Execute Trade with Alpaca
|
| 62 |
+
def execute_trade(signal, symbol='AAPL', qty=1):
|
| 63 |
+
print(f"Executing trade signal: {signal}")
|
| 64 |
+
if signal == "buy":
|
| 65 |
+
api.submit_order(symbol=symbol, qty=qty, side='buy', type='market', time_in_force='gtc')
|
| 66 |
+
elif signal == "sell":
|
| 67 |
+
api.submit_order(symbol=symbol, qty=qty, side='sell', type='market', time_in_force='gtc')
|
| 68 |
|
| 69 |
+
# Step 6: Main Function to Run Pipeline
|
| 70 |
+
def main():
|
| 71 |
+
# 1. Fetch and Prepare Data
|
| 72 |
+
klci_data = fetch_stock_data(SYMBOL, START_DATE, END_DATE)
|
| 73 |
+
|
| 74 |
+
# 2. Run FinBERT Sentiment Analysis
|
| 75 |
+
sample_text = "The market sentiment is bullish for KLCI." # Example text
|
| 76 |
+
sentiment = analyze_sentiment(sample_text)
|
| 77 |
+
print(f"Sentiment: {sentiment}")
|
| 78 |
+
|
| 79 |
+
# 3. Generate Dolly Prediction
|
| 80 |
+
prompt = f"The market trend for KLCI with sentiment {sentiment} and indicators {klci_data[['RSI', 'MACD', 'BB_upper', 'BB_middle', 'BB_lower']].iloc[-1].to_dict()}"
|
| 81 |
+
prediction = generate_prediction(prompt)
|
| 82 |
+
print(f"Dolly Prediction: {prediction}")
|
| 83 |
+
|
| 84 |
+
# 4. Decide Buy/Sell based on Prediction and Execute Trade
|
| 85 |
+
if "buy" in prediction.lower():
|
| 86 |
+
execute_trade("buy", symbol=SYMBOL, qty=1)
|
| 87 |
+
elif "sell" in prediction.lower():
|
| 88 |
+
execute_trade("sell", symbol=SYMBOL, qty=1)
|
| 89 |
+
else:
|
| 90 |
+
print("No clear trade signal from prediction.")
|
| 91 |
|
| 92 |
+
# Run the main function
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
| 95 |
|
|
|
|
|
|
|
| 96 |
|
| 97 |
|