0607 update using database

master
josephwang 10 months ago
parent 5d4de19c39
commit 9e419e8cc1
  1. 32
      TPM.py
  2. 10
      config.py
  3. 2
      function_calling.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

@ -0,0 +1,10 @@
SQL_CONFIG = dict(
database="portfolio_platform",
user="postgres",
host="localhost",
port="5432",
password="password"
)

@ -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)
Loading…
Cancel
Save