-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.py
More file actions
58 lines (45 loc) · 1.76 KB
/
task2.py
File metadata and controls
58 lines (45 loc) · 1.76 KB
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
import yfinance as yf
from apscheduler.schedulers.background import BackgroundScheduler
from pymongo import MongoClient
from datetime import datetime
import time
# Function to fetch and store ICICI Bank data
def fetch_and_store_data():
ticker = "ICICIBANK.NS"
# Create a ticker instance for ICICI Bank
icici_bank = yf.Ticker(ticker)
# Get the historical data for the last 15 minutes
historical_data = icici_bank.history(period="15m")
# Store the data in MongoDB
store_data_in_mongodb(historical_data)
# Function to store data in MongoDB
def store_data_in_mongodb(data):
client = MongoClient("mongodb://localhost:27017/")
db = client["stock_data_db"]
collection = db["icici_bank"]
for index, row in data.iterrows():
# Convert the index (which is a Pandas Timestamp) to a Python datetime object
timestamp = index.to_pydatetime()
# Create a document to store in the MongoDB collection
document = {
"Timestamp": timestamp,
"Open": row["Open"],
"High": row["High"],
"Low": row["Low"],
"Close": row["Close"],
"Volume": row["Volume"]
}
# Insert the document into the collection
collection.insert_one(document)
# Create a scheduler to fetch data every 15 minutes
scheduler = BackgroundScheduler()
scheduler.add_job(fetch_and_store_data, 'interval', minutes=15, start_date='2023-10-10 11:15:00')
# Start the scheduler
scheduler.start()
try:
# Keep the script running to continue fetching data
while True:
time.sleep(5)
except (KeyboardInterrupt, SystemExit):
# Shutdown the scheduler if the script is interrupted
scheduler.shutdown()