From 9e419e8cc17a824b33c2bf5318246d26db509ae5 Mon Sep 17 00:00:00 2001 From: josephwang Date: Fri, 7 Jun 2024 17:53:22 +0800 Subject: [PATCH] 0607 update using database --- TPM.py | 32 +++++++++++++++++++++++++++++--- config.py | 10 ++++++++++ function_calling.py | 2 +- 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 config.py diff --git a/TPM.py b/TPM.py index c759769..ba2b4a4 100644 --- a/TPM.py +++ b/TPM.py @@ -4,7 +4,8 @@ import numpy as np import pandas as pd from scipy.optimize import minimize import yfinance as yf - +import psycopg2 +from config import SQL_CONFIG class MVO(object): @staticmethod def portfolio_info(w, ret, market_ret, rf=0): @@ -188,13 +189,38 @@ def get_Data(tickers,start_date,end_date): all_data_cleaned.set_index('Date', inplace=True) all_data_cleaned.index = pd.to_datetime(all_data_cleaned.index, format='%Y-%m-%d') return all_data_cleaned - +def get_stock(stock_list: list,start_date , end_date): + conn = psycopg2.connect(**SQL_CONFIG) + sql1="SELECT ticker, date, price FROM stock_price where ticker = ANY(%s)" + sql2="SELECT ticker, date, price FROM stock_price_tw where ticker = ANY(%s) ;" + tw = [] + us = [] + for stock in stock_list: + if stock[0].isdigit(): + tw.append(stock) + else: + us.append(stock) + with conn: + with conn.cursor() as curs: + curs.execute(sql1, (us,)) + data_us= curs.fetchall() + curs.execute(sql2, (tw,)) + data_tw= curs.fetchall() + data = data_us+data_tw + dfStock = pd.DataFrame(data, columns=['ticker', 'date', 'price']) + dfStock['date'] = pd.to_datetime(dfStock['date']) + dfStock = dfStock.drop_duplicates() + g = dfStock.groupby('ticker') + port = pd.concat([g.get_group(t).set_index('date')['price'] for t in stock_list], axis=1, join='inner') + port.columns=stock_list + df = port.loc[start_date:end_date] + return df def main(tickers, role, start_date, end_date, lookback, backtest, gamma = 0): try: - data = get_Data(tickers,start_date,end_date) + data = get_stock(tickers,start_date,end_date) except: print("股票資料不合") return False diff --git a/config.py b/config.py new file mode 100644 index 0000000..853b2fd --- /dev/null +++ b/config.py @@ -0,0 +1,10 @@ + + + +SQL_CONFIG = dict( + database="portfolio_platform", + user="postgres", + host="localhost", + port="5432", + password="password" +) \ No newline at end of file diff --git a/function_calling.py b/function_calling.py index bfdb04c..75e8eb0 100644 --- a/function_calling.py +++ b/function_calling.py @@ -114,6 +114,6 @@ def backest_main(query): result_messages = chat_completion_request(sec_message) return result_messages.choices[0].message.content -query = "我想要使用GOOGLE和台積電來進行最大夏普比率2019/7/1至2023/9/22的回測" +query = "我想要使用GOOGLE和台積電來進行最大夏普比率2022/7/1至2024/6/01的回測" article = backest_main(query) print(article) \ No newline at end of file