|
|
|
@ -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 |
|
|
|
|