mercredi 12 juillet 2017

Create random stock data in numpy between fixed range and with max high and low

I made the following function. It generates random stock data between a specified range with a max overflow.

import numpy as np
def generateRandomStockDataInRange(length, start, end, maxOverFlow=0.3, randomness=0.5):
    if(start >= end):
        high = start + (start*maxOverFlow)
        low = end - (end*maxOverFlow)
    else:
        high = end + (end*maxOverFlow)
        low = start - (start*maxOverFlow)

    data_np = (np.random.random(length) -randomness).cumsum()
    data_np *= (high - low) / (data_np.max() - data_np.min())
    data_np += np.linspace(start - data_np[0], end - data_np[-1], len(data_np))

    return data_np

then the function can be called like this:

import matplotlib.pyplot as plt
random_stock_data = generateRandomStockDataInRange(200, 60, 105)
plt.figure()
plt.plot(range(random_stock_data.shape[0]), random_stock_data)
plt.show()
plt.close()

There are two things about this function which i would like to improve but don't know how.

  1. Although i specify how much higher or lower it can go overflow, it still sometimes goes much higher or much lower than that. What would be the cause of that and how can it be corrected?

  2. Is there a way to give a percentage for the randomness or the standard deviation? At the moment as you can see i am using a fixed value of 0.5 which if increased or decreased makes the data more or less random. But it is not a percentage and if the length increased or decreased for the same randomness value the standard deviation is changing as well. I would like to give a percentage for the randomness and that should be respected no matter the data length it should be generated for. Basically the question is: How can the function be modified so that no matter the length given and a fixed percentage for the randomness, it should always have the same standard deviation for the entire data?




Aucun commentaire:

Enregistrer un commentaire