Which is best way to convert currency price from other currency - math

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).

Related

Is there a math formula to calculate the following math problem. ( days of spending based on income )

I would like to learn how to calculate the following in the most efficient way possible. i guess there is a math function existing that could do that. right now i am using google sheet functions. but any programming language will do.
problem: We have 37950 $ We have a daily income of 532 $. -> for how many days in a row can we spend 2700$ in others words, how many days before the bankroll is under 2700$?
current state. now, of course starting money is good for 14 days. then in 14 days we earn around 7473 (its ok to pretend we earn fractions). thus prolonging the streak by close to 3 days., etc, etc. is there an elegant formula to calculate this ?
thanks.
Your daily loss is 2700 - 532 = 2168.
Your wealth divided by your daily loss gives you the number of days.
37950 / 2168 = 17.5046125461
17 days.
Let's check. In 17 days you'll have 37,950 + (17 * 532) - (17 * 2700) = 1094
The next day you're broke.
Subtract a day if same-day earnings can't be spent.

Stocks and Shares System - Simulation

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.

I have a question about optimizing the shifts scheduling (supply) to fulfill the hourly demand as much as possible in R

I would like to create an automatic shift planning tool through R with optimizing the demand.
Given that I have demand by hourly basis. I need to assign shift based on the demand in order to meet the demand as much as possible. I currently have 6 shifts (will list below).
The objective:
to minimize the difference between total supply and total demand
to minimize the difference between supply and demand for each hour
Constraint:
shift constraint - each hour might have several shifts available to be assigned
max capacity - I have the cap of supply. the sum of total shift cant exceed the cap for each hour.
Example:
Hourly_Demand <- c(22,19,18,21,22,28,34,39,44,50,49,47,44,43,50,56,56,61,59,59,46,39,34,26)
Cap <- c(46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,)
Shift_available <-
24Hr shift(A) - c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
16Hr shift(B) - c(0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0)
16Hr shift(C) - c(0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0)
16Hr shift(D) - c(0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0)
16Hr shift(E) - c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
8Hr shift(F) - c(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0)
8Hr shift(G) - c(0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0)
The Timeline for Shift_Available is like c(7am , 8am , 9am , 10am , .... , 23pm , 0am , 1am , ... , 5am , 6am) . And '1' means it is available at that specific hour and contribution for 1 supply.
For example, if I assign 1 x shift(A) , 1 x shift(B), then the supply at 7am will be 1 , the supply at 10am will be 2 with the demand is 21 based on the demand vector.
May I have your opinion on how to make this out. Many thanks and apologize if there is anything explained not that clear.

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