Stocks and Shares System - Simulation - math

I'm creating a system for an online game written in an uncommon language (PAWN), similar to C.
I've done some research and found some good information however it's not what I am fully looking for.
In the game there are several industries that I want there to be stocks and shares on.
For example:
Police Department
Fish Market
Housing Market
The volatility of shares is how much swing (+/-) in price change. The higher the volatility, the higher the swing.
In my game the price of each industry will update every minute.
An industry will will bankrupt when it reaches a minimum price per share.
An industry stock will split when it reaches a maximum price per share.
Example:
Police Dept. - (Bankrupt every 220 price updates) (Stock Split every 660 price updates - if it doesn't bankrupt before then)
Fish Industry - (Bankrupt every 1000 price updates) (Stock Split every 220 price updates - if it doesn't bankrupt before then)
House Market - (Never Bankrupts)
I've found a function and altered it to the desired coding language which factors in volatility.
Float:GenerateNextPrice(stockid)
{
if(stockid < 0 || stockid >= sizeof(gStockMarket)) return -1.0; //
new Float:rnd;
MRandFloatRange(0, 1.0, rnd); // generate number, 0 <= x < 1.0
new Float:old_price = gStockMarket[stockid][gCurrentStockPrice];
new Float:volatility = gStockMarket[stockid][gStockVolatility]; // A stable stock would have a volatility number of perhaps 2. A volatility of 10 would show some pretty large swings.
new Float:change_percent = 2 * volatility * rnd;
if (change_percent > volatility)
{
change_percent -= (2 * volatility);
}
new Float:change_amount = (old_price / 100) * change_percent;
new Float:new_price = old_price + change_amount;
return new_price;
}
This function factors in volatility however the higher the volatility the more the swing.
How would I function where it replicates price increases/decreases but after a certain amount of calls it to eventually bankrupt or split as above?
I understand this may be confusing and happy to answer questions.

Related

Power BI DAX - Throughput Board Time Intelligence Metrics with different time zones

Dealing with a bit of a head scratcher. This is more of a logic based issue rather than actual Power BI code. Hoping someone can help out! Here's the scenario:
Site
Shift Num
Start Time
End Time
Daily Output
A
1
8:00AM
4:00PM
10000
B
1
7:00AM
3:00PM
12000
B
2
4:00PM
2:00AM
7000
C
1
6:00AM
2:00PM
5000
This table contains the sites as well as their respective shift times. The master table above is part of an effort in order to capture throughput data from each of the following sites. This master table is connected to tables with a running log of output for each site and shift like so:
Site
Shift Number
Output
Timestamp
A
1
2500
9:45 AM
A
1
4200
11:15 AM
A
1
5600
12:37 PM
A
1
7500
2:15 PM
So there is a one-to-many relationship between the master table and these child throughput tables. The goal is to create use a gauge chart with the following metrics:
Value: Latest Throughput Value (Latest Output in Child Table)
Maximum Value: Throughput Target for the Day (Shift Target in Master Table)
Target Value: Time-dependent project target
i.e. if we are halfway through Site A's shift 1, we should be at 5000 units: (time passed in shift / total shift time) * shift output
if the shift is currently in non-working hours, then the target value = maximum value
Easy enough, but the problem we are facing is the target value erroring for shifts that cross into the next day (i.e. Site B's shift 2).
The shift times are stored as date-independent time values. Here's the code for the measure to get the target value:
Var CurrentTime = HOUR(UTCNOW()) * 60 + MINUTE(UTCNOW())
VAR ShiftStart = HOUR(MAX('mtb MasterTableUTC'[ShiftStartTimeUTC])) * 60 + MINUTE(MAX('mtb MasterTableUTC'[ShiftStartTimeUTC]))
VAR ShiftEnd = HOUR(MAX('mtb MasterTableUTC'[ShiftEndTimeUTC])) * 60 + MINUTE(MAX('mtb MasterTableUTC'[ShiftEndTimeUTC]))
VAR ShiftDiff = ShiftEnd - ShiftStart
Return
IF(CurrentTime > ShiftEnd || CurrentTime < ShiftStart, MAX('mtb MasterTableUTC'[OutputTarget]),
( (CurrentTime - ShiftStart) / ShiftDiff) * MAX('mtb MasterTableUTC'[OutputTarget]))
Basically, if the current time is outside the range of the shift, it should have the target value equal the total shift target, but if it is in the shift time, it calculates it as a ratio of time passed within the shift. This does not work with shifts that cross midnight as the shift end time value is technically earlier than the shift start time value. Any ideas on how to modify the measure to account for these shifts?

Which is best way to convert currency price from other currency

I am working on NodeJS project where i have All EUR currency, and i need to find another price from EUR
Example: There are two currency that values I have EURUSD and EURAED.
I need to find USDAED, Formula: EURAED/EURUSD = USDAED
But the close price must be equal or between HIGH & LOW prices but after calculation its changes. Formula work with a single price, not if it has open,high,low and close price
Problem:
Many generated currency close price is less than Low or high then High.
First tick, High is high, then next tick, high less than last high. (Once high go high, it will never go down until day end)
Question:
Which is the correct way to find currency prices from other currencies?
Example find USDAED by using EUR market.
Example 2: find CADJPY by using USD market
Note: Excel example just for your reference.
You're trying to cross through the EUR, so for USD/AED the answer is:
On LHS buy USD / sell EUR and sell AED / buy EUR
On RHS sell USD / buy EUR and buy AED / sell EUR
Where the EUR cancels out. However the currencies have to be quoted so that happens. To get USDAED you are asking for a price expressed as # AED per 1 USD. So it is EURAED / EURUSD.
Which is what you've done. The thing is the high for EURUSD has nothing to do with the high for EURAED they are totally unrelated. It makes mathematical sense that when calculating a cross currency Z from base pairs Y / X the limits for the base pairs X and Y are not necessarily the limit for a cross pair Z. The limits (high of the day) for the unrelated base pairs will have happened at different times of day.
Here's a primer on FX calculations (disclaimer: I wrote this some time ago).

Solving for a list price when given purchase price and discount %

(Purchase Price - price paid by reseller)
(List Price - price sold for by reseller)
(Discount - percent discount for reseller)
For example, if an item has a list price of $100, and a purchase price of $75, the discount can be calculated by:
Discount = (List - Purchase)/List
Discount = (100 - 75)/100
Discount = .25 or 25%
I'm looking for the most simplified function to solve when either the List Price or Purchase Price is missing, here is what I have:
1. Calculate List Price using Purchase Price and Discount
List = -(Cost / (Discount - 1))
2. Calculate Purchase Price using List Price and Discount
Cost = List - (List * Discount)
Is there any shorter way to calculate this/simplify it more?
How much simpler should that be? Both your formulas are already reasonably simple but a bit unusual. I'd say that a more standard way is
List = Cost / (1 - Discount)
and
Cost = List * (1 - Discount)
which clearly shows they are reverse to each other.

Trouble with Loop in R - there must be a better way?

I am new to R, and trying to get a handle on things for a school project.
The idea is to model a simple and hypothetical electricity generation/storage system which uses only solar panels and battery storage to meet energy demand. The aim is, given a predetermined storage capacity, to select the least amount of solar paneling that ensures that demand will be satisfied on every day of the year. I have a full-year of daily data - solar insolation figures that determine how productive panels will be, day-time electricity demand, and night-time electricity demand. Surplus generation during the day is stored in batteries, up to the predetermined limit, and then discharged at night to meet demand.
I have written a simple R program, f(x), where x is the amount of solar paneling that is installed. Like the battery-storage parameter, it is invariant over the entire year.
After creating new variables for the total power output per day and total excess power produced per day and adding these as columns 4 and 5 to the original data frame, the program creates two new vectors "batterystartvector" and "batterymidvector," which respectively indicate the battery level at the start of each day and at the midpoint, between day and night.
The program loops over each day (row) in the data frame, and:
(1) Credits the excess power that is produced (column 5) to the storage system up to the predetermined limit (7500 Megawatt hours in my example) - which is then stored in "batterymidvector."
(4) Subtracts the night demand (column 3) from the total just registered in "batterymidvector" to determine how much energy there will be in storage at the start of the next day, and stores this figure in "batterystartvector."
(5) Repeats for all 365 days.
Ultimately, my aim is to use an optimization package, such as DEoptimr, to determine the lowest value for x that ensures that demand is satisfied on all days - that is that no values in either "batterymidvector" or "batterystartvector" are ever negative.
Since every entry in the two battery vectors is dependent on prior entries, I cannot figure out how to write a program that does not use a 'for' loop. But surely there must be a simpler and less clunky way.
Here is the code:
library(DEoptimR)
setwd("C:/Users/User/Desktop/Thesis Stuffs/R Programs")
data <- read.csv("optdata1.csv", header=TRUE)
#x is pv installed and y is pumped-storage capacity
#default is that system starts with complete pumped reservoir
f <- function(x) {
data$output <<- (data$insolation*x)/1000
data$daybalance <<- data$output - data$day
batterystartvector <<- vector(mode="numeric",length="365")
batterystartvector[1] <<- c(7500)
batterymidvector <<- vector(mode="numeric", length="366")
for(i in 1:nrow(data)) {
#charging up
batterymidvector[i] <<- min(batterystartvector[i] + data[i,5], 7500)
#depleting
batterystartvector[i+1] <<- (batterymidvector[i] - data[i,3])
}
}

Calculate average return of strategy

Scenario (using quantstrat, blotter and portfolioanalytics)
I have 10k initial equity
I have a strategy that i want to backtest over 3000 symbol universe (stocks)
Let say the strategy is a simple MA crossover
Every time i get a buy crossover I buy 10k worth of stock and close position
on the sell crossover
For backtest purpose the strategy can trade without any portfolio restriction,
therefore i may be holding 100+ positions at any point in time, therefore the
initial equity shouldn't be considered.
I want to know the AVERAGE return of this strategy over all trades.
In reality if i only had 10k i would only be able to be in one trade at once, but i would like know statisctally what the average return would be.
I then want to compare this with the stock index benchmark.
Do i SUM or MEAN the return stream of each symbol
Is it the return of the portfolio, does this take into account the initial
equity? - i don't want the return to be as a percentage of the initial equity
or consider how may symbols are trading.
I'll add an example strategy when i get time, but the solution to the problem is:
#get the portfolio returns
instRets <- PortfReturns(account.st)
#for each column, NA the values where there is no return, because when the values are averaged out, you don't want 0's to be included in the calculation
# if there are no signals in the strategy, you will invest money elsewhere rather than just leaving lying around. Therefore you only calculate the returns #when the strategy is ACTIVE
for (i in 1:ncol(instRets)){
instRets[,i][instRets[,i] == 0] <- NA
}
#this will give you the average return when the strategy is active, if there are 100 trades on, you want the average return during that period.
portfRets <- xts(rowMeans(instRets, na.rm = T), order.by = index(instRets))
portfRets <- portfRets[!is.na(portfRets)]
Now you can compare the strategy with a benchmark SPY for example. If the strategy has alpha you can use a balancing rule to apply funds to the strategy when signals arise or keep invested in the index when there are no signals.
As far to my knowledge the returns analysis built into blotter uses the initial equity to work out returns, therefor invest the same amount in each trade as you have for initial equity. 10k initial equity, 10k per trade.

Resources