新增了new_user_stategy的model,重构了数据库操作代码,转化为tortoise ORM

This commit is contained in:
xlmessage 2025-02-17 10:20:38 +08:00
parent 62e0ab2da7
commit ce5856ae89
60 changed files with 185 additions and 600 deletions

Binary file not shown.

@ -1,51 +1,21 @@
from fastapi import APIRouter, Query, FastAPI, Body from fastapi import APIRouter, Query, Body
from starlette.middleware.cors import CORSMiddleware
import akshare as ak import akshare as ak
import pymysql
import json import json
from pydantic import BaseModel from pydantic import BaseModel
from typing import List, Dict from src.models.user_strategy import *
import math from src.models.new_user_strategy import *
router = APIRouter() # 创建一个 FastAPI 路由器实例 from src.akshare_data.service import *
router = APIRouter() # 创建一个 FastAPI 路由器实例
# 数据库测试 # 数据库测试
@router.get("/userstrategy") @router.get("/userstrategy")
async def userstrategy(): async def userstrategy():
# 创建数据库连接 # 查询 user_id = 100096 的记录
conn = pymysql.connect( query = UserStrategy.filter(user_id=100096) # 使用 Tortoise ORM 的查询方法
host='cqxqg.tech', # MySQL服务器地址 data = await query.all() # 异步获取所有结果
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 使用 execute()方法执行 SQL 查询
# 通配符 *,意思是查询表里所有内容
cursor.execute("select * from user_strategy where user_id = 100096")
# 使用 fetchone() 方法获取一行数据.
# data = cursor.fetchone()
data = cursor.fetchall()
# print(data)
# 关闭数据库连接
cursor.close()
# 将strategy_request字段中的JSON字符串转换为Python字典
for i in range(0, len(data)):
strategy_request = data[i]['strategy_request']
# 将JSON字符串转换为Python字典
data_dict = json.loads(strategy_request)
data[i]['strategy_request'] = data_dict
return data return data
# 定义Pydantic模型 # 定义Pydantic模型
class InfoItem(BaseModel): class InfoItem(BaseModel):
code: str code: str
@ -77,263 +47,122 @@ class MyData(BaseModel):
# 新加的new_user_strategy数据库表 # 新加的new_user_strategy数据库表
@router.post("/newuserstrategy") @router.post("/newuserstrategy")
async def newuserstrategy(strategy: StrategyRequest = Body(...)): async def newuserstrategy(strategy: StrategyRequest = Body(...)):
# 创建数据库连接 # 获取请求数据
conn = pymysql.connect(
host='cqxqg.tech', # MySQL服务器地址
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# cursor1 = conn.cursor()
# cursor2 = conn.cursor()
# --------------------new_user_strategy数据------------------
# SQL 查询语句
sql1 = "SELECT strategy_name FROM new_user_strategy WHERE id = %s"
# 执行查询
cursor.execute(sql1, ('100096',))
# 获取所有数据
result1 = cursor.fetchall()
# 提取 strategy_name 列并转换为列表
strategy_names1 = [row['strategy_name'] for row in result1]
# print(strategy_names1)
# --------------------user_strategy数据------------------
# SQL 查询语句
sql2 = "SELECT strategy_name FROM user_strategy WHERE user_id = %s"
# 执行查询
cursor.execute(sql2, ('100096',))
# 获取所有数据
result2 = cursor.fetchall()
# 提取 strategy_name 列并转换为列表
strategy_names2 = [row['strategy_name'] for row in result2]
# print(strategy_names2)
# --------------------获取整个请求数据--------------------
request_data = strategy.dict() request_data = strategy.dict()
# print(request_data) # 查询 new_user_strategy 表中是否存在相同的 id 和 strategy_name
existing_strategy = await NewUserStrategy.filter(
id=request_data['id'], strategy_name=request_data['strategy_name']
).first()
if existing_strategy:
# 如果已存在,直接返回提示信息
return {"message": "该策略已存在"}
# 查询 user_strategy 表中是否存在相同的 user_id 和 strategy_name
existing_user_strategy = await UserStrategy.filter(
user_id=request_data['id'], strategy_name=request_data['strategy_name']
).first()
if existing_user_strategy:
# 如果已存在,直接返回提示信息
return {"message": "该策略已在 user_strategy 表中存在"}
# 准备SQL插入语句注意没有包含id列因为它可能是自动递增的
sql = "INSERT INTO new_user_strategy (id, strategy_name, message, info) VALUES (%s, %s, %s, %s)"
# 要插入的数据(确保数据类型与数据库表列匹配)
# 将 message 和 info 转换为 JSON 字符串 # 将 message 和 info 转换为 JSON 字符串
import json
message_json = json.dumps(request_data['message']) message_json = json.dumps(request_data['message'])
info_json = json.dumps(request_data['info']) info_json = json.dumps(request_data['info'])
values = (request_data['id'], request_data['strategy_name'], message_json, info_json)
# 是否进行写入数据库表中 # 创建新的 new_user_strategy 记录
set_strategy_names1 = set(strategy_names1) new_strategy = await NewUserStrategy.create(
set_strategy_names2 = set(strategy_names2) id=request_data['id'],
strategy_name=request_data['strategy_name'],
message=message_json,
info=info_json
)
if request_data['strategy_name'] in strategy_names1: return {"message": "数据插入成功", "strategy_id": new_strategy.id}
# print("信息已存在")
conn.close()
else:
# 执行SQL语句
cursor.execute(sql, values)
# 提交事务到数据库执行
conn.commit()
print("数据插入成功")
# 关闭数据库连接
conn.close()
return {"message": "数据插入成功"}
# for i in range(0, len(result2)):
# if result2[i] not in strategy_names1:
# # 执行SQL语句
# cursor.execute(sql, values)
# # 提交事务到数据库执行
# conn.commit()
# print("数据插入成功")
# # 关闭数据库连接
# conn.close()
# return {"message": "数据插入成功"}
# conn.close()
@router.post("/newadd") @router.post("/newadd")
async def newadd(strategy: StrategyRequest = Body(...)): async def newadd(strategy: StrategyRequest = Body(...)):
conn = pymysql.connect( # 获取请求数据
host='cqxqg.tech', # MySQL服务器地址
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# SQL 查询语句
sql1 = "SELECT strategy_name FROM new_user_strategy WHERE id = %s"
# 执行查询
cursor.execute(sql1, ('100096',))
# 获取所有数据
result1 = cursor.fetchall()
# 获取整个请求数据
request_data = strategy.dict() request_data = strategy.dict()
print(request_data) # 查询 new_user_strategy 表中是否存在相同的 id 和 strategy_name
existing_strategy = await NewUserStrategy.filter(
id=request_data['id'], strategy_name=request_data['strategy_name']
).first()
import json if existing_strategy:
message_json = json.dumps(request_data['message']) # 如果已存在,返回提示信息
info_json = json.dumps(request_data['info'])
print(result1)
for item in result1:
if request_data['strategy_name'] == item['strategy_name']:
return { return {
"code": 204, "code": 204,
"message": "该分组已经存在" "message": "该分组已经存在"
} }
sql = "INSERT INTO new_user_strategy (id, strategy_name, message, info) VALUES (%s, %s, %s, %s)" # 将 message 和 info 转换为 JSON 字符串
# # 执行 SQL message_json = json.dumps(request_data['message'])
cursor.execute(sql, (request_data["id"], request_data['strategy_name'], message_json, info_json)) info_json = json.dumps(request_data['info'])
#
# # 提交事务到数据库执行 # 创建新的 new_user_strategy 记录
conn.commit() await NewUserStrategy.create(
# print("更新数据成功") id=request_data['id'],
# 关闭数据库连接 strategy_name=request_data['strategy_name'],
conn.close() message=message_json,
info=info_json
)
return { return {
"code": 200, "code": 200,
"message": "新建分组成功!" "message": "新建分组成功!"
} }
# 获取数据 # 获取数据
@router.get("/newget") @router.get("/newget")
async def newget(): async def newget():
# 创建数据库连接 # 查询 new_user_strategy 表中 id = 100096 的所有记录
conn = pymysql.connect( query = NewUserStrategy.filter(id=100096)
host='cqxqg.tech', # MySQL服务器地址 data = await query.all()
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 使用 execute()方法执行 SQL 查询
# 通配符 *,意思是查询表里所有内容
cursor.execute("select * from new_user_strategy where id = 100096")
# 使用 fetchone() 方法获取一行数据.
# data = cursor.fetchone()
data = cursor.fetchall()
# print(data)
# 关闭数据库连接
cursor.close()
# 将strategy_request字段中的JSON字符串转换为Python字典
for i in range(0, len(data)):
strategy_request1 = data[i]['message']
strategy_request2 = data[i]['info']
# 将JSON字符串转换为Python字典
data_dict1 = json.loads(strategy_request1)
data_dict2 = json.loads(strategy_request2)
data[i]['message'] = data_dict1
data[i]['info'] = data_dict2
return { return {
"code": 200, "code": 200,
"data": data "data": data
} }
# 新增分组 # 新增分组
@router.post("/newupdata") @router.post("/newupdata")
async def newupdata(strategy: StrategyRequest = Body(...)): async def newupdata(strategy: StrategyRequest = Body(...)):
# 创建数据库连接 # 获取请求数据
conn = pymysql.connect(
host='cqxqg.tech', # MySQL服务器地址
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 获取整个请求数据
request_data = strategy.dict() request_data = strategy.dict()
print(request_data)
import json # 将 message 和 info 转换为 JSON 字符串
message_json = json.dumps(request_data['message']) message_json = json.dumps(request_data['message'])
info_json = json.dumps(request_data['info']) info_json = json.dumps(request_data['info'])
# 查询是否存在对应的 strategy_name
existing_strategy = await NewUserStrategy.filter(strategy_name=request_data['strategy_name']).first()
if not existing_strategy:
return {"message": "不存在"}
# SQL 语句 # 更新记录
sql = """ await NewUserStrategy.filter(strategy_name=request_data['strategy_name']).update(
UPDATE new_user_strategy message=message_json,
SET message = %s, info = %s info=info_json
WHERE strategy_name = %s; )
""" return {"message": "更新成功"}
# 执行 SQL
cursor.execute(sql, (message_json, info_json, request_data['strategy_name']))
# 提交事务到数据库执行
conn.commit()
print("更新数据成功")
# 关闭数据库连接
conn.close()
return "更新成功"
class delItem(BaseModel): class delItem(BaseModel):
strategy_name: str strategy_name: str
# 删除分组 # 删除分组
@router.post("/newdel") @router.post("/newdel")
async def newdel(delitem: delItem): async def newdel(delitem: delItem):
delitem = delitem.strategy_name strategy_name = delitem.strategy_name
# 创建数据库连接
conn = pymysql.connect(
host='cqxqg.tech', # MySQL服务器地址
user='wangche', # MySQL用户名
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor # 删除 new_user_strategy 表中的记录
cursor = conn.cursor() delete_count_new = await NewUserStrategy.filter(strategy_name=strategy_name).delete()
sql1 = "DELETE FROM new_user_strategy WHERE strategy_name = %s" # 删除 user_strategy 表中的记录
delete_count_user = await UserStrategy.filter(strategy_name=strategy_name).delete()
sql2 = "DELETE FROM user_strategy WHERE strategy_name = %s"
cursor.execute(sql1, (delitem,))
cursor.execute(sql2, (delitem,))
# 提交事务到数据库执行
conn.commit()
print("数据删除成功")
# 关闭数据库连接
conn.close()
return "删除成功"
# 检查是否删除成功
if delete_count_new == 0 and delete_count_user == 0:
return {"message": "未找到指定的策略名称"}
return {"message": "删除成功"}
@router.get("/newmodify") @router.get("/newmodify")
@ -341,42 +170,18 @@ async def newmodify(
strategy_name: str = Query(..., description="原始值"), strategy_name: str = Query(..., description="原始值"),
new_strategy_name: str = Query(..., description="更改值") new_strategy_name: str = Query(..., description="更改值")
): ):
print(strategy_name) # 检查是否存在原始 strategy_name
print(new_strategy_name) existing_strategy = await NewUserStrategy.filter(strategy_name=strategy_name).first()
# return "success" if not existing_strategy:
# pass return {"message": "原始策略名称不存在"}
# 创建数据库连接 # 检查新策略名称是否已存在
conn = pymysql.connect( existing_new_strategy = await NewUserStrategy.filter(strategy_name=new_strategy_name).first()
host='cqxqg.tech', # MySQL服务器地址 if existing_new_strategy:
user='wangche', # MySQL用户名 return {"message": "新策略名称已存在"}
password='fN7sXX8saiQKXWbG', # MySQL密码
database='wangche', # 要连接的数据库名
port=3308,
charset='utf8mb4', # 字符集,确保支持中文等
cursorclass=pymysql.cursors.DictCursor # 使用字典形式返回结果
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 更新 strategy_name # 更新 strategy_name
update_sql = "UPDATE new_user_strategy SET strategy_name = %s WHERE strategy_name = %s" await NewUserStrategy.filter(strategy_name=strategy_name).update(strategy_name=new_strategy_name)
cursor.execute(update_sql, (new_strategy_name, strategy_name))
# 提交事务到数据库执行
conn.commit()
print("重命名成功")
# 关闭数据库连接
conn.close()
return "重命名成功"
# 侧边栏webview数据
@router.post("/asidestrinfo/")
async def asidestrinfo():
pass
return {"message": "重命名成功"}
# 股票数据 # 股票数据
@ -388,69 +193,29 @@ async def stock(
end_date: str = Query(..., description="结束日期"), end_date: str = Query(..., description="结束日期"),
): ):
# 获取股票日线行情数据 # 获取股票日线行情数据
# print(symbol, start_date, end_date)
# print(symbol)
global stock_data global stock_data
try: try:
stock_zh_a_daily_df = ak.stock_zh_a_daily(symbol=symbol, start_date=start_date, end_date=end_date, adjust="qfq") stock_zh_a_daily_df = ak.stock_zh_a_daily(symbol=symbol, start_date=start_date, end_date=end_date, adjust="qfq")
# 获取所有的code dates_list = stock_zh_a_daily_df['date'].tolist()
all_dates = stock_zh_a_daily_df['date'] opens_list = clean_data(stock_zh_a_daily_df['open'].tolist())
# 如果你想要一个列表而不是Pandas Series closes_list = clean_data(stock_zh_a_daily_df['close'].tolist())
dates_list = all_dates.tolist() highs_list = clean_data(stock_zh_a_daily_df['high'].tolist())
lows_list = clean_data(stock_zh_a_daily_df['low'].tolist())
volumes_list = clean_data(stock_zh_a_daily_df['volume'].tolist())
amounts_list = clean_data(stock_zh_a_daily_df['amount'].tolist())
all_opens = stock_zh_a_daily_df['open']
opens_list = all_opens.tolist()
cleaned_opens_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in opens_list
]
all_closes = stock_zh_a_daily_df['close']
close_list = all_closes.tolist()
cleaned_close_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in close_list
]
all_highs = stock_zh_a_daily_df['high']
high_list = all_highs.tolist()
cleaned_high_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in high_list
]
all_lows = stock_zh_a_daily_df['low']
low_list = all_lows.tolist()
cleaned_low_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in low_list
]
all_volumes = stock_zh_a_daily_df['volume']
volume_list = all_volumes.tolist()
cleaned_volume_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in volume_list
]
all_amounts = stock_zh_a_daily_df['amount']
amount_lists = all_amounts.tolist()
cleaned_amount_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amount_lists
]
global stock_data global stock_data
stock_data = { stock_data = {
"amount": cleaned_amount_list, "amount": amounts_list,
"close": cleaned_close_list, "close": closes_list,
"date": dates_list, "date": dates_list,
"high": cleaned_high_list, "high": highs_list,
"low": cleaned_low_list, "low": lows_list,
"open": cleaned_opens_list, "open": opens_list,
"outstanding_share": [], "outstanding_share": [],
"turnover": [], "turnover": [],
"volume": cleaned_volume_list "volume": volumes_list
} }
except Exception as e: except Exception as e:
print(e) print(e)
@ -494,35 +259,14 @@ async def kdata():
@router.get("/ganggudata") @router.get("/ganggudata")
async def ganggudata(): async def ganggudata():
stock_hk_spot_em_df = ak.stock_hk_spot_em() stock_hk_spot_em_df = ak.stock_hk_spot_em()
# print(stock_hk_spot_em_df) codes_list = stock_hk_spot_em_df['代码'].tolist()
# 获取所有的code names_list = stock_hk_spot_em_df['名称'].tolist()
all_codes = stock_hk_spot_em_df['代码'] price_list = clean_data(stock_hk_spot_em_df['最新价'].tolist())
# 如果你想要一个列表而不是Pandas Series amplitudes_list = clean_data(stock_hk_spot_em_df['涨跌幅'].tolist())
codes_list = all_codes.tolist()
all_names = stock_hk_spot_em_df['名称']
names_list = all_names.tolist()
all_prices = stock_hk_spot_em_df['最新价']
price_list = all_prices.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_price_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in price_list
]
all_amplitudes = stock_hk_spot_em_df['涨跌幅']
amplitudes_list = all_amplitudes.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_amplitudes_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amplitudes_list
]
# 返回的数据 # 返回的数据
ggstocking = [] ggstocking = []
for i in range(9): for i in range(9):
if cleaned_price_list[i] >= 0: if price_list[i] >= 0:
flag = True flag = True
else: else:
flag = False flag = False
@ -530,9 +274,9 @@ async def ganggudata():
'code': codes_list[i], 'code': codes_list[i],
'name': names_list[i], 'name': names_list[i],
'market': '港股', 'market': '港股',
'newprice': cleaned_price_list[i], 'newprice': price_list[i],
'amplitudetype': flag, 'amplitudetype': flag,
'amplitude': cleaned_amplitudes_list[i], 'amplitude': amplitudes_list[i],
'type': 'ganggu' 'type': 'ganggu'
}) })
@ -549,64 +293,24 @@ async def ganggudataK(
try: try:
stock_hk_hist_df = ak.stock_hk_hist(symbol=symbol, period="daily", start_date=start_date, end_date=end_date, stock_hk_hist_df = ak.stock_hk_hist(symbol=symbol, period="daily", start_date=start_date, end_date=end_date,
adjust="") adjust="")
dates_list = stock_hk_hist_df['日期'].tolist()
# 获取所有的code opens_list = clean_data(stock_hk_hist_df['开盘'].tolist())
all_dates = stock_hk_hist_df['日期'] close_list = clean_data(stock_hk_hist_df['收盘'].tolist())
# 如果你想要一个列表而不是Pandas Series high_list = clean_data(stock_hk_hist_df['最高'].tolist())
dates_list = all_dates.tolist() low_list = clean_data(stock_hk_hist_df['最低'].tolist())
volume_list = clean_data(stock_hk_hist_df['成交量'].tolist())
all_opens = stock_hk_hist_df['开盘'] amount_list = clean_data(stock_hk_hist_df['成交额'].tolist())
opens_list = all_opens.tolist()
cleaned_opens_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in opens_list
]
all_closes = stock_hk_hist_df['收盘']
close_list = all_closes.tolist()
cleaned_close_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in close_list
]
all_highs = stock_hk_hist_df['最高']
high_list = all_highs.tolist()
cleaned_high_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in high_list
]
all_lows = stock_hk_hist_df['最低']
low_list = all_lows.tolist()
cleaned_low_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in low_list
]
all_volumes = stock_hk_hist_df['成交量']
volume_list = all_volumes.tolist()
cleaned_volume_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in volume_list
]
all_amounts = stock_hk_hist_df['成交额']
amount_list = all_amounts.tolist()
cleaned_amount_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amount_list
]
global stock_data global stock_data
stock_data = { stock_data = {
"amount": cleaned_amount_list, "amount": amount_list,
"close": cleaned_close_list, "close": close_list,
"date": dates_list, "date": dates_list,
"high": cleaned_high_list, "high": high_list,
"low": cleaned_low_list, "low": low_list,
"open": cleaned_opens_list, "open": opens_list,
"outstanding_share": [], "outstanding_share": [],
"turnover": [], "turnover": [],
"volume": cleaned_volume_list "volume": volume_list
} }
except Exception as e: except Exception as e:
print(e) print(e)
@ -624,55 +328,38 @@ async def ganggudataK(
finally: finally:
return {"message": stock_data} return {"message": stock_data}
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
# 美股代码数据 # 美股代码数据
@router.get("/meigudata") @router.get("/meigudata")
async def meigudata(): async def meigudata():
stock_us_spot_em_df = ak.stock_us_spot_em() stock_us_spot_em_df = ak.stock_us_spot_em()
# print(stock_us_spot_em_df) codes_list = stock_us_spot_em_df['代码'].tolist()
all_codes = stock_us_spot_em_df['代码'] names_list = stock_us_spot_em_df['名称'].tolist()
# 如果你想要一个列表而不是Pandas Series price_list = clean_data(stock_us_spot_em_df['最新价'].tolist())
codes_list = all_codes.tolist() amplitudes_list = clean_data(stock_us_spot_em_df['涨跌幅'].tolist())
all_names = stock_us_spot_em_df['名称']
names_list = all_names.tolist()
all_prices = stock_us_spot_em_df['最新价']
price_list = all_prices.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_price_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in price_list
]
all_amplitudes = stock_us_spot_em_df['涨跌幅']
amplitudes_list = all_amplitudes.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_amplitudes_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amplitudes_list
]
# 返回的数据 # 返回的数据
mgstocking = [] mgstocking = []
for i in range(9): for i in range(9):
if cleaned_price_list[i] >= 0: if price_list[i] >= 0:
flag = True flag = True
else: else:
flag = False flag = False
mgstocking.append({ mgstocking.append({
'code': codes_list[i], 'code': codes_list[i],
'name': names_list[i], 'name': names_list[i],
'market': '', 'market': '美股',
'newprice': cleaned_price_list[i], 'newprice': price_list[i],
'amplitudetype': flag, 'amplitudetype': flag,
'amplitude': cleaned_amplitudes_list[i], 'amplitude': amplitudes_list[i],
'type': 'meigu' 'type': 'meigu'
}) })
# 返回清理后的列表 # 返回清理后的列表
return mgstocking return mgstocking
# 美股K线图历史数据 # 美股K线图历史数据
@router.get("/meigudataK") @router.get("/meigudataK")
async def meigudataK( async def meigudataK(
@ -683,64 +370,25 @@ async def meigudataK(
try: try:
stock_us_hist_df = ak.stock_us_hist(symbol=symbol, period="daily", start_date=start_date, end_date=end_date, stock_us_hist_df = ak.stock_us_hist(symbol=symbol, period="daily", start_date=start_date, end_date=end_date,
adjust="qfq") adjust="qfq")
dates_list = stock_us_hist_df['日期'].tolist()
opens_list = stock_us_hist_df['开盘'].tolist()
close_list = clean_data(stock_us_hist_df['收盘'].tolist())
high_list = clean_data(stock_us_hist_df['最高'].tolist())
low_list = clean_data(stock_us_hist_df['最低'].tolist())
volume_list = clean_data(stock_us_hist_df['成交量'].tolist())
amount_list = clean_data(stock_us_hist_df['成交额'].tolist())
# 获取所有的code
all_dates = stock_us_hist_df['日期']
# 如果你想要一个列表而不是Pandas Series
dates_list = all_dates.tolist()
all_opens = stock_us_hist_df['开盘']
opens_list = all_opens.tolist()
cleaned_opens_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in opens_list
]
all_closes = stock_us_hist_df['收盘']
close_list = all_closes.tolist()
cleaned_close_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in close_list
]
all_highs = stock_us_hist_df['最高']
high_list = all_highs.tolist()
cleaned_high_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in high_list
]
all_lows = stock_us_hist_df['最低']
low_list = all_lows.tolist()
cleaned_low_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in low_list
]
all_volumes = stock_us_hist_df['成交量']
volume_list = all_volumes.tolist()
cleaned_volume_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in volume_list
]
all_amounts = stock_us_hist_df['成交额']
amount_list = all_amounts.tolist()
cleaned_amount_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amount_list
]
global stock_data global stock_data
stock_data = { stock_data = {
"amount": cleaned_amount_list, "amount": amount_list,
"close": cleaned_close_list, "close": close_list,
"date": dates_list, "date": dates_list,
"high": cleaned_high_list, "high": high_list,
"low": cleaned_low_list, "low": low_list,
"open": cleaned_opens_list, "open": opens_list,
"outstanding_share": [], "outstanding_share": [],
"turnover": [], "turnover": [],
"volume": cleaned_volume_list "volume": volume_list
} }
except Exception as e: except Exception as e:
print(e) print(e)
@ -766,59 +414,26 @@ async def hushendata():
stock_zh_a_spot_df = ak.stock_kc_a_spot_em() stock_zh_a_spot_df = ak.stock_kc_a_spot_em()
except Exception as e: except Exception as e:
print(e) print(e)
# print(stock_zh_a_spot_df) codes_list = stock_zh_a_spot_df['代码'].tolist()
all_codes = stock_zh_a_spot_df['代码'] names_list = stock_zh_a_spot_df['名称'].tolist()
# 如果你想要一个列表而不是Pandas Series price_list = clean_data(stock_zh_a_spot_df['最新价'].tolist())
codes_list = all_codes.tolist() amplitudes_list = clean_data(stock_zh_a_spot_df['涨跌幅'].tolist())
all_names = stock_zh_a_spot_df['名称']
names_list = all_names.tolist()
all_prices = stock_zh_a_spot_df['最新价']
price_list = all_prices.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_price_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in price_list
]
all_amplitudes = stock_zh_a_spot_df['涨跌幅']
amplitudes_list = all_amplitudes.tolist()
# 清理非法浮点数值NaN, Infinity, -Infinity
cleaned_amplitudes_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amplitudes_list
]
# 返回的数据 # 返回的数据
hsstocking = [] hsstocking = []
# for i in range(len(codes_list)):
# if cleaned_price_list[i] >= 0:
# flag = True
# else:
# flag = False
# hsstocking.append({
# 'code': codes_list[i],
# 'name': names_list[i],
# 'market': '港股',
# 'newprice': cleaned_price_list[i],
# 'amplitudetype': flag,
# 'amplitude': cleaned_amplitudes_list[i],
# })
for i in range(9): for i in range(9):
if cleaned_price_list[i] >= 0: if price_list[i] >= 0:
flag = True flag = True
else: else:
flag = False flag = False
hsstocking.append({ hsstocking.append({
'code': codes_list[i], 'code': codes_list[i],
'name': names_list[i], 'name': names_list[i],
'market': '港股', 'market': '沪深',
'newprice': cleaned_price_list[i], 'newprice': price_list[i],
'amplitudetype': flag, 'amplitudetype': flag,
'amplitude': cleaned_amplitudes_list[i], 'amplitude': amplitudes_list[i],
'type': 'hushen' 'type': 'hushen'
}) })
@ -834,63 +449,26 @@ async def hushendataK(
stock_zh_a_daily_qfq_df = ak.stock_zh_a_daily(symbol='sh' + symbol, start_date=start_date, end_date=end_date, stock_zh_a_daily_qfq_df = ak.stock_zh_a_daily(symbol='sh' + symbol, start_date=start_date, end_date=end_date,
adjust="qfq") adjust="qfq")
# 获取所有的code
all_dates = stock_zh_a_daily_qfq_df['date']
# 如果你想要一个列表而不是Pandas Series # 如果你想要一个列表而不是Pandas Series
dates_list = all_dates.tolist() dates_list = stock_zh_a_daily_qfq_df['date'].tolist()
opens_list = clean_data(stock_zh_a_daily_qfq_df['open'].tolist())
close_list = clean_data(stock_zh_a_daily_qfq_df['close'].tolist())
high_list = clean_data(stock_zh_a_daily_qfq_df['high'].tolist())
low_list = clean_data(stock_zh_a_daily_qfq_df['low'].tolist())
volume_list = clean_data(stock_zh_a_daily_qfq_df['volume'].tolist())
amount_list = clean_data(stock_zh_a_daily_qfq_df['amount'].tolist())
all_opens = stock_zh_a_daily_qfq_df['open']
opens_list = all_opens.tolist()
cleaned_opens_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in opens_list
]
all_closes = stock_zh_a_daily_qfq_df['close']
close_list = all_closes.tolist()
cleaned_close_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in close_list
]
all_highs = stock_zh_a_daily_qfq_df['high']
high_list = all_highs.tolist()
cleaned_high_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in high_list
]
all_lows = stock_zh_a_daily_qfq_df['low']
low_list = all_lows.tolist()
cleaned_low_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in low_list
]
all_volumes = stock_zh_a_daily_qfq_df['volume']
volume_list = all_volumes.tolist()
cleaned_volume_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in volume_list
]
all_amounts = stock_zh_a_daily_qfq_df['amount']
amount_lists = all_amounts.tolist()
cleaned_amount_list = [
value if not (math.isnan(value) or math.isinf(value)) else 0.00
for value in amount_lists
]
global stock_data global stock_data
stock_data = { stock_data = {
"amount": cleaned_amount_list, "amount": amount_list,
"close": cleaned_close_list, "close": close_list,
"date": dates_list, "date": dates_list,
"high": cleaned_high_list, "high": high_list,
"low": cleaned_low_list, "low": low_list,
"open": cleaned_opens_list, "open": opens_list,
"outstanding_share": [], "outstanding_share": [],
"turnover": [], "turnover": [],
"volume": cleaned_volume_list "volume": volume_list
} }
except Exception as e: except Exception as e:
print(e) print(e)
@ -908,8 +486,3 @@ async def hushendataK(
finally: finally:
return {"message": stock_data} return {"message": stock_data}

@ -1,6 +1,5 @@
from fastapi import FastAPI,Query
from starlette.middleware.cors import CORSMiddleware
import akshare as ak
async def get_day_k_data(): from typing import Dict, List
pass import math
def clean_data(data: List[float]) -> List[float]:
return [value if not (math.isnan(value) or math.isinf(value)) else 0.00 for value in data]

@ -0,0 +1,12 @@
from tortoise import fields
from tortoise.models import Model
class NewUserStrategy(Model):
id = fields.IntField(pk=True)
strategy_name = fields.CharField(max_length=25, null=False)
message = fields.JSONField(null=True)
info = fields.JSONField(null=True)
class Meta:
table = "new_user_strategy"
default_connection = "default"

@ -73,7 +73,8 @@ models = [
"src.models.stock_zhong_zheng_500", "src.models.stock_zhong_zheng_500",
"src.models.stock_guo_zheng_2000", "src.models.stock_guo_zheng_2000",
"src.models.stock_hu_shen_jing_a", "src.models.stock_hu_shen_jing_a",
"src.models.user_strategy" "src.models.user_strategy",
"src.models.new_user_strategy"
] ]