-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutocorrelation.py
103 lines (85 loc) · 3.07 KB
/
Autocorrelation.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
from polygon import RESTClient
from typing import cast
from urllib3 import HTTPResponse
import pandas as pd
import json
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
# API setup and data retrieval
api_key = 'your polygon api key'
client = RESTClient(api_key)
# Get the current date and subtract one day to get the previous date
end_date = datetime.now().date() # Current date
start_date = end_date - timedelta(days=1) # Previous date
# Convert dates to strings in the format 'YYYY-MM-DD'
start_date_str = start_date.strftime('%Y-%m-%d')
end_date_str = end_date.strftime('%Y-%m-%d')
# Fetch the data
aggs = cast(
HTTPResponse,
client.get_aggs(
'NVDA',
1,
'minute',
start_date_str,
end_date_str,
raw=True
),
)
poly_data = json.loads(aggs.data)
poly_data = poly_data['results']
# Check the length of the data to ensure full period coverage
print(f"Number of data points fetched: {len(poly_data)}")
# Prepare the data for DataFrame
dates = []
open_prices = []
high_prices = []
low_prices = []
close_prices = []
volumes = []
for bar in poly_data:
dates.append(pd.Timestamp(bar['t'], tz='GMT', unit='ms'))
open_prices.append(bar['o'])
high_prices.append(bar['h'])
low_prices.append(bar['l'])
close_prices.append(bar['c'])
volumes.append(bar['v'])
data = {
'Open': open_prices,
'High': high_prices,
'Low': low_prices,
'Close': close_prices,
'Volume': volumes
}
dataFrame = pd.DataFrame(data, index=dates)
# Calculate returns (percentage change in closing prices)
dataFrame['Returns'] = dataFrame['Close'].pct_change()
# Calculate rolling volatility (standard deviation of returns)
dataFrame['Volatility'] = dataFrame['Returns'].rolling(window=30).std()
# Create a figure and subplots
fig, ax = plt.subplots(4, 1, figsize=(14, 12), sharex=True)
# 1. Plot the line chart for the closing prices
ax[0].set_title('NVDA Line Chart - Closing Prices')
ax[0].plot(dataFrame.index, dataFrame['Close'], label='Close Price')
ax[0].set_ylabel('Price')
ax[0].legend()
# 2. Calculate and plot rolling autocorrelation of returns
rolling_autocorr = dataFrame['Returns'].rolling(window=30).apply(lambda x: x.autocorr(), raw=False)
rolling_autocorr = rolling_autocorr.dropna() # Drop NaN values from autocorrelation
ax[1].plot(rolling_autocorr, label='Rolling Autocorrelation (30-minute window)')
ax[1].set_title('Rolling Autocorrelation of Returns')
ax[1].set_ylabel('Autocorrelation')
ax[1].legend()
# 3. Plot the volume data
ax[2].bar(dataFrame.index, dataFrame['Volume'], width=0.0005, label='Volume', color='orange')
ax[2].set_title('Volume over Time')
ax[2].set_ylabel('Volume')
ax[2].legend()
# 4. Plot the volatility data
ax[3].plot(dataFrame.index, dataFrame['Volatility'], label='Rolling Volatility (30-minute window)', color='green')
ax[3].set_title('Volatility over Time')
ax[3].set_ylabel('Volatility')
ax[3].legend()
# Format the x-axis for better readability (time)
plt.tight_layout()
plt.show()