pricegenerator.PriceGenerator

PriceGenerator is the platform for generating prices similar to real stock prices, but you can control the statistics of their distribution. Generates chain of candlesticks with predefined statistical parameters, return Pandas DataFrame or saving as .CSV-file with OHLCV-candlestick in every string. Use PriceGenerator to generate synthetic data to test your trading strategy.

In additional you can view some statistical and probability parameters of generated or loaded prices.

Sample example:

Chart

gift

uLogger = <Logger PriceGenerator-UniLogger (DEBUG)>
GOOGLE_TEMPLATE_J2 = '{# This template based on Jinja markup language: https://jinja.palletsprojects.com/en/latest/ #}\n<!DOCTYPE html>\n<html>\n\n<head>\n <title>{{ title }}</title>\n <meta charset="utf-8">\n <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>\n <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>\n <script type="text/javascript">google.charts.load(\'current\', {\'packages\': [\'corechart\']});</script>\n <style type="text/css">\n #preloader {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #FFFFFF;\n z-index: 99;\n }\n #status {\n width: 300px;\n height: 150px;\n position: absolute;\n left: 50%;\n top: 50%;\n background-image: url(https://raw.githubusercontent.com/niklausgerber/PreLoadMe/master/img/status.gif);\n background-repeat: no-repeat;\n background-position: left;\n margin: -100px 0 0 -100px;\n font-family: "Segoe UI", "Frutiger", "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", "Arial", sans-serif;\n font-size: 14px;\n }\n pre {\n font-family: "Lucida Console", sans-serif;\n font-size: 11px;\n padding: 0;\n border-width: 0 0 0 0;\n }\n table {\n font-family: "Segoe UI", "Frutiger", "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", "Arial", sans-serif;\n font-size: 12px;\n border-spacing: 0;\n text-align: left;\n background: white;\n width: 100%;\n }\n th {\n border-radius: 10px 10px 10px 10px;\n border-style: solid;\n border-width: 0 1px 1px 0;\n border-color: white;\n padding: 6px;\n vertical-align: middle;\n padding-left: 1em;\n background: #E6E6E6;\n height: 50px;\n }\n td {\n border-radius: 10px 10px 10px 10px;\n border-style: solid;\n border-width: 0 1px 1px 0;\n border-color: white;\n padding: 6px;\n vertical-align: top;\n padding-left: 1em;\n background: white;\n }\n </style>\n <script>\n function drawChartCandlesticks(candlesData) {\n var chartOptions = {\n legend: "none",\n titlePosition: "in",\n chartArea: {width: "100%", height: "100%"},\n fontSize: 11,\n candlestick: {\n fallingColor: {stroke: "#000000", strokeWidth: 1, fill: "#999999"},\n risingColor: {stroke: "#000000", strokeWidth: 1, fill: "#FFFFFF"},\n },\n colors: ["#000000"],\n hAxis: {textPosition: "none"},\n vAxis: {textPosition: "in", textStyle: {fontSize: 12}},\n }\n if (typeof candlesData !== "undefined") {\n var data = google.visualization.arrayToDataTable(candlesData, true);\n var chart = new google.visualization.CandlestickChart(document.getElementById("candlestickChart"));\n chart.draw(data, chartOptions);\n }\n }\n </script>\n</head>\n\n\n<body onload="drawChartCandlesticks({{ candlesData }})">\n\n\n<!-- Preloader -->\n<script>\n $(window).on(\'load\', function() {\n $(\'#status\').fadeOut(\'slow\');\n $(\'#preloader\').fadeOut(\'slow\');\n })\n</script>\n<div id="preloader">\n <div id="status">Wait...</div>\n</div>\n\n\n<!-- Chart part -->\n\n<table id="chart">\n <tr>\n <th style="width: 80%;">\n <b>{{ title }}</b>\n </th>\n <th>\n <b>Info</b>\n </th>\n </tr>\n <tr>\n <td>\n <div id="candlestickChart" style="height: 800px; width: 100%;"></div>\n </td>\n <td>\n {% for line in info %}\n <pre>{{ line }}</pre>\n {% endfor %}\n </td>\n </tr>\n</table>\n\n\n<!-- Footer -->\n\n<table>\n <tr>\n <th><b>Generated by <a href="https://github.com/Tim55667757/PriceGenerator">PriceGenerator</a></b></th>\n </tr>\n</table>\n\n\n</body>\n\n</html>\n'
class PriceGenerator:

This class implements methods to generation of prices statistically similar to real ones.

