-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrading_alpaca.py
198 lines (142 loc) · 5.39 KB
/
trading_alpaca.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import os
from alpaca_trade_api import REST
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Alpaca API credentials
BASE_URL = "https://paper-api.alpaca.markets/"
ALPACA_API_KEY = os.environ.get('ALPACA_API_KEY')
ALPACA_SECRET_KEY = os.environ.get('ALPACA_SECRET_KEY')
# Instantiate REST API Connection
api = REST(key_id=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY,
base_url=BASE_URL, api_version='v2')
# Fetch Account
account = api.get_account()
# Print Account Details
print(account.id, account.equity, account.status)
def calculate_mean_reversion(data):
# Make sure column names match those in bars_df
data['Mean'] = data['close'].rolling(window=3).mean()
data['StdDev'] = data['close'].rolling(window=3).std()
data['Upper'] = data['Mean'] + (data['StdDev'] * 2)
data['Lower'] = data['Mean'] - (data['StdDev'] * 2)
data['Position'] = np.where(data['close'] > data['Upper'], -1, np.nan)
data['Position'] = np.where(data['close'] < data['Lower'], 1, data['Position'])
data['Position'] = data['Position'].ffill().fillna(0)
print(data)
return data
# Fetch AMD data from the last 100 days using a valid timeframe
try:
barset = api.get_bars(
'AMD',
timeframe='50Min',
limit=100
)
bars_df = barset.df
data = bars_df
mean_r = calculate_mean_reversion(data)
print(mean_r)
data.to_csv('AMD_mean_reversion_data.csv', index=True)
# Preview Data
print(bars_df.head())
# Optional: Plot the data
plt.style.use('dark_background')
plt.figure(figsize=(12, 6))
plt.plot(bars_df.index, bars_df['close'], label='Close Price')
plt.title('AMD 15-Minute Closing Prices')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()
except Exception as e:
print(f"An error occurred: {e}")
# Call the function with the DataFrame
# data_mr = calculate_mean_reversion(data)
# from alpaca.trading.client import TradingClient
# import alpaca_trade_api as tradeapi
# trading_client = TradingClient('PK1N3MB68S3ALQMIUCV8', 'Gc6GPDNhaAJ5YYbxQayetshmyDGtFcf9jgo32iTr')
# # Get our position in AAPL.
# OII_position = trading_client.get_open_position('OII')
# # Get a list of all of our positions.
# portfolio = trading_client.get_all_positions()
# # Print the quantity of shares for each position.
# for position in portfolio:
# print("{} shares of {}".format(position.qty, position.symbol))
# import alpaca_trade_api as tradeapi
# # from alpaca_trade_api import
# import matplotlib.pyplot as plt
# # # API Info for fetching data, portfolio, etc. from Alpaca
# BASE_URL = "https://paper-api.alpaca.markets/"
# ALPACA_API_KEY = "PK1N3MB68S3ALQMIUCV8"
# ALPACA_SECRET_KEY = "Gc6GPDNhaAJ5YYbxQayetshmyDGtFcf9jgo32iTr"
# # # Instantiate REST API Connection
# api = tradeapi.REST(key_id=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY,
# base_url=BASE_URL, api_version='v2')
# # # Fetch Account
# account = api.get_account()
# #Print Account Details
# print(account.id, account.equity, account.status)
# # # # Fetch Apple data from last 100 days
# AMD_data = api.get_bars('AMD', 'Day', limit=100)
# # # # Preview Data
# print(AMD_data.df.head())
# from alpaca_trade_api import REST, TimeFrame
# import matplotlib.pyplot as plt
# # Alpaca API credentials
# BASE_URL = "https://paper-api.alpaca.markets/"
# ALPACA_API_KEY = "PK1N3MB68S3ALQMIUCV8"
# ALPACA_SECRET_KEY = "Gc6GPDNhaAJ5YYbxQayetshmyDGtFcf9jgo32iTr"
# # Instantiate REST API Connection
# api = REST(key_id=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY,
# base_url=BASE_URL, api_version='v2')
# # Fetch Account
# account = api.get_account()
# # Print Account Details
# print(account.id, account.equity, account.status)
# # Fetch AMD data from last 100 days using correct TimeFrame
# try:
# barset = api.get_bars(
# 'AMD',
# TimeFrame.Day,
# limit=100
# )
# # Convert to DataFrame for easier manipulation
# bars_df = barset.df
# # Preview Data
# print(bars_df.head())
# # Optional: Plot the data
# plt.figure(figsize=(12, 6))
# plt.plot(bars_df.index, bars_df['close'], label='Close Price')
# plt.title('AMD Daily Closing Prices')
# plt.xlabel('Date')
# plt.ylabel('Price')
# plt.legend()
# plt.grid(True)
# plt.show()
# except Exception as e:
# print(f"An error occurred: {e}")
# # # Fetch Apple data from last 100 days
# AMD_data = api.get_bars('AAPL', 'day', limit=100).df
# # Reformat data (drop multiindex, rename columns, reset index)
# AMD_data.columns = AMD_data.columns.to_flat_index()
# AMD_data.columns = [x[1] for x in AMD_data.columns]
# AMD_data.reset_index(inplace=True)
# print(AMD_data.head())
# # Plot stock price data
# plt.style.use('dark_background')
# plot = AMD_data.plot(x="time", y="close", legend=False)
# plot.set_xlabel("Date")
# plot.set_ylabel("Apple Close Price ($)")
# plt.show()
# api.submit_order(symbol='AAPL', qty=1, side='buy', type='market', time_in_force='day')
# #short order for tsla
# api.submit_order('TSLA', 1, 'sell', 'market', 'day')
# # Get stock position for Apple
# aapl_position = api.get_position('AAPL')
# print(aapl_position)
# # Get a list of all of our positions.
# portfolio = api.list_positions()
# # Print the quantity of shares for each position.
# for position in portfolio:
# print("{} shares of {}".format(position.qty, position.symbol))