Truy xuất và lưu dữ liệu realtime lên Google Sheet
Các ví dụ liên quan đến việc truy xuất dữ liệu realtime và lưu lên Google Sheet
Last updated
Các ví dụ liên quan đến việc truy xuất dữ liệu realtime và lưu lên Google Sheet
Last updated
import os
import gspread
import time
import pandas as pd
from FiinQuantX import FiinSession, RealTimeData
from gspread_dataframe import set_with_dataframe
from oauth2client.service_account import ServiceAccountCredentials
username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"
client_fq = FiinSession(
username = username,
password = password
).login()
def OnTickerEvent(data: RealTimeData):
global full_df
df = data.to_dataFrame()
# Xác thực và kết nối đến Google Sheets
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("REPLACE_WITH_JSON_FILE_NAME")
client = gspread.authorize(creds)
# Mở Google Sheet và chọn worksheet
sheet = client.open("REPLACE_WITH_YOUR_GOOGLE_SHEET_FILE_NAME").worksheet("REPLACE_WITH_SHEET_NAME")
# Thêm data vào Google Sheet ---
existing_rows = len(sheet.get_all_values()) # Đếm số cột hiện có
# Nếu chưa có cột nào thêm data mới bao gồm cả tiêu đề cột, nếu không chỉ thêm data, không thêm tiêu đề cột
if existing_rows <= 1:
set_with_dataframe(sheet, df, row=existing_rows, include_column_header=True)
else:
set_with_dataframe(sheet, df, row=existing_rows + 1, include_column_header=False)
tickers = ['STB', 'FPT', 'MSN', 'HPG']
event = client_fq.Trading_Data_Stream(tickers=tickers, callback=OnTickerEvent)
event.start()
try:
while not event._stop:
time.sleep(1)
except KeyboardInterrupt:
print("KeyboardInterrupt received, stopping...")
event.stop()