2020年6月11日 星期四

自訂策略回測績效 -每天用前一天的收盤價下單 1 股 直到沒有資金可以購買 然後用前一天的收盤價賣出 直到可以賣出

import csv
import requests
import math
import pandas as pd # 引用套件並縮寫為 pd
import datetime
import time
import json
import numpy as np
from io import StringIO
import matplotlib.pyplot as plt
import pytz
from sklearn import preprocessing


def getStockPrice(stockName):
p = math.floor(time.time())
period1 = "0" # 2017/06/01
period2 = str(math.floor(time.time()))
url = (
"https://query1.finance.yahoo.com/v7/finance/download/"
+ stockName
+ "?period1="
+ period1
+ "&period2="
+ period2
+ "&interval=1d&events=history"
)
response = requests.get(url)
data = pd.read_csv(StringIO(response.text), index_col="Date")
return data


# print(data.index)
# print(type(data.index))

# 持股策略
# 初期資金 usd 2000
# step 1 每天用前一天的收盤價下單 1 股 直到沒有資金可以購買
# step 2 然後用前一天的收盤價賣出 直到可以賣出
# 然後重複 step 1 , 2
def stockStrategy(stockName, initialFund):
data = getStockPrice(stockName)

cash = initialFund
buyQty = 1
stockWarehouse = 0
theValue = {} # 總淨值
theStockValue = {} # 只計算股票帳面價值
tradeIndex = data.index

oneTimebidValue = {} # 只在期初下單買進 之後就不管了
oneTimebidstockWarehouse = initialFund // data.loc[tradeIndex[0]]["Adj Close"]
oneTimebidCash = (
initialFund - oneTimebidstockWarehouse * data.loc[tradeIndex[0]]["Adj Close"]
)

volum = {}

theDay = 1
Day = 0
for theDay in tradeIndex:
Day += 1
print(type(tradeIndex.size), tradeIndex.size, Day)
if Day >= tradeIndex.size:
break
lastDay = Day - 1
# print(tradeIndex[lastDay])
# print(data.loc[tradeIndex[lastDay]]["Adj Close"])
tradePrice = data.loc[tradeIndex[lastDay]]["Adj Close"]
if cash > tradePrice * buyQty:
if tradePrice < data.loc[tradeIndex[Day]]["Adj Close"]:
cash -= tradePrice * buyQty
stockWarehouse += buyQty
else:
if tradePrice > data.loc[tradeIndex[Day]]["Adj Close"]:
cash += tradePrice * stockWarehouse
stockWarehouse = 0
theValue[tradeIndex[Day]] = (
cash + stockWarehouse * data.loc[tradeIndex[Day]]["Adj Close"]
)
theStockValue[tradeIndex[Day]] = (
stockWarehouse * data.loc[tradeIndex[Day]]["Adj Close"]
)
oneTimebidValue[tradeIndex[Day]] = (
oneTimebidstockWarehouse * data.loc[tradeIndex[Day]]["Adj Close"]
) + oneTimebidCash
volum[tradeIndex[Day]] = data.loc[tradeIndex[Day]]["Volume"]

# print(theValue)
timeLine = list(theValue.keys())
values = list(theValue.values())
# print(timeLine, values)
plt.plot(timeLine, values)
# print(theValue)

timeLine = list(oneTimebidValue.keys())
values = list(oneTimebidValue.values())
# print(timeLine, values)
plt.plot(timeLine, values)
plt.show()


stockName = "V"
initialFund = 2000
stockStrategy(stockName, initialFund)

# us = pytz.timezone("US/Pacific")
# today = datetime.datetime.now(tz=us)
# yesterday = today - datetime.timedelta(days=1)
# yesterday = yesterday.strftime("%Y-%m-%d")
# print(yesterday, type(yesterday))