balik zmen uff

This commit is contained in:
David Brazda
2023-11-03 20:49:24 +01:00
parent de5382d04a
commit 0db88b194c
53 changed files with 1693 additions and 514 deletions

View File

@ -0,0 +1,64 @@
# 2 clients for historical data StockHistoricalDataClient (needs keys), CryptoHistoricalDataClient
# 2 clients for real time data CryptoDataStream, StockDataStream
# naimportuju si daneho clienta
from alpaca.data.historical import StockHistoricalDataClient, CryptoHistoricalDataClient
#pokdu pouzivam historicke data(tzn. REST) tak si naimportuju dany request object
from alpaca.data.requests import StockLatestQuoteRequest, StockBarsRequest, StockTradesRequest, StockSnapshotRequest
#objekty se kterymi pak pracuju (jsou soucasi package výše, tady jen informačně)
from alpaca.data import Quote, Trade, Snapshot, Bar
from alpaca.data.models import BarSet, QuoteSet, TradeSet
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from v2realbot.utils.utils import zoneNY
from v2realbot.config import ACCOUNT1_PAPER_API_KEY, ACCOUNT1_PAPER_SECRET_KEY
from config import API_KEY, SECRET_KEY
from alpaca.data.enums import DataFeed
from datetime import datetime, timedelta
import pandas as pd
from rich import print
from collections import defaultdict
from pandas import to_datetime
from msgpack.ext import Timestamp
from v2realbot.utils.historicals import convert_daily_bars
def get_last_close():
pass
def get_todays_open():
pass
##vrati historicke bary v nasem formatu
def get_historical_bars(symbol: str, time_from: datetime, time_to: datetime, timeframe: TimeFrame):
stock_client = StockHistoricalDataClient(ACCOUNT1_PAPER_API_KEY, ACCOUNT1_PAPER_SECRET_KEY, raw_data=True)
bar_request = StockBarsRequest(symbol_or_symbols=symbol,timeframe=timeframe, start=time_from, end=time_to, feed=DataFeed.SIP)
bars: BarSet = stock_client.get_stock_bars(bar_request)
print("puvodni bars", bars["BAC"])
print(bars)
return convert_daily_bars(bars[symbol])
#v initu plnime pozadovana historicka data do historicals[]
#zatim natvrdo
#last 30 days bars
#get 30 days
time_to = datetime.now(tz=zoneNY)
time_from = time_to - timedelta(days=2)
bary = get_historical_bars("BAC", time_from, time_to, TimeFrame.Hour)
print(bary)
historicals = defaultdict(dict)
historicals["30"] = bary
print(historicals)
# stock_client = StockHistoricalDataClient(ACCOUNT1_PAPER_API_KEY, ACCOUNT1_PAPER_SECRET_KEY, raw_data=True)
# snapshotRequest = StockSnapshotRequest(symbol_or_symbols=["BAC"], feed="sip")
# snapshotResponse = stock_client.get_stock_snapshot(snapshotRequest)
# print("snapshot", snapshotResponse)
# snapshotResponse["BAC"]["dailyBar"]

View File

@ -15,3 +15,6 @@ y_interp = spi.interp1d(x, y)
#create plot of x vs. y
#plt.plot(x, y, '-ob')

View File

@ -0,0 +1,5 @@
import numpy as np
atr10 = 11.1
print(np.interp(atr10, [1, 10,11,12], [0, 1,100,1]))

22
testy/fourier.py Normal file
View File