Model generated: OHLCV-candlesticks (open, high, low, close, volume).

PriceGenerator()

Main class init.

prices

Generated or loaded prices will be available in this Pandas DataFrame variable.

csvHeaders

Headers in .CSV-file. Default: ["date", "time", "open", "high", "low", "close", "volume"].

dfHeaders

Headers in Pandas DataFrame. Default: ["datetime", "open", "high", "low", "close", "volume"].

sep

Separator in csv - file. Default: ,

j2template

Full path to custom jinja2 html-template file (e.g. google_template_example.j2) or just set here a long multi-string variable. Default: GOOGLE_TEMPLATE_J2 is a multi-string variable with internal template.

j2model

Dictionary of variables for jinja2 template. If None then used default variables for internal GOOGLE_TEMPLATE_J2

ticker

Some fake ticker name. Default: Test.

timeframe

Time delta between two neighbour candles. Default: timedelta(hours=1).

timeStart

First date and time for candles chain.

horizon

Candlesticks count in generated or loaded chain of prices, must be >= 5. Default: None (means auto-detect length of chain if loaded from file).

trendSplit

Set different trends, e.g. trendSplit="/\-" means that generated candles has uptrend at first part, next downtrend and then no trend. Used only together with splitCount variable. Also, you can use words: up, down, no or chars: u, d, n with the hyphen symbol as separator, e.g. trendSplit=up-down-no-up, trendSplit=u-d-n-u etc. Default: "", empty string mean that will be used random trend directions.

splitCount

Set candles count in different trends, e.g. splitCount=[5, 10, 15] means that generated candles has 3 trends with 5, 10 and 15 candles in chain, with sum must be equal to horizon. Used only together with trendSplit variable. Default: [], empty list mean that will be used random candles count in trends.

maxClose

Maximum of close prices must be >= minClose. Default: random in interval (70, 90).

minClose

Minimum of close prices must be <= maxClose. Default: random in interval (60, 70).

initClose

First candle close price value. If None then used random number in interval between minClose and maxClose. Default: None.

maxOutlier

Maximum size of outliers. If None then used value (maxClose - minClose) / 10. Default: None.

maxCandleBody

Maximum of candle body sizes: abs(open - close). If None then used value maxOutlier * 90%. Default: None.

upCandlesProb

Probability that next candle is up. Default: 0.5 (means 50% of probability).

outliersProb

Outlier probability (price tails). Default: 0.03 (means 3% of probability).

trendDeviation

Relative deviation for trend detection. "NO trend" if (1st_close - last_close) / 1st_close <= self.trendDeviation. Default: 0.005 (means ±0.5% of price deviation).

maxVolume

Maximum of generated trade volumes. Default: random in interval [1, 100000].

stat: dict

Some statistics available after candles loaded or generated.

precision

Signs after comma.

zigZagDeviation

Relative deviation to detection next points used by Zig-Zag indicator. Default: 0.03 (means 3% of price deviation).

@staticmethod
def FormattedDelta(tDelta: datetime.timedelta, fmt: str) -> str:

Pretty format for timedelta objects.

Example: FormattedDelta(timedelta(days=2, hours=3, minutes=15, seconds=35), "{days} days {hours}:{minutes}:{seconds}") -> "2 days 3:15:35".

Returns

timedelta object formatted as a string.

def DetectPrecision( self, examples: Union[numpy.ndarray, pandas.core.series.Series, list]) -> int:

Auto-detect precision from example values. E.g. 0.123 -> 3, 0.12345 -> 5 and so on. This method change precision variable after detect precision.

See also about statistics.mode: https://docs.python.org/3.9/library/statistics.html#statistics.mode Changed in Python version >= 3.8: Now mode() method handles multimodal datasets by returning the first mode encountered. Previously, it raised StatisticsError when more than one mode was found.

Parameters
  • examples: chain with examples of float values.
def DetectTimeframe(self) -> datetime.timedelta:

Auto-detect time delta between last two neighbour candles.

Returns

timedelta object, also saved to timeframe.

def LoadFromFile(self, fileName: str) -> pandas.core.frame.DataFrame:

Create Pandas OHLCV-model from CSV-file. Default columns in CSV-file are ["date", "time", "open", "high", "low", "close", "volume"].

Parameters
  • fileName: path to CSV-file with OHLCV columns.
Returns

Pandas DataFrame.

def SaveToFile(self, fileName: str) -> None:

Save Pandas OHLCV model to CSV-file.

Parameters
  • fileName: path to CSV-file.
