modify scripts

This commit is contained in:
oscarz
2025-03-17 11:08:13 +08:00
parent e6327fbe73
commit f43cd53159
177 changed files with 5 additions and 178173 deletions

View File

@ -0,0 +1,9 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_market_snapshot(['SH.600000', 'HK.00700'])
if ret == RET_OK:
print(data)
else:
print('error:', data)
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

View File

@ -0,0 +1,62 @@
import pymysql
import pandas as pd
from futu import *
import logging
from config import db_config # 引用config.py中的数据库配置
# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s - %(message)s')
logger = logging.getLogger()
# 数据库连接函数
def connect_to_db():
return pymysql.connect(**db_config)
# 从sp300表中获取所有股票代码
def fetch_sp300_codes(connection):
query = "SELECT code FROM hs300"
return pd.read_sql(query, connection)
# 获取市场快照并保存到 CSV 文件
def get_market_snapshot_and_save_to_csv(stock_codes, output_file):
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_market_snapshot(stock_codes)
if ret == RET_OK:
logger.info(f"Successfully fetched market snapshot for {len(stock_codes)} codes.")
# 将数据写入CSV文件
data.to_csv(output_file, index=False)
logger.info(f"Snapshot data saved to {output_file}")
else:
logger.error(f"Error fetching market snapshot: {data}")
quote_ctx.close()
# 主函数
def main():
try:
# 连接数据库
connection = connect_to_db()
# 从 sp300 表中获取所有的股票代码
sp300_codes_df = fetch_sp300_codes(connection)
# 提取股票代码列表
stock_codes = sp300_codes_df['code'].tolist()
if not stock_codes:
logger.warning("No stock codes found in sp300 table.")
return
# 获取市场快照并保存到 CSV 文件
output_file = "market_snapshot.csv"
get_market_snapshot_and_save_to_csv(stock_codes, output_file)
except Exception as e:
logger.error(f"An error occurred: {e}")
finally:
if connection:
connection.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,18 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data, page_req_key = quote_ctx.request_history_kline('HK.00700', autype=AuType.NONE, start='2021-10-03', end='2021-11-08', max_count=50) # 每页5个请求第一页
if ret == RET_OK:
print(data)
print(data['code'][0]) # 取第一条的股票代码
print(data['close'].values.tolist()) # 第一页收盘价转为 list
else:
print('error:', data)
while page_req_key != None: # 请求后面的所有结果
print('*************************************')
ret, data, page_req_key = quote_ctx.request_history_kline('HK.00700', start='2024-04-11', end='2024-06-18', max_count=50, page_req_key=page_req_key) # 请求翻页后的数据
if ret == RET_OK:
print(data)
else:
print('error:', data)
print('All pages are finished!')
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

View File

@ -0,0 +1,12 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_user_security("全部")
if ret == RET_OK:
print(data)
if data.shape[0] > 0: # 如果自选股列表不为空
print(data['code'][0]) # 取第一条的股票代码
print(data['code'].values.tolist()) # 转为 list
else:
print('error:', data)
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

View File

@ -0,0 +1,11 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_plate_list(Market.HK, Plate.CONCEPT)
if ret == RET_OK:
print(data)
print(data['plate_name'][0]) # 取第一条的板块名称
print(data['plate_name'].values.tolist()) # 转为 list
else:
print('error:', data)
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

View File

@ -0,0 +1,11 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_plate_stock('SH.LIST3000005')
if ret == RET_OK:
print(data)
#print(data['stock_name'][0]) # 取第一条的股票名称
#print(data['stock_name'].values.tolist()) # 转为 list
else:
print('error:', data)
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

11
src/sample/get_rehab.py Normal file
View File

@ -0,0 +1,11 @@
from futu import *
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
ret, data = quote_ctx.get_rehab("US.AAPL")
if ret == RET_OK:
print(data)
print(data['ex_div_date'][0]) # 取第一条的除权除息日
print(data['ex_div_date'].values.tolist()) # 转为 list
else:
print('error:', data)
quote_ctx.close() # 结束后记得关闭当条连接,防止连接条数用尽

View File

@ -0,0 +1,28 @@
import yfinance as yf
import pandas as pd
code = 'KDP'
# 获取AAPL的股票数据
stock = yf.Ticker(code)
# 获取过去十年的日K线数据前复权
hist_data = stock.history(period="10y", auto_adjust=True)
print (hist_data['Close'].resample('Y').last().pct_change)
# 打印数据前几行
print(hist_data.head())
# 保存到CSV文件
hist_data.to_csv(f"{code}_10year_data_adjust.csv")
# 获取过去十年的日K线数据不复权
hist_data = stock.history(period="10y", auto_adjust=False)
# 打印数据前几行
print(hist_data.head())
# 保存到CSV文件
hist_data.to_csv(f"{code}_10year_data.csv")

View File

@ -0,0 +1,17 @@
import yfinance as yf
import pandas as pd
from datetime import datetime, timedelta
# 获取当前日期
end_date = datetime.today().strftime('%Y-%m-%d')
# 获取十年前的日期
start_date = (datetime.today() - timedelta(days=365*10)).strftime('%Y-%m-%d')
# 下载 AAPL 股票数据
data = yf.download('AAPL', start=start_date, end=end_date)
# 将数据保存为 CSV 文件
data.to_csv('AAPL.csv')
print(f"Downloaded AAPL stock data from {start_date} to {end_date} and saved to AAPL.csv")