-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
166 lines (142 loc) · 5.88 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# from lumibot.brokers import Alpaca
# from lumibot.backtesting import YahooDataBacktesting
# from lumibot.strategies.strategy import Strategy
# from lumibot.traders import Trader
# from datetime import datetime
# from alpaca_trade_api import REST
# from datetime import datetime ,timedelta
# base_url = "https://paper-api.alpaca.markets/v2"
# api_secret = "EgWKKpY7ZPmg6QfRLAIRhx5EL3tB5BvgLke2FOs5"
# api_key = "PK8E5I05JTIRMZG272LC"
# alpaca_cred = {
# "API_KEY" : api_key,
# "API_SECRET" : api_secret,
# "PAPER" : True
# }
# class MLtrader(Strategy):
# def initialize(self, symbol:str="SPY", cash_at_risk:float=.5):
# self.symbol = symbol
# self.sleeptime = "24H"
# self.last_trade = None
# self.cash_at_risk = cash_at_risk
# self.api=REST(base_url=base_url, key_id=api_key, secret_key=api_secret)
# def on_trading_iteration(self):
# cash, last_price, quantity = self.position_sizing()
# if cash > last_price:
# if self.last_trade == None:
# news=self.get_news()
# print(news)
# order=self.create_order(self.symbol,
# 10,
# "buy",
# type = "bracket",
# take_profit_price = last_price*1.20,
# stop_loss_price = last_price*0.95)
# self.submit_order(order)
# self.last_trade="buy"
# def position_sizing(self):
# cash = self.get_cash()
# last_price = self.get_last_price(self.symbol)
# quantity = round(cash * self.cash_at_risk / last_price,0)
# return cash, last_price, quantity
# def get_dates(self):
# today=self.get_datetime()
# three_days_prior=today-timedelta(days=3)
# return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')
# def get_sentiment(self):
# today, three_days_prior = self.get_dates()
# news=self.api.get_news(symbol=self.symbol, start=three_days_prior, end=today)
# news = [ev.__dict__["_raw"]["headline"] for ev in news]
# return news
# start_date=datetime(2023, 12, 15)
# end_date=datetime(2023, 12, 31)
# broker= Alpaca(alpaca_cred)
# strategy=MLtrader(name = 'mlstart', broker = broker,
# parameter={"symbol" : "SPY",
# "cash_at_risk" : .5})
# strategy.backtest(YahooDataBacktesting,
# start_date,
# end_date,
# parameters={"symbol":"SPY", "cash_at_rish":.5})
from lumibot.brokers import Alpaca
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies.strategy import Strategy
from lumibot.traders import Trader
from datetime import datetime
from alpaca_trade_api import REST
from timedelta import Timedelta
from finbert_utils import estimate_sentiment
API_KEY = "PK8E5I05JTIRMZG272LC"
API_SECRET = "EgWKKpY7ZPmg6QfRLAIRhx5EL3tB5BvgLke2FOs5"
BASE_URL = "https://paper-api.alpaca.markets"
ALPACA_CREDS = {
"API_KEY":API_KEY,
"API_SECRET": API_SECRET,
"PAPER": True
}
class MLTrader(Strategy):
def initialize(self, symbol:str="SPY", cash_at_risk:float=.5):
self.symbol = symbol
self.sleeptime = "24H"
self.last_trade = None
self.cash_at_risk = cash_at_risk
self.api = REST(base_url=BASE_URL, key_id=API_KEY, secret_key=API_SECRET)
def position_sizing(self):
cash = self.get_cash()
last_price = self.get_last_price(self.symbol)
quantity = round(cash * self.cash_at_risk / last_price,0)
return cash, last_price, quantity
def get_dates(self):
today = self.get_datetime()
three_days_prior = today - Timedelta(days=3)
return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')
def get_sentiment(self):
today, three_days_prior = self.get_dates()
news = self.api.get_news(symbol=self.symbol,
start=three_days_prior,
end=today)
news = [ev.__dict__["_raw"]["headline"] for ev in news]
probability, sentiment = estimate_sentiment(news)
return probability, sentiment
def on_trading_iteration(self):
cash, last_price, quantity = self.position_sizing()
probability, sentiment = self.get_sentiment()
if cash > last_price:
if sentiment == "positive" and probability > .999:
if self.last_trade == "sell":
self.sell_all()
order = self.create_order(
self.symbol,
quantity,
"buy",
type="bracket",
take_profit_price=last_price*1.20,
stop_loss_price=last_price*.95
)
self.submit_order(order)
self.last_trade = "buy"
elif sentiment == "negative" and probability > .999:
if self.last_trade == "buy":
self.sell_all()
order = self.create_order(
self.symbol,
quantity,
"sell",
type="bracket",
take_profit_price=last_price*.8,
stop_loss_price=last_price*1.05
)
self.submit_order(order)
self.last_trade = "sell"
start_date = datetime(2020,1,1)
end_date = datetime(2023,12,31)
broker = Alpaca(ALPACA_CREDS)
strategy = MLTrader(name='mlstrat', broker=broker,
parameters={"symbol":"SPY",
"cash_at_risk":.5})
strategy.backtest(
YahooDataBacktesting,
start_date,
end_date,
parameters={"symbol":"SPY", "cash_at_risk":.5}
)