@staticmethod
def GetTrend( firstClose: float, lastClose: float, trendDeviation: float = 0.005) -> str:

Get string with trend: "UP trend", "DOWN trend" or "NO trend".

Parameters
  • firstClose: close of first candle.
  • lastClose: close of last candle.
  • trendDeviation: relative deviation for trend detection, 0.005 mean ±0.5% by default.
Returns

string with trend direction "NO trend", "UP trend" or "DOWN trend".

@staticmethod
def ZigZagFilter( datetimes: pandas.core.series.Series, values: Union[pandas.core.series.Series, list], deviation: float) -> pandas.core.frame.DataFrame:

This method filter input data as Zig-Zag indicator: when input value of candlestick price (e.g. close price) is difference with next values with define percent then this point is a point of Zig-Zag indicator.

Parameters
  • datetimes: input Pandas Series with datetime values.
  • values: input Pandas Series or list, e.g. list of closes values of candlesticks.
  • deviation: float number in [0, 1] interval is a relative difference between i and i + 1 values to set as Zig-Zag point.
Returns

Pandas DataFrame with two Series of filtered data "datetimes": filtered_datetimes and "filtered": filtered_values.

def GetStatistics(self) -> list[str]:

Calculates statistics of candles chain.

Returns

list with text in Markdown format with statistics.

def Generate(self) -> pandas.core.frame.DataFrame:

Main method to generating prices.

:return Pandas DataFrame object with OHLCV-candlestick in every row and also saving it to the prices.

def RenderBokeh( self, fileName: Optional[str] = 'index.html', viewInBrowser: bool = False, darkTheme: bool = False, markers: Optional[pandas.core.frame.DataFrame] = None, lines: Optional[list[pandas.core.frame.DataFrame]] = None, title: Optional[str] = None, width: Optional[int] = 1800, height: Optional[int] = 940, showControlsOnChart: bool = True, showStatOnChart: bool = True, inline: bool = False) -> Optional[gridplot]:

Rendering prices from Pandas DataFrame as OHLCV Bokeh chart of candlesticks and save it to HTML-file. Pandas DataFrame in prices variable must contain "datetime", "open", "high", "low", "close" and "volume" columns.

See also: https://docs.bokeh.org/en/latest/docs/gallery/candlestick.html

Parameters
  • fileName: HTML-file path to save Bokeh chart. index.html by default.
  • viewInBrowser: If True, then immediately opens HTML chart in browser after rendering. False by default.
  • darkTheme: chart theme. False by default, mean that will be used light theme, False mean dark theme.
  • markers: Pandas DataFrame with additional markers that will be placed on main series. None by default. Marker is a custom symbol, example: ×, ↓ or ↑. Dataframe with markers must contain at least two columns. There are datetime with date and time and some markers columns (markersUpper, markersCenter or markersLower). Length of markers series must be equal to the length of main candles series.
  • lines: list with custom series, where additional chart-lines will place on main series. None by default. Line data must contain at least two columns. There are datetime with date and time and custom_line_name with y-coordinates. Length of the chart-line dataframes must be equal to the length of main candle series.
  • title: specific chart title. If None, then used auto-generated title. None by default.
  • width: chart width. If None, then used auto-width. 1800 px by default.
  • height: chart height. If None, then used auto-height. 940 px by default.
  • showControlsOnChart: enable controls block in legend to hide/show some elements on chart, True by default.
  • showStatOnChart: show statistics block on chart, True (by default) mean that will be calculating additional series, like as Trend and Average Points. And some classical indicators, like as SMA, HMA, VWMA, Bollinger Bands, Parabolic Stop and Reverse, Alligator and Zig-Zag indicator. Warning! Calculate statistic takes more time. If you want to decrease chart rendering time, then set this parameter to False.
  • inline: if True, then output chart in Jupyter Notebook cell. False by default.
Returns

bokeh.layouts.gridplot with all layouts objects or None.

def RenderGoogle( self, fileName: str = 'index.html', viewInBrowser: bool = False, title: Optional[str] = None) -> None:

Rendering prices from Pandas DataFrame as non-interactive Google Candlestick chart and save it to HTML-file.

See also: https://developers.google.com/chart/interactive/docs/gallery/candlestickchart

Parameters
  • fileName: HTML-file path to save Google Candlestick chart.
  • viewInBrowser: If True, then immediately opens html in browser after rendering.
  • title: specific chart title. If None, then used auto-generated title. None by default.
def ParseArgs():

This function get and parse command line keys.

def Main():

Main function for work with PriceGenerator in the console.

See examples:

gift