@ -0,0 +1,22 @@
import numpy as np
import scipy.fft as fft
time_series = np.array(prices)
n = len(time_series)
# Compute the Fourier transform
yf = fft(time_series)
xf = np.linspace(0.0, 1.0/(2.0), n//2)
# Compute the Fourier transform
yf = np.abs(fft(time_series))
# Find the corresponding frequencies
frequencies = xf
# Find the corresponding amplitudes
amplitudes = 2.0/n * np.abs(yf[:n//2])
# Interpret the amplitudes and frequencies
for freq, ampl in zip(frequencies, amplitudes):
print(f"Frequency: {freq}, Amplitude: {ampl}")

106
testy/localmaximatest.py Normal file
View File

@ -0,0 +1,106 @@
import numpy as np
import matplotlib.pyplot as plt
from v2realbot.controller.services import get_archived_runner_details_byID
from v2realbot.common.model import RunArchiveDetail
from scipy.signal import argrelextrema
id = "c5ae757f-6bdd-4d1f-84a8-98bdaad65a28"
res, val = get_archived_runner_details_byID(id)
if res < 0:
print(res)
detail = RunArchiveDetail(**val)
# detail.indicators[0]
price_series = np.array(detail.bars["vwap"])
#price_series = detail.bars["vwap"]
timestamps = detail.bars["time"]
prices = []
#TODO pridat k indikatorum convert to numpy, abych mohl pouzivat numpy operace v expressionu
def get_local_maxima_numpy(
series: np.ndarray,
debug=False,
) -> np.ndarray:
"""calculate local maximal point"""
if series.size == 0:
return np.array([])
# Calculate the difference between adjacent elements.
diff = np.diff(series)
# Find the indices of the elements where the difference changes sign from positive to negative.
high_index = np.where((diff[:-1] >= 0) & (diff[1:] < 0))[0] + 1
# Return a NumPy array containing the local maxima.
return high_index#series[high_index]
def get_local_minima_numpy(
series: np.ndarray,
debug=False,
) -> np.ndarray:
"""calculate local maximal point"""
if series.size == 0:
return np.array([])
# Calculate the difference between adjacent elements.
diff = np.diff(series)
# Find the indices of the elements where the difference changes sign from positive to negative.
low_index = np.where((diff[:-1] <= 0) & (diff[1:] > 0))[0] + 1
# Return a NumPy array containing the local maxima.
return low_index#series[high_index]
def get_local_minima(prices):
return prices[-2] if len(prices) >= 3 and prices[-2] > prices[-3] and prices[-2] > prices[-1] else None
# iter_prices = []
# for price in detail.bars["vwap"]:
# iter_prices.append(price)
# get_local_minima(iter_prices)
def calculate_support_resistance(bars, window=5):
lows = np.array(bars['low'])
highs = np.array(bars['high'])
rolling_support = np.minimum.accumulate(lows)[::-1][:window][::-1]
rolling_resistance = np.maximum.accumulate(highs)[::-1][:window][::-1]
return {'rolling_support': rolling_support.tolist(), 'rolling_resistance': rolling_resistance.tolist()}
rolling = calculate_support_resistance(detail.bars, 5)
print(rolling)
# func = "prices[-1] if np.all(prices[-1] > prices[-2:]) else 0"
# #func = "prices[-2] if len(prices) >= 3 and prices[-2] > prices[-3] and prices[-2] > prices[-1] else None"
# for price in price_series:
# prices.append(price)
# print(eval(func))
# maxima_indices = argrelextrema(price_series, np.greater)[0]
# minima_indices = argrelextrema(price_series, np.less)[0]
# # Print the indices of local maxima and minima
# print("Local Maxima Indices:", maxima_indices)
# print("Local Minima Indices:", minima_indices)
print("from new function")
maxima_indices = get_local_maxima_numpy(price_series)
minima_indices = get_local_minima_numpy(price_series)
print("Local Maxima Indices:", maxima_indices)
print("Local Minima Indices:", minima_indices)
# Plot the price series with local maxima and minima
plt.figure(figsize=(10, 6))
plt.plot(range(len(price_series)), price_series, label='Price Series')
plt.scatter(maxima_indices, price_series[maxima_indices], color='r', label='Local Maxima', zorder=5)
plt.scatter(minima_indices, price_series[minima_indices], color='g', label='Local Minima', zorder=5)
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Price Series with Local Maxima and Minima')
plt.legend()
plt.show()

View File

@ -0,0 +1,74 @@
import numpy as np
import matplotlib.pyplot as plt
from v2realbot.controller.services import get_archived_runner_details_byID, preview_indicator_byTOML
from v2realbot.common.model import RunArchiveDetail, InstantIndicator
from scipy.signal import argrelextrema
from v2realbot.utils.utils import AttributeDict, zoneNY, zonePRG, safe_get, dict_replace_value, Store, parse_toml_string, json_serial, is_open_hours, send_to_telegram
##SCAFFOLDING for development of new indicator
runner_id = "7512b097-1f29-4c61-a331-2b1a40fd3f91"
toml = """
#[stratvars.indicators.local_maxik]
type = 'custom'
subtype = 'basestats'
on_confirmed_only = true
cp.lookback = 30
cp.source = 'vwap'
cp.function = 'maxima'
"""
toml = """
type = 'custom'
subtype = 'expression'
on_confirmed_only = true
cp.expression = 'int(utls.is_pivot(high,3))'
"""
toml = """
type = 'custom'
subtype = 'expression'
on_confirmed_only = true
cp.expression = 'int(utls.is_pivot(high,3))'
"""
res, val = get_archived_runner_details_byID(runner_id)
if res < 0:
print("error fetching runner")
print(res)
detail = RunArchiveDetail(**val)
res, toml_parsed = parse_toml_string(toml)
if res < 0:
print("invalid tml",res, toml)
print(toml_parsed)
#toml_parsed = AttributeDict(**toml_parsed)
# for i in toml_parsed["stratvars"]["indicators"]:
# break
ind: InstantIndicator = InstantIndicator(name="testind", toml=toml)
result, new_ind_values = preview_indicator_byTOML(id=runner_id, indicator=ind)
if result < 0:
print("error", result, val)
# detail.indicators[0]
price_series = np.array(detail.bars["vwap"])
new_ind_value = np.array(new_ind_values)
#price_series = detail.bars["vwap"]
#timestamps = detail.bars["time"]
# Plot the price series with local maxima and minima
plt.figure(figsize=(10, 6))
plt.plot(range(len(price_series)), price_series, label='Price')
plt.plot(range(len(new_ind_value)), new_ind_value, label='Indicator')
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Price Series with Local Maxima and Minima')
plt.legend()
plt.show()

19
testy/templatetest.py Normal file
View File

@ -0,0 +1,19 @@
import numpy as np
import matplotlib.pyplot as plt
from v2realbot.controller.services import get_archived_runner_details_byID
from v2realbot.common.model import RunArchiveDetail
# Generate sample price data
timestamps = np.arange('2023-10-27', '2023-10-28', dtype='datetime64[s]')
price = 100 + np.arange(100) * 0.5
id = "e74b5d35-6552-4dfc-ba59-2eda215af292"
res, val = get_archived_runner_details_byID(id)
if res < 0:
print(res)
detail = RunArchiveDetail(**val)
# detail.indicators[0]
price = detail.bars["vwap"]
timestamps = detail.bars["time"]

124
testy/testsuppressmedium.py Normal file
View File

@ -0,0 +1,124 @@
import numpy as np
import matplotlib.pyplot as plt
from v2realbot.controller.services import get_archived_runner_details_byID
from v2realbot.common.model import RunArchiveDetail
from scipy.signal import argrelextrema
import mplfinance
id = "e74b5d35-6552-4dfc-ba59-2eda215af292"
res, val = get_archived_runner_details_byID(id)
if res < 0:
print(res)
detail = RunArchiveDetail(**val)
# detail.indicators[0]
price_series = np.array(detail.bars["vwap"])
df = {}
highs = np.array(detail.bars["high"])
lows = np.array(detail.bars["low"])
np_high = np.array(detail.bars["high"])
np_low = np.array(detail.bars["low"])
price_series = detail.bars["vwap"]
timestamps = detail.bars["time"]
prices = []
#TODO pridat k indikatorum convert to numpy, abych mohl pouzivat numpy operace v expressionu
# func = "prices[-1] if np.all(prices[-1] > prices[-2:]) else 0"
# #func = "prices[-2] if len(prices) >= 3 and prices[-2] > prices[-3] and prices[-2] > prices[-1] else None"
# for price in price_series:
# prices.append(price)
# print(eval(func))
class Sup_Res_Finder():
def __init__(self, s=None):
if s is None:
self.s = np.mean(np.diff(np.concatenate([[np.nan], np.highs, [np.nan]], axis=0)))
else:
self.s = s
def isSupport(self, lows, i):
support = lows[i] < lows[i-1] and lows[i] < lows[i+1] \
and lows[i+1] < lows[i+2] and lows[i-1] < lows[i-2]
return support
def isResistance(self, highs, i):
resistance = highs[i] > highs[i-1] and highs[i] > highs[i+1] \
and highs[i+1] > highs[i+2] and highs[i-1] > highs[i-2]
return resistance
def find_levels(self, highs, lows):
levels = []
for i in range(2, len(lows) - 2):
if self.isSupport(lows, i):
l = lows[i]
if not np.any([abs(l - x) < self.s for x in levels]):
levels.append((i, l))
elif self.isResistance(highs, i):
l = highs[i]
if not np.any([abs(l - x) < self.s for x in levels]):
levels.append((i, l))
return levels
def plot_ohlc_with_support_resistance(bars, s=None):
highs = np.array(bars['high'])
lows = np.array(bars['low'])
finder = Sup_Res_Finder(s=s)
levels = finder.find_levels(highs, lows)
fig, ax = plt.subplots()
# Plot the candlesticks
ax.plot(bars['time'], highs, color='green', linestyle='-', linewidth=0.8)
ax.plot(bars['time'], lows, color='red', linestyle='-', linewidth=0.8)
ax.fill_between(bars['time'], highs, lows, color='green' if highs[0] > lows[0] else 'red', alpha=0.5)
# Plot the support and resistance levels
for level in levels:
ax.hlines(level[1], level[0] - 0.5, level[0] + 0.5, color='black', linewidth=1)
ax.set_xlabel('Time')
ax.set_ylabel('Price')
ax.set_title('OHLC Chart with Support and Resistance Levels')
plt.show()
plot_ohlc_with_support_resistance(detail.bars, 0.05)
# print(price_series)
# # Find local maxima and minima using the optimized function.
# maxima_indices = argrelextrema(price_series, np.greater)[0]
# minima_indices = argrelextrema(price_series, np.less)[0]
# print(maxima_indices)
# print(minima_indices)
# # # Find local maxima and minima
# # maxima_indices = argrelextrema(price_series, np.greater)[0]
# # minima_indices = argrelextrema(price_series, np.less)[0]
# Plot the price series with local maxima and minima
# plt.figure(figsize=(10, 6))
# plt.plot(range(len(price_series)), price_series, label='Price Series')
# plt.scatter(maxima_indices, price_series[maxima_indices], color='r', label='Local Maxima', zorder=5)
# plt.scatter(minima_indices, price_series[minima_indices], color='g', label='Local Minima', zorder=5)
# plt.xlabel('Time')
# plt.ylabel('Price')
# plt.title('Price Series with Local Maxima and Minima')
# plt.legend()
# plt.show()
# # Print the indices of local maxima and minima
# print("Local Maxima Indices:", maxima_indices)
# print("Local Minima Indices:", minima_indices)

23
testy/vectorbt/test.py Normal file
View File

@ -0,0 +1,23 @@
import vectorbt as vb
class ShortOnCloseBreakoutStrategy:
def init(self):
self.last_close = self.data.close[-1]
def next(self):
# Enter a short position when the price is below the last day's close
if self.data.close < self.last_close:
self.sell()
# Exit the short position after 10 ticks
elif self.data.close > self.last_close + 10:
self.buy()
# Create a backtest object
#backtest = vb.Backtest(ShortOnCloseBreakoutStrategy())
# Load the closing prices for the assets in the portfolio
close = vb.YFData.download('AAPL', start='2023-01-01').get('Close')
print(close)
# Backtest the strategy

51
testy/volatilitytest.py Normal file
View File

@ -0,0 +1,51 @@
import numpy as np
import matplotlib.pyplot as plt
from v2realbot.controller.services import get_archived_runner_details_byID
from v2realbot.common.model import RunArchiveDetail
# Generate sample price data
timestamps = np.arange('2023-10-27', '2023-10-28', dtype='datetime64[s]')
price = 100 + np.arange(100) * 0.5
id = "e74b5d35-6552-4dfc-ba59-2eda215af292"
res, val = get_archived_runner_details_byID(id)
if res < 0:
print(res)
detail = RunArchiveDetail(**val)
# detail.indicators[0]
price = detail.bars["vwap"]
timestamps = detail.bars["time"]
# Calculate the standard deviation of price changes over a specified time interval
def calculate_volatility(price, window):
volatility = np.zeros_like(price)
for i in range(window, len(price)):
volatility[i] = np.std(price[i - window: i])
return volatility
# Set a threshold for the indicator
threshold = 0.4
# Identify breakout points based on the threshold
def identify_breakouts(volatility, threshold):
return volatility > threshold
# Plot the price data and the volatility breakout points
def plot_data(timestamps, price, breakout_points):
plt.figure(figsize=(12, 6))
plt.plot(timestamps, price, label='Price')
breakout_timestamps = timestamps[np.where(breakout_points)[0]]
breakout_prices = price[np.where(breakout_points)[0]]
plt.scatter(breakout_timestamps, breakout_prices, color='r', label='Volatility Breakout')
plt.xlabel('Time')
plt.ylabel('Price')
plt.title('Intraday Volatility Breakout Indicator')
plt.legend()
plt.show()
# Applying the functions
window = 30
volatility = calculate_volatility(price, window)
breakout_points = identify_breakouts(volatility, threshold)
plot_data(timestamps, price, breakout_points)